repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/event.rs
futures/src/event.rs
//! Listen to runtime events. use crate::MaybeSend; use crate::core::event::{self, Event}; use crate::core::window; use crate::subscription::{self, Subscription}; /// Returns a [`Subscription`] to all the ignored runtime events. /// /// This subscription will notify your application of any [`Event`] that was /// not captured by any widget. pub fn listen() -> Subscription<Event> { listen_with(|event, status, _window| match status { event::Status::Ignored => Some(event), event::Status::Captured => None, }) } /// Creates a [`Subscription`] that listens and filters all the runtime events /// with the provided function, producing messages accordingly. /// /// This subscription will call the provided function for every [`Event`] /// handled by the runtime. If the function: /// /// - Returns `None`, the [`Event`] will be discarded. /// - Returns `Some` message, the `Message` will be produced. pub fn listen_with<Message>( f: fn(Event, event::Status, window::Id) -> Option<Message>, ) -> Subscription<Message> where Message: 'static + MaybeSend, { #[derive(Hash)] struct EventsWith; subscription::filter_map((EventsWith, f), move |event| match event { subscription::Event::Interaction { event: Event::Window(window::Event::RedrawRequested(_)), .. } | subscription::Event::SystemThemeChanged(_) | subscription::Event::PlatformSpecific(_) => None, subscription::Event::Interaction { window, event, status, } => f(event, status, window), }) } /// Creates a [`Subscription`] that produces a message for every runtime event, /// including the redraw request events. /// /// **Warning:** This [`Subscription`], if unfiltered, may produce messages in /// an infinite loop. pub fn listen_raw<Message>( f: fn(Event, event::Status, window::Id) -> Option<Message>, ) -> Subscription<Message> where Message: 'static + MaybeSend, { #[derive(Hash)] struct RawEvents; subscription::filter_map((RawEvents, f), move |event| match event { subscription::Event::Interaction { window, event, status, } => f(event, status, window), subscription::Event::SystemThemeChanged(_) | subscription::Event::PlatformSpecific(_) => { None } }) } /// Creates a [`Subscription`] that notifies of custom application URL /// received from the system. /// /// _**Note:** Currently, it only triggers on macOS and the executable needs to be properly [bundled]!_ /// /// [bundled]: https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW19 pub fn listen_url() -> Subscription<String> { #[derive(Hash)] struct ListenUrl; subscription::filter_map(ListenUrl, move |event| match event { subscription::Event::PlatformSpecific(subscription::PlatformSpecific::MacOS( subscription::MacOS::ReceivedUrl(url), )) => Some(url), _ => None, }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/lib.rs
futures/src/lib.rs
//! Asynchronous tasks for GUI programming, inspired by Elm. //! //! ![The foundations of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/foundations.png?raw=true) #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] pub use futures; pub use iced_core as core; mod maybe; mod runtime; pub mod backend; pub mod event; pub mod executor; pub mod keyboard; pub mod stream; pub mod subscription; pub use executor::Executor; pub use maybe::{MaybeSend, MaybeSync}; pub use platform::*; pub use runtime::Runtime; pub use subscription::Subscription; #[cfg(not(target_arch = "wasm32"))] mod platform { /// A boxed static future. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub type BoxFuture<T> = futures::future::BoxFuture<'static, T>; /// A boxed static stream. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub type BoxStream<T> = futures::stream::BoxStream<'static, T>; /// Boxes a stream. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub fn boxed_stream<T, S>(stream: S) -> BoxStream<T> where S: futures::Stream<Item = T> + Send + 'static, { futures::stream::StreamExt::boxed(stream) } } #[cfg(target_arch = "wasm32")] mod platform { /// A boxed static future. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub type BoxFuture<T> = futures::future::LocalBoxFuture<'static, T>; /// A boxed static stream. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub type BoxStream<T> = futures::stream::LocalBoxStream<'static, T>; /// Boxes a stream. /// /// - On native platforms, it needs a `Send` requirement. /// - On the Web platform, it does not need a `Send` requirement. pub fn boxed_stream<T, S>(stream: S) -> BoxStream<T> where S: futures::Stream<Item = T> + 'static, { futures::stream::StreamExt::boxed_local(stream) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend.rs
futures/src/backend.rs
//! The underlying implementations of the `iced_futures` contract! pub mod null; #[cfg(not(target_arch = "wasm32"))] pub mod native; #[cfg(target_arch = "wasm32")] pub mod wasm; pub mod default;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/subscription.rs
futures/src/subscription.rs
//! Listen to external events in your application. mod tracker; pub use tracker::Tracker; use crate::core::event; use crate::core::theme; use crate::core::window; use crate::futures::Stream; use crate::{BoxStream, MaybeSend}; use std::any::TypeId; use std::hash::Hash; /// A subscription event. #[derive(Debug, Clone, PartialEq)] pub enum Event { /// A user interacted with a user interface in a window. Interaction { /// The window holding the interface of the interaction. window: window::Id, /// The [`Event`] describing the interaction. /// /// [`Event`]: event::Event event: event::Event, /// The [`event::Status`] of the interaction. status: event::Status, }, /// The system theme has changed. SystemThemeChanged(theme::Mode), /// A platform specific event. PlatformSpecific(PlatformSpecific), } /// A platform specific event #[derive(Debug, Clone, PartialEq, Eq)] pub enum PlatformSpecific { /// A MacOS specific event MacOS(MacOS), } /// Describes an event specific to MacOS #[derive(Debug, Clone, PartialEq, Eq)] pub enum MacOS { /// Triggered when the app receives an URL from the system /// /// _**Note:** For this event to be triggered, the executable needs to be properly [bundled]!_ /// /// [bundled]: https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW19 ReceivedUrl(String), } /// A stream of runtime events. /// /// It is the input of a [`Subscription`]. pub type EventStream = BoxStream<Event>; /// The hasher used for identifying subscriptions. pub type Hasher = rustc_hash::FxHasher; /// A request to listen to external events. /// /// Besides performing async actions on demand with `Task`, most /// applications also need to listen to external events passively. /// /// A [`Subscription`] is normally provided to some runtime, like a `Task`, /// and it will generate events as long as the user keeps requesting it. /// /// For instance, you can use a [`Subscription`] to listen to a `WebSocket` /// connection, keyboard presses, mouse events, time ticks, etc. /// /// # The Lifetime of a [`Subscription`] /// Much like a [`Future`] or a [`Stream`], a [`Subscription`] does not produce any effects /// on its own. For a [`Subscription`] to run, it must be returned to the iced runtime—normally /// in the `subscription` function of an `application` or a `daemon`. /// /// When a [`Subscription`] is provided to the runtime for the first time, the runtime will /// start running it asynchronously. Running a [`Subscription`] consists in building its underlying /// [`Stream`] and executing it in an async runtime. /// /// Therefore, you can think of a [`Subscription`] as a "stream builder". It simply represents a way /// to build a certain [`Stream`] together with some way to _identify_ it. /// /// Identification is important because when a specific [`Subscription`] stops being returned to the /// iced runtime, the runtime will kill its associated [`Stream`]. The runtime uses the identity of a /// [`Subscription`] to keep track of it. /// /// This way, iced allows you to declaratively __subscribe__ to particular streams of data temporarily /// and whenever necessary. /// /// ``` /// # mod iced { /// # pub mod time { /// # pub use iced_futures::backend::default::time::every; /// # pub use std::time::{Duration, Instant}; /// # } /// # /// # pub use iced_futures::Subscription; /// # } /// use iced::time::{self, Duration, Instant}; /// use iced::Subscription; /// /// struct State { /// timer_enabled: bool, /// } /// /// fn subscription(state: &State) -> Subscription<Instant> { /// if state.timer_enabled { /// time::every(Duration::from_secs(1)) /// } else { /// Subscription::none() /// } /// } /// ``` /// /// [`Future`]: std::future::Future #[must_use = "`Subscription` must be returned to the runtime to take effect; normally in your `subscription` function."] pub struct Subscription<T> { recipes: Vec<Box<dyn Recipe<Output = T>>>, } impl<T> Subscription<T> { /// Returns an empty [`Subscription`] that will not produce any output. pub fn none() -> Self { Self { recipes: Vec::new(), } } /// Returns a [`Subscription`] that will call the given function to create and /// asynchronously run the given [`Stream`]. /// /// # Creating an asynchronous worker with bidirectional communication /// You can leverage this helper to create a [`Subscription`] that spawns /// an asynchronous worker in the background and establish a channel of /// communication with an `iced` application. /// /// You can achieve this by creating an `mpsc` channel inside the closure /// and returning the `Sender` as a `Message` for the `Application`: /// /// ``` /// # mod iced { /// # pub use iced_futures::Subscription; /// # pub use iced_futures::futures; /// # pub use iced_futures::stream; /// # } /// use iced::futures::channel::mpsc; /// use iced::futures::sink::SinkExt; /// use iced::futures::Stream; /// use iced::stream; /// use iced::Subscription; /// /// pub enum Event { /// Ready(mpsc::Sender<Input>), /// WorkFinished, /// // ... /// } /// /// enum Input { /// DoSomeWork, /// // ... /// } /// /// fn some_worker() -> impl Stream<Item = Event> { /// stream::channel(100, async |mut output| { /// // Create channel /// let (sender, mut receiver) = mpsc::channel(100); /// /// // Send the sender back to the application /// output.send(Event::Ready(sender)).await; /// /// loop { /// use iced_futures::futures::StreamExt; /// /// // Read next input sent from `Application` /// let input = receiver.select_next_some().await; /// /// match input { /// Input::DoSomeWork => { /// // Do some async work... /// /// // Finally, we can optionally produce a message to tell the /// // `Application` the work is done /// output.send(Event::WorkFinished).await; /// } /// } /// } /// }) /// } /// /// fn subscription() -> Subscription<Event> { /// Subscription::run(some_worker) /// } /// ``` /// /// Check out the [`websocket`] example, which showcases this pattern to maintain a `WebSocket` /// connection open. /// /// [`websocket`]: https://github.com/iced-rs/iced/tree/master/examples/websocket pub fn run<S>(builder: fn() -> S) -> Self where S: Stream<Item = T> + MaybeSend + 'static, T: 'static, { from_recipe(Runner { data: builder, spawn: |builder, _| builder(), }) } /// Returns a [`Subscription`] that will create and asynchronously run the /// given [`Stream`]. /// /// Both the `data` and the function pointer will be used to uniquely identify /// the [`Subscription`]. pub fn run_with<D, S>(data: D, builder: fn(&D) -> S) -> Self where D: Hash + 'static, S: Stream<Item = T> + MaybeSend + 'static, T: 'static, { from_recipe(Runner { data: (data, builder), spawn: |(data, builder), _| builder(data), }) } /// Batches all the provided subscriptions and returns the resulting /// [`Subscription`]. pub fn batch(subscriptions: impl IntoIterator<Item = Subscription<T>>) -> Self { Self { recipes: subscriptions .into_iter() .flat_map(|subscription| subscription.recipes) .collect(), } } /// Adds a value to the [`Subscription`] context. /// /// The value will be part of the identity of a [`Subscription`]. pub fn with<A>(self, value: A) -> Subscription<(A, T)> where T: 'static, A: std::hash::Hash + Clone + Send + Sync + 'static, { struct With<A, B> { recipe: Box<dyn Recipe<Output = A>>, value: B, } impl<A, B> Recipe for With<A, B> where A: 'static, B: 'static + std::hash::Hash + Clone + Send + Sync, { type Output = (B, A); fn hash(&self, state: &mut Hasher) { std::any::TypeId::of::<B>().hash(state); self.value.hash(state); self.recipe.hash(state); } fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { use futures::StreamExt; let value = self.value; Box::pin( self.recipe .stream(input) .map(move |element| (value.clone(), element)), ) } } Subscription { recipes: self .recipes .into_iter() .map(|recipe| { Box::new(With { recipe, value: value.clone(), }) as Box<dyn Recipe<Output = (A, T)>> }) .collect(), } } /// Transforms the [`Subscription`] output with the given function. /// /// The closure provided must be a non-capturing closure. pub fn map<F, A>(self, f: F) -> Subscription<A> where T: 'static, F: Fn(T) -> A + MaybeSend + Clone + 'static, A: 'static, { const { check_zero_sized::<F>(); } struct Map<A, B, F> where F: Fn(A) -> B + 'static, { recipe: Box<dyn Recipe<Output = A>>, mapper: F, } impl<A, B, F> Recipe for Map<A, B, F> where A: 'static, B: 'static, F: Fn(A) -> B + 'static + MaybeSend, { type Output = B; fn hash(&self, state: &mut Hasher) { TypeId::of::<F>().hash(state); self.recipe.hash(state); } fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { use futures::StreamExt; Box::pin(self.recipe.stream(input).map(self.mapper)) } } Subscription { recipes: self .recipes .into_iter() .map(|recipe| { Box::new(Map { recipe, mapper: f.clone(), }) as Box<dyn Recipe<Output = A>> }) .collect(), } } /// Transforms the [`Subscription`] output with the given function, yielding only /// values only when the function returns `Some(A)`. /// /// The closure provided must be a non-capturing closure. pub fn filter_map<F, A>(mut self, f: F) -> Subscription<A> where T: MaybeSend + 'static, F: Fn(T) -> Option<A> + MaybeSend + Clone + 'static, A: MaybeSend + 'static, { const { check_zero_sized::<F>(); } struct FilterMap<A, B, F> where F: Fn(A) -> Option<B> + 'static, { recipe: Box<dyn Recipe<Output = A>>, mapper: F, } impl<A, B, F> Recipe for FilterMap<A, B, F> where A: 'static, B: 'static + MaybeSend, F: Fn(A) -> Option<B> + MaybeSend, { type Output = B; fn hash(&self, state: &mut Hasher) { TypeId::of::<F>().hash(state); self.recipe.hash(state); } fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { use futures::StreamExt; use futures::future; let mapper = self.mapper; Box::pin( self.recipe .stream(input) .filter_map(move |a| future::ready(mapper(a))), ) } } Subscription { recipes: self .recipes .drain(..) .map(|recipe| { Box::new(FilterMap { recipe, mapper: f.clone(), }) as Box<dyn Recipe<Output = A>> }) .collect(), } } /// Returns the amount of recipe units in this [`Subscription`]. pub fn units(&self) -> usize { self.recipes.len() } } /// Creates a [`Subscription`] from a [`Recipe`] describing it. pub fn from_recipe<T>(recipe: impl Recipe<Output = T> + 'static) -> Subscription<T> { Subscription { recipes: vec![Box::new(recipe)], } } /// Returns the different recipes of the [`Subscription`]. pub fn into_recipes<T>(subscription: Subscription<T>) -> Vec<Box<dyn Recipe<Output = T>>> { subscription.recipes } impl<T> std::fmt::Debug for Subscription<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Subscription").finish() } } /// The description of a [`Subscription`]. /// /// A [`Recipe`] is the internal definition of a [`Subscription`]. It is used /// by runtimes to run and identify subscriptions. You can use it to create your /// own! pub trait Recipe { /// The events that will be produced by a [`Subscription`] with this /// [`Recipe`]. type Output; /// Hashes the [`Recipe`]. /// /// This is used by runtimes to uniquely identify a [`Subscription`]. fn hash(&self, state: &mut Hasher); /// Executes the [`Recipe`] and produces the stream of events of its /// [`Subscription`]. fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output>; } /// Creates a [`Subscription`] from a hashable id and a filter function. pub fn filter_map<I, F, T>(id: I, f: F) -> Subscription<T> where I: Hash + 'static, F: Fn(Event) -> Option<T> + MaybeSend + 'static, T: 'static + MaybeSend, { from_recipe(Runner { data: id, spawn: |_, events| { use futures::future; use futures::stream::StreamExt; events.filter_map(move |event| future::ready(f(event))) }, }) } struct Runner<I, F, S, T> where F: FnOnce(&I, EventStream) -> S, S: Stream<Item = T>, { data: I, spawn: F, } impl<I, F, S, T> Recipe for Runner<I, F, S, T> where I: Hash + 'static, F: FnOnce(&I, EventStream) -> S, S: Stream<Item = T> + MaybeSend + 'static, { type Output = T; fn hash(&self, state: &mut Hasher) { std::any::TypeId::of::<I>().hash(state); self.data.hash(state); } fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { crate::boxed_stream((self.spawn)(&self.data, input)) } } const fn check_zero_sized<T>() { if std::mem::size_of::<T>() != 0 { panic!( "The Subscription closure provided is not non-capturing. \ Closures given to Subscription::map or filter_map cannot \ capture external variables. If you need to capture state, \ consider using Subscription::with." ); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/runtime.rs
futures/src/runtime.rs
//! Run commands and keep track of subscriptions. use crate::subscription; use crate::{BoxStream, Executor, MaybeSend}; use futures::{Sink, SinkExt, channel::mpsc}; use std::marker::PhantomData; /// A batteries-included runtime of commands and subscriptions. /// /// If you have an [`Executor`], a [`Runtime`] can be leveraged to run any /// `Command` or [`Subscription`] and get notified of the results! /// /// [`Subscription`]: crate::Subscription #[derive(Debug)] pub struct Runtime<Executor, Sender, Message> { executor: Executor, sender: Sender, subscriptions: subscription::Tracker, _message: PhantomData<Message>, } impl<Executor, Sender, Message> Runtime<Executor, Sender, Message> where Executor: self::Executor, Sender: Sink<Message, Error = mpsc::SendError> + Unpin + MaybeSend + Clone + 'static, Message: MaybeSend + 'static, { /// Creates a new empty [`Runtime`]. /// /// You need to provide: /// - an [`Executor`] to spawn futures /// - a `Sender` implementing `Sink` to receive the results pub fn new(executor: Executor, sender: Sender) -> Self { Self { executor, sender, subscriptions: subscription::Tracker::new(), _message: PhantomData, } } /// Runs the given closure inside the [`Executor`] of the [`Runtime`]. /// /// See [`Executor::enter`] to learn more. pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R { self.executor.enter(f) } /// Runs a future to completion in the current thread within the [`Runtime`]. #[cfg(not(target_arch = "wasm32"))] pub fn block_on<T>(&mut self, future: impl Future<Output = T>) -> T { self.executor.block_on(future) } /// Runs a [`Stream`] in the [`Runtime`] until completion. /// /// The resulting `Message`s will be forwarded to the `Sender` of the /// [`Runtime`]. /// /// [`Stream`]: BoxStream pub fn run(&mut self, stream: BoxStream<Message>) { use futures::{FutureExt, StreamExt}; let sender = self.sender.clone(); let future = stream.map(Ok).forward(sender).map(|result| match result { Ok(()) => (), Err(error) => { log::warn!("Stream could not run until completion: {error}"); } }); self.executor.spawn(future); } /// Sends a message concurrently through the [`Runtime`]. pub fn send(&mut self, message: Message) { let mut sender = self.sender.clone(); self.executor.spawn(async move { let _ = sender.send(message).await; }); } /// Tracks a [`Subscription`] in the [`Runtime`]. /// /// It will spawn new streams or close old ones as necessary! See /// [`Tracker::update`] to learn more about this! /// /// [`Tracker::update`]: subscription::Tracker::update /// [`Subscription`]: crate::Subscription pub fn track( &mut self, recipes: impl IntoIterator<Item = Box<dyn subscription::Recipe<Output = Message>>>, ) { let Runtime { executor, subscriptions, sender, .. } = self; let futures = executor.enter(|| subscriptions.update(recipes.into_iter(), sender.clone())); for future in futures { executor.spawn(future); } } /// Broadcasts an event to all the subscriptions currently alive in the /// [`Runtime`]. /// /// See [`Tracker::broadcast`] to learn more. /// /// [`Tracker::broadcast`]: subscription::Tracker::broadcast pub fn broadcast(&mut self, event: subscription::Event) { self.subscriptions.broadcast(event); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/executor.rs
futures/src/executor.rs
//! Choose your preferred executor to power a runtime. use crate::MaybeSend; /// A type that can run futures. pub trait Executor: Sized { /// Creates a new [`Executor`]. fn new() -> Result<Self, futures::io::Error> where Self: Sized; /// Spawns a future in the [`Executor`]. fn spawn(&self, future: impl Future<Output = ()> + MaybeSend + 'static); /// Runs a future to completion in the current thread within the [`Executor`]. #[cfg(not(target_arch = "wasm32"))] fn block_on<T>(&self, future: impl Future<Output = T>) -> T; /// Runs the given closure inside the [`Executor`]. /// /// Some executors, like `tokio`, require some global state to be in place /// before creating futures. This method can be leveraged to set up this /// global state, call a function, restore the state, and obtain the result /// of the call. fn enter<R>(&self, f: impl FnOnce() -> R) -> R { f() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/maybe.rs
futures/src/maybe.rs
#[cfg(not(target_arch = "wasm32"))] mod platform { /// An extension trait that enforces `Send` only on native platforms. /// /// Useful for writing cross-platform async code! pub trait MaybeSend: Send {} impl<T> MaybeSend for T where T: Send {} /// An extension trait that enforces `Sync` only on native platforms. /// /// Useful for writing cross-platform async code! pub trait MaybeSync: Sync {} impl<T> MaybeSync for T where T: Sync {} } #[cfg(target_arch = "wasm32")] mod platform { /// An extension trait that enforces `Send` only on native platforms. /// /// Useful for writing cross-platform async code! pub trait MaybeSend {} impl<T> MaybeSend for T {} /// An extension trait that enforces `Sync` only on native platforms. /// /// Useful for writing cross-platform async code! pub trait MaybeSync {} impl<T> MaybeSync for T {} } pub use platform::{MaybeSend, MaybeSync};
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/keyboard.rs
futures/src/keyboard.rs
//! Listen to keyboard events. use crate::core; use crate::core::keyboard::Event; use crate::subscription::{self, Subscription}; /// Returns a [`Subscription`] that listens to ignored keyboard events. pub fn listen() -> Subscription<Event> { #[derive(Hash)] struct Listen; subscription::filter_map(Listen, move |event| match event { subscription::Event::Interaction { event: core::Event::Keyboard(event), status: core::event::Status::Ignored, .. } => Some(event), _ => None, }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/subscription/tracker.rs
futures/src/subscription/tracker.rs
use crate::subscription::{Event, Hasher, Recipe}; use crate::{BoxFuture, MaybeSend}; use futures::channel::mpsc; use futures::sink::{Sink, SinkExt}; use rustc_hash::FxHashMap; use std::hash::Hasher as _; /// A registry of subscription streams. /// /// If you have an application that continuously returns a [`Subscription`], /// you can use a [`Tracker`] to keep track of the different recipes and keep /// its executions alive. /// /// [`Subscription`]: crate::Subscription #[derive(Debug, Default)] pub struct Tracker { subscriptions: FxHashMap<u64, Execution>, } #[derive(Debug)] pub struct Execution { _cancel: futures::channel::oneshot::Sender<()>, listener: Option<futures::channel::mpsc::Sender<Event>>, } impl Tracker { /// Creates a new empty [`Tracker`]. pub fn new() -> Self { Self { subscriptions: FxHashMap::default(), } } /// Updates the [`Tracker`] with the given [`Subscription`]. /// /// A [`Subscription`] can cause new streams to be spawned or old streams /// to be closed. /// /// The [`Tracker`] keeps track of these streams between calls to this /// method: /// /// - If the provided [`Subscription`] contains a new [`Recipe`] that is /// currently not being run, it will spawn a new stream and keep it alive. /// - On the other hand, if a [`Recipe`] is currently in execution and the /// provided [`Subscription`] does not contain it anymore, then the /// [`Tracker`] will close and drop the relevant stream. /// /// It returns a list of futures that need to be spawned to materialize /// the [`Tracker`] changes. /// /// [`Recipe`]: crate::subscription::Recipe /// [`Subscription`]: crate::Subscription pub fn update<Message, Receiver>( &mut self, recipes: impl Iterator<Item = Box<dyn Recipe<Output = Message>>>, receiver: Receiver, ) -> Vec<BoxFuture<()>> where Message: 'static + MaybeSend, Receiver: 'static + Sink<Message, Error = mpsc::SendError> + Unpin + MaybeSend + Clone, { use futures::stream::StreamExt; let mut futures: Vec<BoxFuture<()>> = Vec::new(); let mut alive = std::collections::HashSet::new(); for recipe in recipes { let id = { let mut hasher = Hasher::default(); recipe.hash(&mut hasher); hasher.finish() }; let _ = alive.insert(id); if self.subscriptions.contains_key(&id) { continue; } let (cancel, mut canceled) = futures::channel::oneshot::channel(); // TODO: Use bus if/when it supports async let (event_sender, event_receiver) = futures::channel::mpsc::channel(100); let mut receiver = receiver.clone(); let mut stream = recipe.stream(event_receiver.boxed()); let future = async move { loop { let select = futures::future::select(&mut canceled, stream.next()); match select.await { futures::future::Either::Left(_) | futures::future::Either::Right((None, _)) => break, futures::future::Either::Right((Some(message), _)) => { let _ = receiver.send(message).await; } } } }; let _ = self.subscriptions.insert( id, Execution { _cancel: cancel, listener: if event_sender.is_closed() { None } else { Some(event_sender) }, }, ); futures.push(Box::pin(future)); } self.subscriptions.retain(|id, _| alive.contains(id)); futures } /// Broadcasts an event to the subscriptions currently alive. /// /// A subscription's [`Recipe::stream`] always receives a stream of events /// as input. This stream can be used by some subscription to listen to /// shell events. /// /// This method publishes the given event to all the subscription streams /// currently open. /// /// [`Recipe::stream`]: crate::subscription::Recipe::stream pub fn broadcast(&mut self, event: Event) { self.subscriptions .values_mut() .filter_map(|connection| connection.listener.as_mut()) .for_each(|listener| { if let Err(error) = listener.try_send(event.clone()) { log::warn!("Error sending event to subscription: {error:?}"); } }); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/native.rs
futures/src/backend/native.rs
//! Backends that are only available in native platforms: Windows, macOS, or Linux. #[cfg(feature = "tokio")] pub mod tokio; #[cfg(feature = "smol")] pub mod smol; #[cfg(feature = "thread-pool")] pub mod thread_pool;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/default.rs
futures/src/backend/default.rs
//! A default, cross-platform backend. //! //! - On native platforms, it will use: //! - `backend::native::tokio` when the `tokio` feature is enabled. //! - `backend::native::smol` when the `smol` feature is enabled. //! - `backend::native::thread_pool` when the `thread-pool` feature is enabled. //! - `backend::null` otherwise. //! //! - On Wasm, it will use `backend::wasm::wasm_bindgen`. #[cfg(not(target_arch = "wasm32"))] mod platform { #[cfg(feature = "tokio")] pub use crate::backend::native::tokio::*; #[cfg(all(feature = "smol", not(feature = "tokio"),))] pub use crate::backend::native::smol::*; #[cfg(all(feature = "thread-pool", not(any(feature = "tokio", feature = "smol"))))] pub use crate::backend::native::thread_pool::*; #[cfg(not(any(feature = "tokio", feature = "smol", feature = "thread-pool")))] pub use crate::backend::null::*; } #[cfg(target_arch = "wasm32")] mod platform { pub use crate::backend::wasm::wasm_bindgen::*; } pub use platform::*;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/null.rs
futures/src/backend/null.rs
//! A backend that does nothing! use crate::MaybeSend; /// An executor that drops all the futures, instead of spawning them. #[derive(Debug)] pub struct Executor; impl crate::Executor for Executor { fn new() -> Result<Self, futures::io::Error> { Ok(Self) } fn spawn(&self, _future: impl Future<Output = ()> + MaybeSend + 'static) {} #[cfg(not(target_arch = "wasm32"))] fn block_on<T>(&self, _future: impl Future<Output = T>) -> T { unimplemented!() } } pub mod time { //! Listen and react to time. }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/wasm.rs
futures/src/backend/wasm.rs
//! Backends that are only available on Wasm targets. pub mod wasm_bindgen;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/native/tokio.rs
futures/src/backend/native/tokio.rs
//! A `tokio` backend. /// A `tokio` executor. pub type Executor = tokio::runtime::Runtime; impl crate::Executor for Executor { fn new() -> Result<Self, futures::io::Error> { tokio::runtime::Runtime::new() } #[allow(clippy::let_underscore_future)] fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { let _ = tokio::runtime::Runtime::spawn(self, future); } fn enter<R>(&self, f: impl FnOnce() -> R) -> R { let _guard = tokio::runtime::Runtime::enter(self); f() } fn block_on<T>(&self, future: impl Future<Output = T>) -> T { self.block_on(future) } } pub mod time { //! Listen and react to time. use crate::MaybeSend; use crate::core::time::{Duration, Instant}; use crate::subscription::Subscription; use futures::stream; /// Returns a [`Subscription`] that produces messages at a set interval. /// /// The first message is produced after a `duration`, and then continues to /// produce more messages every `duration` after that. pub fn every(duration: Duration) -> Subscription<Instant> { Subscription::run_with(duration, |duration| { use futures::stream::StreamExt; let start = tokio::time::Instant::now() + *duration; let mut interval = tokio::time::interval_at(start, *duration); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let stream = { futures::stream::unfold(interval, |mut interval| async move { Some((interval.tick().await, interval)) }) }; stream.map(tokio::time::Instant::into_std).boxed() }) } /// Returns a [`Subscription`] that runs the given async function at a /// set interval; producing the result of the function as output. pub fn repeat<F, T>(f: fn() -> F, interval: Duration) -> Subscription<T> where F: Future<Output = T> + MaybeSend + 'static, T: MaybeSend + 'static, { Subscription::run_with((f, interval), |(f, interval)| { let f = *f; let interval = *interval; stream::unfold(0, move |i| async move { if i > 0 { tokio::time::sleep(interval).await; } Some((f().await, i + 1)) }) }) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/native/thread_pool.rs
futures/src/backend/native/thread_pool.rs
//! A `ThreadPool` backend. /// A thread pool executor for futures. pub type Executor = futures::executor::ThreadPool; impl crate::Executor for Executor { fn new() -> Result<Self, futures::io::Error> { futures::executor::ThreadPool::new() } fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { self.spawn_ok(future); } fn block_on<T>(&self, future: impl Future<Output = T>) -> T { futures::executor::block_on(future) } } pub mod time { //! Listen and react to time. }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/native/smol.rs
futures/src/backend/native/smol.rs
//! A `smol` backend. /// A `smol` executor. #[derive(Debug)] pub struct Executor; impl crate::Executor for Executor { fn new() -> Result<Self, futures::io::Error> { Ok(Self) } fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { smol::spawn(future).detach(); } fn block_on<T>(&self, future: impl Future<Output = T>) -> T { smol::block_on(future) } } pub mod time { //! Listen and react to time. use crate::subscription::{self, Hasher, Subscription}; /// Returns a [`Subscription`] that produces messages at a set interval. /// /// The first message is produced after a `duration`, and then continues to /// produce more messages every `duration` after that. pub fn every(duration: std::time::Duration) -> Subscription<std::time::Instant> { subscription::from_recipe(Every(duration)) } #[derive(Debug)] struct Every(std::time::Duration); impl subscription::Recipe for Every { type Output = std::time::Instant; fn hash(&self, state: &mut Hasher) { use std::hash::Hash; std::any::TypeId::of::<Self>().hash(state); self.0.hash(state); } fn stream( self: Box<Self>, _input: subscription::EventStream, ) -> futures::stream::BoxStream<'static, Self::Output> { use futures::stream::StreamExt; smol::Timer::interval(self.0).boxed() } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/backend/wasm/wasm_bindgen.rs
futures/src/backend/wasm/wasm_bindgen.rs
//! A `wasm-bindgen-futures` backend. /// A `wasm-bindgen-futures` executor. #[derive(Debug)] pub struct Executor; impl crate::Executor for Executor { fn new() -> Result<Self, futures::io::Error> { Ok(Self) } fn spawn(&self, future: impl futures::Future<Output = ()> + 'static) { wasm_bindgen_futures::spawn_local(future); } } pub mod time { //! Listen and react to time. use crate::subscription::Subscription; use wasmtimer::std::Instant; /// Returns a [`Subscription`] that produces messages at a set interval. /// /// The first message is produced after a `duration`, and then continues to /// produce more messages every `duration` after that. pub fn every(duration: std::time::Duration) -> Subscription<Instant> { Subscription::run_with(duration, |duration| { use futures::stream::StreamExt; let mut interval = wasmtimer::tokio::interval(*duration); interval.set_missed_tick_behavior(wasmtimer::tokio::MissedTickBehavior::Skip); let stream = { futures::stream::unfold(interval, |mut interval| async move { Some((interval.tick().await, interval)) }) }; stream.boxed() }) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/pixels.rs
core/src/pixels.rs
/// An amount of logical pixels. /// /// Normally used to represent an amount of space, or the size of something. /// /// This type is normally asked as an argument in a generic way /// (e.g. `impl Into<Pixels>`) and, since `Pixels` implements `From` both for /// `f32` and `u16`, you should be able to provide both integers and float /// literals as needed. #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)] pub struct Pixels(pub f32); impl Pixels { /// Zero pixels. pub const ZERO: Self = Self(0.0); } impl From<f32> for Pixels { fn from(amount: f32) -> Self { Self(amount) } } impl From<u32> for Pixels { fn from(amount: u32) -> Self { Self(amount as f32) } } impl From<Pixels> for f32 { fn from(pixels: Pixels) -> Self { pixels.0 } } impl std::ops::Add for Pixels { type Output = Pixels; fn add(self, rhs: Self) -> Self { Pixels(self.0 + rhs.0) } } impl std::ops::Add<f32> for Pixels { type Output = Pixels; fn add(self, rhs: f32) -> Self { Pixels(self.0 + rhs) } } impl std::ops::Mul for Pixels { type Output = Pixels; fn mul(self, rhs: Self) -> Self { Pixels(self.0 * rhs.0) } } impl std::ops::Mul<f32> for Pixels { type Output = Pixels; fn mul(self, rhs: f32) -> Self { Pixels(self.0 * rhs) } } impl std::ops::Div for Pixels { type Output = Pixels; fn div(self, rhs: Self) -> Self { Pixels(self.0 / rhs.0) } } impl std::ops::Div<f32> for Pixels { type Output = Pixels; fn div(self, rhs: f32) -> Self { Pixels(self.0 / rhs) } } impl std::ops::Div<u32> for Pixels { type Output = Pixels; fn div(self, rhs: u32) -> Self { Pixels(self.0 / rhs as f32) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/shadow.rs
core/src/shadow.rs
use crate::{Color, Vector}; /// A shadow. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Shadow { /// The color of the shadow. pub color: Color, /// The offset of the shadow. pub offset: Vector, /// The blur radius of the shadow. pub blur_radius: f32, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/settings.rs
core/src/settings.rs
//! Configure your application. use crate::{Font, Pixels}; use std::borrow::Cow; /// The settings of an iced program. #[derive(Debug, Clone)] pub struct Settings { /// The identifier of the application. /// /// If provided, this identifier may be used to identify the application or /// communicate with it through the windowing system. pub id: Option<String>, /// The fonts to load on boot. pub fonts: Vec<Cow<'static, [u8]>>, /// The default [`Font`] to be used. /// /// By default, it uses [`Family::SansSerif`](crate::font::Family::SansSerif). pub default_font: Font, /// The text size that will be used by default. /// /// The default value is `16.0`. pub default_text_size: Pixels, /// If set to true, the renderer will try to perform antialiasing for some /// primitives. /// /// Enabling it can produce a smoother result in some widgets, like the /// `canvas` widget, at a performance cost. /// /// By default, it is enabled. pub antialiasing: bool, /// Whether or not to attempt to synchronize rendering when possible. /// /// Disabling it can improve rendering performance on some platforms. /// /// By default, it is enabled. pub vsync: bool, } impl Default for Settings { fn default() -> Self { Self { id: None, fonts: Vec::new(), default_font: Font::default(), default_text_size: Pixels(16.0), antialiasing: true, vsync: true, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/element.rs
core/src/element.rs
use crate::layout; use crate::mouse; use crate::overlay; use crate::renderer; use crate::widget; use crate::widget::tree::{self, Tree}; use crate::{ Border, Clipboard, Color, Event, Layout, Length, Rectangle, Shell, Size, Vector, Widget, }; use std::borrow::Borrow; /// A generic [`Widget`]. /// /// It is useful to build composable user interfaces that do not leak /// implementation details in their __view logic__. /// /// If you have a [built-in widget], you should be able to use `Into<Element>` /// to turn it into an [`Element`]. /// /// [built-in widget]: crate::widget pub struct Element<'a, Message, Theme, Renderer> { widget: Box<dyn Widget<Message, Theme, Renderer> + 'a>, } impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> { /// Creates a new [`Element`] containing the given [`Widget`]. pub fn new(widget: impl Widget<Message, Theme, Renderer> + 'a) -> Self where Renderer: crate::Renderer, { Self { widget: Box::new(widget), } } /// Returns a reference to the [`Widget`] of the [`Element`], pub fn as_widget(&self) -> &dyn Widget<Message, Theme, Renderer> { self.widget.as_ref() } /// Returns a mutable reference to the [`Widget`] of the [`Element`], pub fn as_widget_mut(&mut self) -> &mut dyn Widget<Message, Theme, Renderer> { self.widget.as_mut() } /// Applies a transformation to the produced message of the [`Element`]. /// /// This method is useful when you want to decouple different parts of your /// UI and make them __composable__. /// /// # Example /// Imagine we want to use [our counter](index.html#usage). But instead of /// showing a single counter, we want to display many of them. We can reuse /// the `Counter` type as it is! /// /// We use composition to model the __state__ of our new application: /// /// ``` /// # mod counter { /// # pub struct Counter; /// # } /// use counter::Counter; /// /// struct ManyCounters { /// counters: Vec<Counter>, /// } /// ``` /// /// We can store the state of multiple counters now. However, the /// __messages__ we implemented before describe the user interactions /// of a __single__ counter. Right now, we need to also identify which /// counter is receiving user interactions. Can we use composition again? /// Yes. /// /// ``` /// # mod counter { /// # #[derive(Debug, Clone, Copy)] /// # pub enum Message {} /// # } /// #[derive(Debug, Clone, Copy)] /// pub enum Message { /// Counter(usize, counter::Message) /// } /// ``` /// /// We compose the previous __messages__ with the index of the counter /// producing them. Let's implement our __view logic__ now: /// /// ```no_run /// # mod iced { /// # pub use iced_core::Function; /// # pub type Element<'a, Message> = iced_core::Element<'a, Message, iced_core::Theme, ()>; /// # /// # pub mod widget { /// # pub fn row<'a, Message>(iter: impl IntoIterator<Item = super::Element<'a, Message>>) -> super::Element<'a, Message> { /// # unimplemented!() /// # } /// # } /// # } /// # /// # mod counter { /// # #[derive(Debug, Clone, Copy)] /// # pub enum Message {} /// # pub struct Counter; /// # /// # pub type Element<'a, Message> = iced_core::Element<'a, Message, iced_core::Theme, ()>; /// # /// # impl Counter { /// # pub fn view(&self) -> Element<Message> { /// # unimplemented!() /// # } /// # } /// # } /// # /// use counter::Counter; /// /// use iced::widget::row; /// use iced::{Element, Function}; /// /// struct ManyCounters { /// counters: Vec<Counter>, /// } /// /// #[derive(Debug, Clone, Copy)] /// pub enum Message { /// Counter(usize, counter::Message), /// } /// /// impl ManyCounters { /// pub fn view(&self) -> Element<Message> { /// // We can quickly populate a `row` by mapping our counters /// row( /// self.counters /// .iter() /// .map(Counter::view) /// .enumerate() /// .map(|(index, counter)| { /// // Here we turn our `Element<counter::Message>` into /// // an `Element<Message>` by combining the `index` and the /// // message of the `element`. /// counter.map(Message::Counter.with(index)) /// }), /// ) /// .into() /// } /// } /// ``` /// /// Finally, our __update logic__ is pretty straightforward: simple /// delegation. /// /// ``` /// # mod counter { /// # #[derive(Debug, Clone, Copy)] /// # pub enum Message {} /// # pub struct Counter; /// # /// # impl Counter { /// # pub fn update(&mut self, _message: Message) {} /// # } /// # } /// # /// # use counter::Counter; /// # /// # struct ManyCounters { /// # counters: Vec<Counter>, /// # } /// # /// # #[derive(Debug, Clone, Copy)] /// # pub enum Message { /// # Counter(usize, counter::Message) /// # } /// impl ManyCounters { /// pub fn update(&mut self, message: Message) { /// match message { /// Message::Counter(index, counter_msg) => { /// if let Some(counter) = self.counters.get_mut(index) { /// counter.update(counter_msg); /// } /// } /// } /// } /// } /// ``` pub fn map<B>(self, f: impl Fn(Message) -> B + 'a) -> Element<'a, B, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::Renderer + 'a, B: 'a, { Element::new(Map::new(self.widget, f)) } /// Marks the [`Element`] as _to-be-explained_. /// /// The [`Renderer`] will explain the layout of the [`Element`] graphically. /// This can be very useful for debugging your layout! /// /// [`Renderer`]: crate::Renderer pub fn explain<C: Into<Color>>(self, color: C) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::Renderer + 'a, { Element { widget: Box::new(Explain::new(self, color.into())), } } } impl<'a, Message, Theme, Renderer> Borrow<dyn Widget<Message, Theme, Renderer> + 'a> for Element<'a, Message, Theme, Renderer> { fn borrow(&self) -> &(dyn Widget<Message, Theme, Renderer> + 'a) { self.widget.borrow() } } impl<'a, Message, Theme, Renderer> Borrow<dyn Widget<Message, Theme, Renderer> + 'a> for &Element<'a, Message, Theme, Renderer> { fn borrow(&self) -> &(dyn Widget<Message, Theme, Renderer> + 'a) { self.widget.borrow() } } struct Map<'a, A, B, Theme, Renderer> { widget: Box<dyn Widget<A, Theme, Renderer> + 'a>, mapper: Box<dyn Fn(A) -> B + 'a>, } impl<'a, A, B, Theme, Renderer> Map<'a, A, B, Theme, Renderer> { pub fn new<F>( widget: Box<dyn Widget<A, Theme, Renderer> + 'a>, mapper: F, ) -> Map<'a, A, B, Theme, Renderer> where F: 'a + Fn(A) -> B, { Map { widget, mapper: Box::new(mapper), } } } impl<'a, A, B, Theme, Renderer> Widget<B, Theme, Renderer> for Map<'a, A, B, Theme, Renderer> where Renderer: crate::Renderer + 'a, A: 'a, B: 'a, { fn tag(&self) -> tree::Tag { self.widget.tag() } fn state(&self) -> tree::State { self.widget.state() } fn children(&self) -> Vec<Tree> { self.widget.children() } fn diff(&self, tree: &mut Tree) { self.widget.diff(tree); } fn size(&self) -> Size<Length> { self.widget.size() } fn size_hint(&self) -> Size<Length> { self.widget.size_hint() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.widget.layout(tree, renderer, limits) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.widget.operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, B>, viewport: &Rectangle, ) { let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); self.widget.update( tree, event, layout, cursor, renderer, clipboard, &mut local_shell, viewport, ); shell.merge(local_shell, &self.mapper); } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.widget .draw(tree, renderer, theme, style, layout, cursor, viewport); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.widget .mouse_interaction(tree, layout, cursor, viewport, renderer) } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, B, Theme, Renderer>> { let mapper = &self.mapper; self.widget .overlay(tree, layout, renderer, viewport, translation) .map(move |overlay| overlay.map(mapper)) } } struct Explain<'a, Message, Theme, Renderer: crate::Renderer> { element: Element<'a, Message, Theme, Renderer>, color: Color, } impl<'a, Message, Theme, Renderer> Explain<'a, Message, Theme, Renderer> where Renderer: crate::Renderer, { fn new(element: Element<'a, Message, Theme, Renderer>, color: Color) -> Self { Explain { element, color } } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Explain<'_, Message, Theme, Renderer> where Renderer: crate::Renderer, { fn size(&self) -> Size<Length> { self.element.widget.size() } fn size_hint(&self) -> Size<Length> { self.element.widget.size_hint() } fn tag(&self) -> tree::Tag { self.element.widget.tag() } fn state(&self) -> tree::State { self.element.widget.state() } fn children(&self) -> Vec<Tree> { self.element.widget.children() } fn diff(&self, tree: &mut Tree) { self.element.widget.diff(tree); } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.element.widget.layout(tree, renderer, limits) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.element .widget .operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { self.element.widget.update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { fn explain_layout<Renderer: crate::Renderer>( renderer: &mut Renderer, color: Color, layout: Layout<'_>, ) { renderer.fill_quad( renderer::Quad { bounds: layout.bounds(), border: Border { color, width: 1.0, ..Border::default() }, ..renderer::Quad::default() }, Color::TRANSPARENT, ); for child in layout.children() { explain_layout(renderer, color, child); } } self.element .widget .draw(tree, renderer, theme, style, layout, cursor, viewport); renderer.with_layer(Rectangle::INFINITE, |renderer| { explain_layout(renderer, self.color, layout); }); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.element .widget .mouse_interaction(tree, layout, cursor, viewport, renderer) } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.element .widget .overlay(tree, layout, renderer, viewport, translation) } } impl<'a, T, Message, Theme, Renderer> From<Option<T>> for Element<'a, Message, Theme, Renderer> where T: Into<Self>, Renderer: crate::Renderer, { fn from(element: Option<T>) -> Self { struct Void; impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Void where Renderer: crate::Renderer, { fn size(&self) -> Size<Length> { Size { width: Length::Fixed(0.0), height: Length::Fixed(0.0), } } fn layout( &mut self, _tree: &mut Tree, _renderer: &Renderer, _limits: &layout::Limits, ) -> layout::Node { layout::Node::new(Size::ZERO) } fn draw( &self, _tree: &Tree, _renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, _layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { } } element.map(T::into).unwrap_or_else(|| Element::new(Void)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/event.rs
core/src/event.rs
//! Handle events of a user interface. use crate::input_method; use crate::keyboard; use crate::mouse; use crate::touch; use crate::window; /// A user interface event. /// /// _**Note:** This type is largely incomplete! If you need to track /// additional events, feel free to [open an issue] and share your use case!_ /// /// [open an issue]: https://github.com/iced-rs/iced/issues #[derive(Debug, Clone, PartialEq)] pub enum Event { /// A keyboard event Keyboard(keyboard::Event), /// A mouse event Mouse(mouse::Event), /// A window event Window(window::Event), /// A touch event Touch(touch::Event), /// An input method event InputMethod(input_method::Event), } /// The status of an [`Event`] after being processed. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Event`] was **NOT** handled by any widget. Ignored, /// The [`Event`] was handled and processed by a widget. Captured, } impl Status { /// Merges two [`Status`] into one. /// /// `Captured` takes precedence over `Ignored`: /// /// ``` /// use iced_core::event::Status; /// /// assert_eq!(Status::Ignored.merge(Status::Ignored), Status::Ignored); /// assert_eq!(Status::Ignored.merge(Status::Captured), Status::Captured); /// assert_eq!(Status::Captured.merge(Status::Ignored), Status::Captured); /// assert_eq!(Status::Captured.merge(Status::Captured), Status::Captured); /// ``` pub fn merge(self, b: Self) -> Self { match self { Status::Ignored => b, Status::Captured => Status::Captured, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/lib.rs
core/src/lib.rs
//! The core library of [Iced]. //! //! This library holds basic types that can be reused and re-exported in //! different runtime implementations. //! //! ![The foundations of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/foundations.png?raw=true) //! //! [Iced]: https://github.com/iced-rs/iced #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] pub mod alignment; pub mod animation; pub mod border; pub mod clipboard; pub mod event; pub mod font; pub mod gradient; pub mod image; pub mod input_method; pub mod keyboard; pub mod layout; pub mod mouse; pub mod overlay; pub mod padding; pub mod renderer; pub mod svg; pub mod text; pub mod theme; pub mod time; pub mod touch; pub mod widget; pub mod window; mod angle; mod background; mod color; mod content_fit; mod element; mod length; mod pixels; mod point; mod rectangle; mod rotation; mod settings; mod shadow; mod shell; mod size; mod transformation; mod vector; pub use alignment::Alignment; pub use angle::{Degrees, Radians}; pub use animation::Animation; pub use background::Background; pub use border::Border; pub use clipboard::Clipboard; pub use color::Color; pub use content_fit::ContentFit; pub use element::Element; pub use event::Event; pub use font::Font; pub use gradient::Gradient; pub use image::Image; pub use input_method::InputMethod; pub use layout::Layout; pub use length::Length; pub use overlay::Overlay; pub use padding::Padding; pub use pixels::Pixels; pub use point::Point; pub use rectangle::Rectangle; pub use renderer::Renderer; pub use rotation::Rotation; pub use settings::Settings; pub use shadow::Shadow; pub use shell::Shell; pub use size::Size; pub use svg::Svg; pub use text::Text; pub use theme::Theme; pub use transformation::Transformation; pub use vector::Vector; pub use widget::Widget; pub use bytes::Bytes; pub use smol_str::SmolStr; pub use std::convert::Infallible as Never; /// A function that can _never_ be called. /// /// This is useful to turn generic types into anything /// you want by coercing them into a type with no possible /// values. pub fn never<T>(never: Never) -> T { match never {} } /// A trait extension for binary functions (`Fn(A, B) -> O`). /// /// It enables you to use a bunch of nifty functional programming paradigms /// that work well with iced. pub trait Function<A, B, O> { /// Applies the given first argument to a binary function and returns /// a new function that takes the other argument. /// /// This lets you partially "apply" a function—equivalent to currying, /// but it only works with binary functions. If you want to apply an /// arbitrary number of arguments, create a little struct for them. /// /// # When is this useful? /// Sometimes you will want to identify the source or target /// of some message in your user interface. This can be achieved through /// normal means by defining a closure and moving the identifier /// inside: /// /// ```rust /// # let element: Option<()> = Some(()); /// # enum Message { ButtonPressed(u32, ()) } /// let id = 123; /// /// # let _ = { /// element.map(move |result| Message::ButtonPressed(id, result)) /// # }; /// ``` /// /// That's quite a mouthful. [`with`](Self::with) lets you write: /// /// ```rust /// # use iced_core::Function; /// # let element: Option<()> = Some(()); /// # enum Message { ButtonPressed(u32, ()) } /// let id = 123; /// /// # let _ = { /// element.map(Message::ButtonPressed.with(id)) /// # }; /// ``` /// /// Effectively creating the same closure that partially applies /// the `id` to the message—but much more concise! fn with(self, prefix: A) -> impl Fn(B) -> O; } impl<F, A, B, O> Function<A, B, O> for F where F: Fn(A, B) -> O, Self: Sized, A: Clone, { fn with(self, prefix: A) -> impl Fn(B) -> O { move |result| self(prefix.clone(), result) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/svg.rs
core/src/svg.rs
//! Load and draw vector graphics. use crate::{Color, Radians, Rectangle, Size}; use rustc_hash::FxHasher; use std::borrow::Cow; use std::hash::{Hash, Hasher as _}; use std::path::PathBuf; use std::sync::Arc; /// A raster image that can be drawn. #[derive(Debug, Clone, PartialEq)] pub struct Svg<H = Handle> { /// The handle of the [`Svg`]. pub handle: H, /// The [`Color`] filter to be applied to the [`Svg`]. /// /// If some [`Color`] is set, the whole [`Svg`] will be /// painted with it—ignoring any intrinsic colors. /// /// This can be useful for coloring icons programmatically /// (e.g. with a theme). pub color: Option<Color>, /// The rotation to be applied to the image; on its center. pub rotation: Radians, /// The opacity of the [`Svg`]. /// /// 0 means transparent. 1 means opaque. pub opacity: f32, } impl Svg<Handle> { /// Creates a new [`Svg`] with the given handle. pub fn new(handle: impl Into<Handle>) -> Self { Self { handle: handle.into(), color: None, rotation: Radians(0.0), opacity: 1.0, } } /// Sets the [`Color`] filter of the [`Svg`]. pub fn color(mut self, color: impl Into<Color>) -> Self { self.color = Some(color.into()); self } /// Sets the rotation of the [`Svg`]. pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self { self.rotation = rotation.into(); self } /// Sets the opacity of the [`Svg`]. pub fn opacity(mut self, opacity: impl Into<f32>) -> Self { self.opacity = opacity.into(); self } } impl From<&Handle> for Svg { fn from(handle: &Handle) -> Self { Svg::new(handle.clone()) } } /// A handle of Svg data. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Handle { id: u64, data: Arc<Data>, } impl Handle { /// Creates an SVG [`Handle`] pointing to the vector image of the given /// path. pub fn from_path(path: impl Into<PathBuf>) -> Handle { Self::from_data(Data::Path(path.into())) } /// Creates an SVG [`Handle`] from raw bytes containing either an SVG string /// or gzip compressed data. /// /// This is useful if you already have your SVG data in-memory, maybe /// because you downloaded or generated it procedurally. pub fn from_memory(bytes: impl Into<Cow<'static, [u8]>>) -> Handle { Self::from_data(Data::Bytes(bytes.into())) } fn from_data(data: Data) -> Handle { let mut hasher = FxHasher::default(); data.hash(&mut hasher); Handle { id: hasher.finish(), data: Arc::new(data), } } /// Returns the unique identifier of the [`Handle`]. pub fn id(&self) -> u64 { self.id } /// Returns a reference to the SVG [`Data`]. pub fn data(&self) -> &Data { &self.data } } impl<T> From<T> for Handle where T: Into<PathBuf>, { fn from(path: T) -> Handle { Handle::from_path(path.into()) } } impl Hash for Handle { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } /// The data of a vectorial image. #[derive(Clone, Hash, PartialEq, Eq)] pub enum Data { /// File data Path(PathBuf), /// In-memory data /// /// Can contain an SVG string or a gzip compressed data. Bytes(Cow<'static, [u8]>), } impl std::fmt::Debug for Data { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Data::Path(path) => write!(f, "Path({path:?})"), Data::Bytes(_) => write!(f, "Bytes(...)"), } } } /// A [`Renderer`] that can render vector graphics. /// /// [renderer]: crate::renderer pub trait Renderer: crate::Renderer { /// Returns the default dimensions of an SVG for the given [`Handle`]. fn measure_svg(&self, handle: &Handle) -> Size<u32>; /// Draws an SVG with the given [`Handle`], an optional [`Color`] filter, and inside the provided `bounds`. fn draw_svg(&mut self, svg: Svg, bounds: Rectangle, clip_bounds: Rectangle); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/theme.rs
core/src/theme.rs
//! Use the built-in theme and styles. pub mod palette; pub use palette::Palette; use crate::Color; use std::borrow::Cow; use std::fmt; use std::sync::Arc; /// A built-in theme. #[derive(Debug, Clone, PartialEq)] pub enum Theme { /// The built-in light variant. Light, /// The built-in dark variant. Dark, /// The built-in Dracula variant. Dracula, /// The built-in Nord variant. Nord, /// The built-in Solarized Light variant. SolarizedLight, /// The built-in Solarized Dark variant. SolarizedDark, /// The built-in Gruvbox Light variant. GruvboxLight, /// The built-in Gruvbox Dark variant. GruvboxDark, /// The built-in Catppuccin Latte variant. CatppuccinLatte, /// The built-in Catppuccin Frappé variant. CatppuccinFrappe, /// The built-in Catppuccin Macchiato variant. CatppuccinMacchiato, /// The built-in Catppuccin Mocha variant. CatppuccinMocha, /// The built-in Tokyo Night variant. TokyoNight, /// The built-in Tokyo Night Storm variant. TokyoNightStorm, /// The built-in Tokyo Night Light variant. TokyoNightLight, /// The built-in Kanagawa Wave variant. KanagawaWave, /// The built-in Kanagawa Dragon variant. KanagawaDragon, /// The built-in Kanagawa Lotus variant. KanagawaLotus, /// The built-in Moonfly variant. Moonfly, /// The built-in Nightfly variant. Nightfly, /// The built-in Oxocarbon variant. Oxocarbon, /// The built-in Ferra variant: Ferra, /// A [`Theme`] that uses a [`Custom`] palette. Custom(Arc<Custom>), } impl Theme { /// A list with all the defined themes. pub const ALL: &'static [Self] = &[ Self::Light, Self::Dark, Self::Dracula, Self::Nord, Self::SolarizedLight, Self::SolarizedDark, Self::GruvboxLight, Self::GruvboxDark, Self::CatppuccinLatte, Self::CatppuccinFrappe, Self::CatppuccinMacchiato, Self::CatppuccinMocha, Self::TokyoNight, Self::TokyoNightStorm, Self::TokyoNightLight, Self::KanagawaWave, Self::KanagawaDragon, Self::KanagawaLotus, Self::Moonfly, Self::Nightfly, Self::Oxocarbon, Self::Ferra, ]; /// Creates a new custom [`Theme`] from the given [`Palette`]. pub fn custom(name: impl Into<Cow<'static, str>>, palette: Palette) -> Self { Self::custom_with_fn(name, palette, palette::Extended::generate) } /// Creates a new custom [`Theme`] from the given [`Palette`], with /// a custom generator of a [`palette::Extended`]. pub fn custom_with_fn( name: impl Into<Cow<'static, str>>, palette: Palette, generate: impl FnOnce(Palette) -> palette::Extended, ) -> Self { Self::Custom(Arc::new(Custom::with_fn(name, palette, generate))) } /// Returns the [`Palette`] of the [`Theme`]. pub fn palette(&self) -> Palette { match self { Self::Light => Palette::LIGHT, Self::Dark => Palette::DARK, Self::Dracula => Palette::DRACULA, Self::Nord => Palette::NORD, Self::SolarizedLight => Palette::SOLARIZED_LIGHT, Self::SolarizedDark => Palette::SOLARIZED_DARK, Self::GruvboxLight => Palette::GRUVBOX_LIGHT, Self::GruvboxDark => Palette::GRUVBOX_DARK, Self::CatppuccinLatte => Palette::CATPPUCCIN_LATTE, Self::CatppuccinFrappe => Palette::CATPPUCCIN_FRAPPE, Self::CatppuccinMacchiato => Palette::CATPPUCCIN_MACCHIATO, Self::CatppuccinMocha => Palette::CATPPUCCIN_MOCHA, Self::TokyoNight => Palette::TOKYO_NIGHT, Self::TokyoNightStorm => Palette::TOKYO_NIGHT_STORM, Self::TokyoNightLight => Palette::TOKYO_NIGHT_LIGHT, Self::KanagawaWave => Palette::KANAGAWA_WAVE, Self::KanagawaDragon => Palette::KANAGAWA_DRAGON, Self::KanagawaLotus => Palette::KANAGAWA_LOTUS, Self::Moonfly => Palette::MOONFLY, Self::Nightfly => Palette::NIGHTFLY, Self::Oxocarbon => Palette::OXOCARBON, Self::Ferra => Palette::FERRA, Self::Custom(custom) => custom.palette, } } /// Returns the [`palette::Extended`] of the [`Theme`]. pub fn extended_palette(&self) -> &palette::Extended { match self { Self::Light => &palette::EXTENDED_LIGHT, Self::Dark => &palette::EXTENDED_DARK, Self::Dracula => &palette::EXTENDED_DRACULA, Self::Nord => &palette::EXTENDED_NORD, Self::SolarizedLight => &palette::EXTENDED_SOLARIZED_LIGHT, Self::SolarizedDark => &palette::EXTENDED_SOLARIZED_DARK, Self::GruvboxLight => &palette::EXTENDED_GRUVBOX_LIGHT, Self::GruvboxDark => &palette::EXTENDED_GRUVBOX_DARK, Self::CatppuccinLatte => &palette::EXTENDED_CATPPUCCIN_LATTE, Self::CatppuccinFrappe => &palette::EXTENDED_CATPPUCCIN_FRAPPE, Self::CatppuccinMacchiato => &palette::EXTENDED_CATPPUCCIN_MACCHIATO, Self::CatppuccinMocha => &palette::EXTENDED_CATPPUCCIN_MOCHA, Self::TokyoNight => &palette::EXTENDED_TOKYO_NIGHT, Self::TokyoNightStorm => &palette::EXTENDED_TOKYO_NIGHT_STORM, Self::TokyoNightLight => &palette::EXTENDED_TOKYO_NIGHT_LIGHT, Self::KanagawaWave => &palette::EXTENDED_KANAGAWA_WAVE, Self::KanagawaDragon => &palette::EXTENDED_KANAGAWA_DRAGON, Self::KanagawaLotus => &palette::EXTENDED_KANAGAWA_LOTUS, Self::Moonfly => &palette::EXTENDED_MOONFLY, Self::Nightfly => &palette::EXTENDED_NIGHTFLY, Self::Oxocarbon => &palette::EXTENDED_OXOCARBON, Self::Ferra => &palette::EXTENDED_FERRA, Self::Custom(custom) => &custom.extended, } } } impl fmt::Display for Theme { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.name()) } } /// A [`Theme`] with a customized [`Palette`]. #[derive(Debug, Clone, PartialEq)] pub struct Custom { name: Cow<'static, str>, palette: Palette, extended: palette::Extended, } impl Custom { /// Creates a [`Custom`] theme from the given [`Palette`]. pub fn new(name: String, palette: Palette) -> Self { Self::with_fn(name, palette, palette::Extended::generate) } /// Creates a [`Custom`] theme from the given [`Palette`] with /// a custom generator of a [`palette::Extended`]. pub fn with_fn( name: impl Into<Cow<'static, str>>, palette: Palette, generate: impl FnOnce(Palette) -> palette::Extended, ) -> Self { Self { name: name.into(), palette, extended: generate(palette), } } } impl fmt::Display for Custom { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } /// A theme mode, denoting the tone or brightness of a theme. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Mode { /// No specific tone. #[default] None, /// A mode referring to themes with light tones. Light, /// A mode referring to themes with dark tones. Dark, } /// The base style of a theme. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The background [`Color`] of the application. pub background_color: Color, /// The default text [`Color`] of the application. pub text_color: Color, } /// The default blank style of a theme. pub trait Base { /// Returns the default theme for the preferred [`Mode`]. fn default(preference: Mode) -> Self; /// Returns the [`Mode`] of the theme. fn mode(&self) -> Mode; /// Returns the default base [`Style`] of the theme. fn base(&self) -> Style; /// Returns the color [`Palette`] of the theme. /// /// This [`Palette`] may be used by the runtime for /// debugging purposes; like displaying performance /// metrics or devtools. fn palette(&self) -> Option<Palette>; /// Returns the unique name of the theme. /// /// This name may be used to efficiently detect theme /// changes in some widgets. fn name(&self) -> &str; } impl Base for Theme { fn default(preference: Mode) -> Self { use std::env; use std::sync::OnceLock; static SYSTEM: OnceLock<Option<Theme>> = OnceLock::new(); let system = SYSTEM.get_or_init(|| { let name = env::var("ICED_THEME").ok()?; Theme::ALL .iter() .find(|theme| theme.to_string() == name) .cloned() }); if let Some(system) = system { return system.clone(); } match preference { Mode::None | Mode::Light => Self::Light, Mode::Dark => Self::Dark, } } fn mode(&self) -> Mode { if self.extended_palette().is_dark { Mode::Dark } else { Mode::Light } } fn base(&self) -> Style { default(self) } fn palette(&self) -> Option<Palette> { Some(self.palette()) } fn name(&self) -> &str { match self { Self::Light => "Light", Self::Dark => "Dark", Self::Dracula => "Dracula", Self::Nord => "Nord", Self::SolarizedLight => "Solarized Light", Self::SolarizedDark => "Solarized Dark", Self::GruvboxLight => "Gruvbox Light", Self::GruvboxDark => "Gruvbox Dark", Self::CatppuccinLatte => "Catppuccin Latte", Self::CatppuccinFrappe => "Catppuccin Frappé", Self::CatppuccinMacchiato => "Catppuccin Macchiato", Self::CatppuccinMocha => "Catppuccin Mocha", Self::TokyoNight => "Tokyo Night", Self::TokyoNightStorm => "Tokyo Night Storm", Self::TokyoNightLight => "Tokyo Night Light", Self::KanagawaWave => "Kanagawa Wave", Self::KanagawaDragon => "Kanagawa Dragon", Self::KanagawaLotus => "Kanagawa Lotus", Self::Moonfly => "Moonfly", Self::Nightfly => "Nightfly", Self::Oxocarbon => "Oxocarbon", Self::Ferra => "Ferra", Self::Custom(custom) => &custom.name, } } } /// The default [`Style`] of a built-in [`Theme`]. pub fn default(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { background_color: palette.background.base.color, text_color: palette.background.base.text, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget.rs
core/src/widget.rs
//! Create custom widgets and operate on them. pub mod operation; pub mod text; pub mod tree; mod id; pub use id::Id; pub use operation::Operation; pub use text::Text; pub use tree::Tree; use crate::layout::{self, Layout}; use crate::mouse; use crate::overlay; use crate::renderer; use crate::{Clipboard, Event, Length, Rectangle, Shell, Size, Vector}; /// A component that displays information and allows interaction. /// /// If you want to build your own widgets, you will need to implement this /// trait. /// /// # Examples /// The repository has some [examples] showcasing how to implement a custom /// widget: /// /// - [`custom_widget`], a demonstration of how to build a custom widget that /// draws a circle. /// - [`geometry`], a custom widget showcasing how to draw geometry with the /// `Mesh2D` primitive in [`iced_wgpu`]. /// /// [examples]: https://github.com/iced-rs/iced/tree/master/examples /// [`custom_widget`]: https://github.com/iced-rs/iced/tree/master/examples/custom_widget /// [`geometry`]: https://github.com/iced-rs/iced/tree/master/examples/geometry /// [`iced_wgpu`]: https://github.com/iced-rs/iced/tree/master/wgpu pub trait Widget<Message, Theme, Renderer> where Renderer: crate::Renderer, { /// Returns the [`Size`] of the [`Widget`] in lengths. fn size(&self) -> Size<Length>; /// Returns a [`Size`] hint for laying out the [`Widget`]. /// /// This hint may be used by some widget containers to adjust their sizing strategy /// during construction. fn size_hint(&self) -> Size<Length> { self.size() } /// Returns the [`layout::Node`] of the [`Widget`]. /// /// This [`layout::Node`] is used by the runtime to compute the [`Layout`] of the /// user interface. fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node; /// Draws the [`Widget`] using the associated `Renderer`. fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ); /// Returns the [`Tag`] of the [`Widget`]. /// /// [`Tag`]: tree::Tag fn tag(&self) -> tree::Tag { tree::Tag::stateless() } /// Returns the [`State`] of the [`Widget`]. /// /// [`State`]: tree::State fn state(&self) -> tree::State { tree::State::None } /// Returns the state [`Tree`] of the children of the [`Widget`]. fn children(&self) -> Vec<Tree> { Vec::new() } /// Reconciles the [`Widget`] with the provided [`Tree`]. fn diff(&self, tree: &mut Tree) { tree.children.clear(); } /// Applies an [`Operation`] to the [`Widget`]. fn operate( &mut self, _tree: &mut Tree, _layout: Layout<'_>, _renderer: &Renderer, _operation: &mut dyn Operation, ) { } /// Processes a runtime [`Event`]. /// /// By default, it does nothing. fn update( &mut self, _tree: &mut Tree, _event: &Event, _layout: Layout<'_>, _cursor: mouse::Cursor, _renderer: &Renderer, _clipboard: &mut dyn Clipboard, _shell: &mut Shell<'_, Message>, _viewport: &Rectangle, ) { } /// Returns the current [`mouse::Interaction`] of the [`Widget`]. /// /// By default, it returns [`mouse::Interaction::None`]. fn mouse_interaction( &self, _tree: &Tree, _layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { mouse::Interaction::None } /// Returns the overlay of the [`Widget`], if there is any. fn overlay<'a>( &'a mut self, _tree: &'a mut Tree, _layout: Layout<'a>, _renderer: &Renderer, _viewport: &Rectangle, _translation: Vector, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { None } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/vector.rs
core/src/vector.rs
/// A 2D vector. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Vector<T = f32> { /// The X component of the [`Vector`] pub x: T, /// The Y component of the [`Vector`] pub y: T, } impl<T> Vector<T> { /// Creates a new [`Vector`] with the given components. pub const fn new(x: T, y: T) -> Self { Self { x, y } } } impl Vector { /// The zero [`Vector`]. pub const ZERO: Self = Self::new(0.0, 0.0); /// Rounds the [`Vector`]. pub fn round(self) -> Self { Self { x: self.x.round(), y: self.y.round(), } } } impl<T> std::ops::Neg for Vector<T> where T: std::ops::Neg<Output = T>, { type Output = Self; fn neg(self) -> Self::Output { Self::new(-self.x, -self.y) } } impl<T> std::ops::Add for Vector<T> where T: std::ops::Add<Output = T>, { type Output = Self; fn add(self, b: Self) -> Self { Self::new(self.x + b.x, self.y + b.y) } } impl<T> std::ops::AddAssign for Vector<T> where T: std::ops::AddAssign, { fn add_assign(&mut self, b: Self) { self.x += b.x; self.y += b.y; } } impl<T> std::ops::Sub for Vector<T> where T: std::ops::Sub<Output = T>, { type Output = Self; fn sub(self, b: Self) -> Self { Self::new(self.x - b.x, self.y - b.y) } } impl<T> std::ops::SubAssign for Vector<T> where T: std::ops::SubAssign, { fn sub_assign(&mut self, b: Self) { self.x -= b.x; self.y -= b.y; } } impl<T> std::ops::Mul<T> for Vector<T> where T: std::ops::Mul<Output = T> + Copy, { type Output = Self; fn mul(self, scale: T) -> Self { Self::new(self.x * scale, self.y * scale) } } impl<T> std::ops::MulAssign<T> for Vector<T> where T: std::ops::MulAssign + Copy, { fn mul_assign(&mut self, scale: T) { self.x *= scale; self.y *= scale; } } impl<T> std::ops::Div<T> for Vector<T> where T: std::ops::Div<Output = T> + Copy, { type Output = Self; fn div(self, scale: T) -> Self { Self::new(self.x / scale, self.y / scale) } } impl<T> std::ops::DivAssign<T> for Vector<T> where T: std::ops::DivAssign + Copy, { fn div_assign(&mut self, scale: T) { self.x /= scale; self.y /= scale; } } impl<T> From<[T; 2]> for Vector<T> { fn from([x, y]: [T; 2]) -> Self { Self::new(x, y) } } impl<T> From<Vector<T>> for [T; 2] where T: Copy, { fn from(other: Vector<T>) -> Self { [other.x, other.y] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/content_fit.rs
core/src/content_fit.rs
//! Control the fit of some content (like an image) within a space. use crate::Size; use std::fmt; /// The strategy used to fit the contents of a widget to its bounding box. /// /// Each variant of this enum is a strategy that can be applied for resolving /// differences in aspect ratio and size between the image being displayed and /// the space its being displayed in. /// /// For an interactive demonstration of these properties as they are implemented /// in CSS, see [Mozilla's docs][1], or run the `tour` example /// /// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, Default)] pub enum ContentFit { /// Scale as big as it can be without needing to crop or hide parts. /// /// The image will be scaled (preserving aspect ratio) so that it just fits /// within the window. This won't distort the image or crop/hide any edges, /// but if the image doesn't fit perfectly, there may be whitespace on the /// top/bottom or left/right. /// /// This is a great fit for when you need to display an image without losing /// any part of it, particularly when the image itself is the focus of the /// screen. #[default] Contain, /// Scale the image to cover all of the bounding box, cropping if needed. /// /// This doesn't distort the image, and it ensures that the widget's area is /// completely covered, but it might crop off a bit of the edges of the /// widget, particularly when there is a big difference between the aspect /// ratio of the widget and the aspect ratio of the image. /// /// This is best for when you're using an image as a background, or to fill /// space, and any details of the image around the edge aren't too /// important. Cover, /// Distort the image so the widget is 100% covered without cropping. /// /// This stretches the image to fit the widget, without any whitespace or /// cropping. However, because of the stretch, the image may look distorted /// or elongated, particularly when there's a mismatch of aspect ratios. Fill, /// Don't resize or scale the image at all. /// /// This will not apply any transformations to the provided image, but also /// means that unless you do the math yourself, the widget's area will not /// be completely covered, or the image might be cropped. /// /// This is best for when you've sized the image yourself. None, /// Scale the image down if it's too big for the space, but never scale it /// up. /// /// This works much like [`Contain`](Self::Contain), except that if the /// image would have been scaled up, it keeps its original resolution to /// avoid the bluring that accompanies upscaling images. ScaleDown, } impl ContentFit { /// Attempt to apply the given fit for a content size within some bounds. /// /// The returned value is the recommended scaled size of the content. pub fn fit(&self, content: Size, bounds: Size) -> Size { let content_ar = content.width / content.height; let bounds_ar = bounds.width / bounds.height; match self { Self::Contain => { if bounds_ar > content_ar { Size { width: content.width * bounds.height / content.height, ..bounds } } else { Size { height: content.height * bounds.width / content.width, ..bounds } } } Self::Cover => { if bounds_ar < content_ar { Size { width: content.width * bounds.height / content.height, ..bounds } } else { Size { height: content.height * bounds.width / content.width, ..bounds } } } Self::Fill => bounds, Self::None => content, Self::ScaleDown => { if bounds_ar > content_ar && bounds.height < content.height { Size { width: content.width * bounds.height / content.height, ..bounds } } else if bounds.width < content.width { Size { height: content.height * bounds.width / content.width, ..bounds } } else { content } } } } } impl fmt::Display for ContentFit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { ContentFit::Contain => "Contain", ContentFit::Cover => "Cover", ContentFit::Fill => "Fill", ContentFit::None => "None", ContentFit::ScaleDown => "Scale Down", }) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/image.rs
core/src/image.rs
//! Load and draw raster graphics. use crate::border; use crate::{Bytes, Radians, Rectangle, Size}; use rustc_hash::FxHasher; use std::hash::{Hash, Hasher}; use std::io; use std::path::{Path, PathBuf}; use std::sync::{Arc, Weak}; /// A raster image that can be drawn. #[derive(Debug, Clone, PartialEq)] pub struct Image<H = Handle> { /// The handle of the image. pub handle: H, /// The filter method of the image. pub filter_method: FilterMethod, /// The rotation to be applied to the image; on its center. pub rotation: Radians, /// The border radius of the [`Image`]. /// /// Currently, this will only be applied to the `clip_bounds`. pub border_radius: border::Radius, /// The opacity of the image. /// /// 0 means transparent. 1 means opaque. pub opacity: f32, /// If set to `true`, the image will be snapped to the pixel grid. /// /// This can avoid graphical glitches, specially when using /// [`FilterMethod::Nearest`]. pub snap: bool, } impl Image<Handle> { /// Creates a new [`Image`] with the given handle. pub fn new(handle: impl Into<Handle>) -> Self { Self { handle: handle.into(), filter_method: FilterMethod::default(), rotation: Radians(0.0), border_radius: border::Radius::default(), opacity: 1.0, snap: false, } } /// Sets the filter method of the [`Image`]. pub fn filter_method(mut self, filter_method: FilterMethod) -> Self { self.filter_method = filter_method; self } /// Sets the rotation of the [`Image`]. pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self { self.rotation = rotation.into(); self } /// Sets the opacity of the [`Image`]. pub fn opacity(mut self, opacity: impl Into<f32>) -> Self { self.opacity = opacity.into(); self } /// Sets whether the [`Image`] should be snapped to the pixel grid. pub fn snap(mut self, snap: bool) -> Self { self.snap = snap; self } } impl From<&Handle> for Image { fn from(handle: &Handle) -> Self { Image::new(handle.clone()) } } /// A handle of some image data. #[derive(Clone, PartialEq, Eq)] pub enum Handle { /// A file handle. The image data will be read /// from the file path. /// /// Use [`from_path`] to create this variant. /// /// [`from_path`]: Self::from_path Path(Id, PathBuf), /// A handle pointing to some encoded image bytes in-memory. /// /// Use [`from_bytes`] to create this variant. /// /// [`from_bytes`]: Self::from_bytes Bytes(Id, Bytes), /// A handle pointing to decoded image pixels in RGBA format. /// /// Use [`from_rgba`] to create this variant. /// /// [`from_rgba`]: Self::from_rgba Rgba { /// The id of this handle. id: Id, /// The width of the image. width: u32, /// The height of the image. height: u32, /// The pixels. pixels: Bytes, }, } impl Handle { /// Creates an image [`Handle`] pointing to the image of the given path. /// /// Makes an educated guess about the image format by examining the data in the file. pub fn from_path<T: Into<PathBuf>>(path: T) -> Handle { let path = path.into(); Self::Path(Id::path(&path), path) } /// Creates an image [`Handle`] containing the encoded image data directly. /// /// Makes an educated guess about the image format by examining the given data. /// /// This is useful if you already have your image loaded in-memory, maybe /// because you downloaded or generated it procedurally. pub fn from_bytes(bytes: impl Into<Bytes>) -> Handle { Self::Bytes(Id::unique(), bytes.into()) } /// Creates an image [`Handle`] containing the decoded image pixels directly. /// /// This function expects the pixel data to be provided as a collection of [`Bytes`] /// of RGBA pixels. Therefore, the length of the pixel data should always be /// `width * height * 4`. /// /// This is useful if you have already decoded your image. pub fn from_rgba(width: u32, height: u32, pixels: impl Into<Bytes>) -> Handle { Self::Rgba { id: Id::unique(), width, height, pixels: pixels.into(), } } /// Returns the unique identifier of the [`Handle`]. pub fn id(&self) -> Id { match self { Handle::Path(id, _) | Handle::Bytes(id, _) | Handle::Rgba { id, .. } => *id, } } } impl<T> From<T> for Handle where T: Into<PathBuf>, { fn from(path: T) -> Handle { Handle::from_path(path.into()) } } impl From<&Handle> for Handle { fn from(value: &Handle) -> Self { value.clone() } } impl std::fmt::Debug for Handle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Path(id, path) => write!(f, "Path({id:?}, {path:?})"), Self::Bytes(id, _) => write!(f, "Bytes({id:?}, ...)"), Self::Rgba { id, width, height, .. } => { write!(f, "Pixels({id:?}, {width} * {height})") } } } } /// The unique identifier of some [`Handle`] data. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id(_Id); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] enum _Id { Unique(u64), Hash(u64), } impl Id { fn unique() -> Self { use std::sync::atomic::{self, AtomicU64}; static NEXT_ID: AtomicU64 = AtomicU64::new(0); Self(_Id::Unique(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed))) } fn path(path: impl AsRef<Path>) -> Self { let hash = { let mut hasher = FxHasher::default(); path.as_ref().hash(&mut hasher); hasher.finish() }; Self(_Id::Hash(hash)) } } /// Image filtering strategy. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum FilterMethod { /// Bilinear interpolation. #[default] Linear, /// Nearest neighbor. Nearest, } /// A memory allocation of a [`Handle`], often in GPU memory. /// /// Renderers tend to decode and upload image data concurrently to /// avoid blocking the user interface. This means that when you use a /// [`Handle`] in a widget, there may be a slight frame delay until it /// is finally visible. If you are animating images, this can cause /// undesirable flicker. /// /// When you obtain an [`Allocation`] explicitly, you get the guarantee /// that using a [`Handle`] will draw the corresponding [`Image`] /// immediately in the next frame. /// /// This guarantee is valid as long as you hold an [`Allocation`]. /// Only when you drop all its clones, the renderer may choose to free /// the memory of the [`Handle`]. Be careful! #[derive(Debug, Clone, PartialEq, Eq)] pub struct Allocation(Arc<Memory>); /// Some memory taken by an [`Allocation`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Memory { handle: Handle, size: Size<u32>, } impl Allocation { /// Returns a weak reference to the [`Memory`] of the [`Allocation`]. pub fn downgrade(&self) -> Weak<Memory> { Arc::downgrade(&self.0) } /// Upgrades a [`Weak`] memory reference to an [`Allocation`]. pub fn upgrade(weak: &Weak<Memory>) -> Option<Allocation> { Weak::upgrade(weak).map(Allocation) } /// Returns the [`Handle`] of this [`Allocation`]. pub fn handle(&self) -> &Handle { &self.0.handle } /// Returns the [`Size`] of the image of this [`Allocation`]. pub fn size(&self) -> Size<u32> { self.0.size } } /// Creates a new [`Allocation`] for the given handle. /// /// This should only be used internally by renderer implementations. /// /// # Safety /// Must only be created once the [`Handle`] is allocated in memory. #[allow(unsafe_code)] pub unsafe fn allocate(handle: &Handle, size: Size<u32>) -> Allocation { Allocation(Arc::new(Memory { handle: handle.clone(), size, })) } /// A [`Renderer`] that can render raster graphics. /// /// [renderer]: crate::renderer pub trait Renderer: crate::Renderer { /// The image Handle to be displayed. Iced exposes its own default implementation of a [`Handle`] /// /// [`Handle`]: Self::Handle type Handle: Clone; /// Loads an image and returns an explicit [`Allocation`] to it. /// /// If the image is not already loaded, this method will block! You should /// generally not use it in drawing logic if you want to avoid frame drops. fn load_image(&self, handle: &Self::Handle) -> Result<Allocation, Error>; /// Returns the dimensions of an image for the given [`Handle`]. /// /// If the image is not already loaded, the [`Renderer`] may choose to return /// `None`, load the image in the background, and then trigger a relayout. /// /// If you need a measurement right away, consider using [`Renderer::load_image`]. fn measure_image(&self, handle: &Self::Handle) -> Option<Size<u32>>; /// Draws an [`Image`] inside the provided `bounds`. /// /// If the image is not already loaded, the [`Renderer`] may choose to render /// nothing, load the image in the background, and then trigger a redraw. /// /// If you need to draw an image right away, consider using [`Renderer::load_image`] /// and hold on to an [`Allocation`] first. fn draw_image(&mut self, image: Image<Self::Handle>, bounds: Rectangle, clip_bounds: Rectangle); } /// An image loading error. #[derive(Debug, Clone, thiserror::Error)] pub enum Error { /// The image data was invalid or could not be decoded. #[error("the image data was invalid or could not be decoded: {0}")] Invalid(Arc<dyn std::error::Error + Send + Sync>), /// The image file was not found. #[error("the image file could not be opened: {0}")] Inaccessible(Arc<io::Error>), /// Loading images is unsupported. #[error("loading images is unsupported")] Unsupported, /// The image is empty. #[error("the image is empty")] Empty, /// Not enough memory to allocate the image. #[error("not enough memory to allocate the image")] OutOfMemory, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/renderer.rs
core/src/renderer.rs
//! Write your own renderer. #[cfg(debug_assertions)] mod null; use crate::image; use crate::{ Background, Border, Color, Font, Pixels, Rectangle, Shadow, Size, Transformation, Vector, }; /// Whether anti-aliasing should be avoided by snapping primitive coordinates to the /// pixel grid. pub const CRISP: bool = cfg!(feature = "crisp"); /// A component that can be used by widgets to draw themselves on a screen. pub trait Renderer { /// Starts recording a new layer. fn start_layer(&mut self, bounds: Rectangle); /// Ends recording a new layer. /// /// The new layer will clip its contents to the provided `bounds`. fn end_layer(&mut self); /// Draws the primitives recorded in the given closure in a new layer. /// /// The layer will clip its contents to the provided `bounds`. fn with_layer(&mut self, bounds: Rectangle, f: impl FnOnce(&mut Self)) { self.start_layer(bounds); f(self); self.end_layer(); } /// Starts recording with a new [`Transformation`]. fn start_transformation(&mut self, transformation: Transformation); /// Ends recording a new layer. /// /// The new layer will clip its contents to the provided `bounds`. fn end_transformation(&mut self); /// Applies a [`Transformation`] to the primitives recorded in the given closure. fn with_transformation(&mut self, transformation: Transformation, f: impl FnOnce(&mut Self)) { self.start_transformation(transformation); f(self); self.end_transformation(); } /// Applies a translation to the primitives recorded in the given closure. fn with_translation(&mut self, translation: Vector, f: impl FnOnce(&mut Self)) { self.with_transformation(Transformation::translate(translation.x, translation.y), f); } /// Fills a [`Quad`] with the provided [`Background`]. fn fill_quad(&mut self, quad: Quad, background: impl Into<Background>); /// Creates an [`image::Allocation`] for the given [`image::Handle`] and calls the given callback with it. fn allocate_image( &mut self, handle: &image::Handle, callback: impl FnOnce(Result<image::Allocation, image::Error>) + Send + 'static, ); /// Provides hints to the [`Renderer`] about the rendering target. /// /// This may be used internally by the [`Renderer`] to perform optimizations /// and/or improve rendering quality. /// /// For instance, providing a `scale_factor` may be used by some renderers to /// perform metrics hinting internally in physical coordinates while keeping /// layout coordinates logical and, therefore, maintain linearity. fn hint(&mut self, scale_factor: f32); /// Returns the last scale factor provided as a [`hint`](Self::hint). fn scale_factor(&self) -> Option<f32>; /// Resets the [`Renderer`] to start drawing in the `new_bounds` from scratch. fn reset(&mut self, new_bounds: Rectangle); /// Polls any concurrent computations that may be pending in the [`Renderer`]. /// /// By default, it does nothing. fn tick(&mut self) {} } /// A polygon with four sides. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Quad { /// The bounds of the [`Quad`]. pub bounds: Rectangle, /// The [`Border`] of the [`Quad`]. The border is drawn on the inside of the [`Quad`]. pub border: Border, /// The [`Shadow`] of the [`Quad`]. pub shadow: Shadow, /// Whether the [`Quad`] should be snapped to the pixel grid. pub snap: bool, } impl Default for Quad { fn default() -> Self { Self { bounds: Rectangle::with_size(Size::ZERO), border: Border::default(), shadow: Shadow::default(), snap: CRISP, } } } /// The styling attributes of a [`Renderer`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The text color pub text_color: Color, } impl Default for Style { fn default() -> Self { Style { text_color: Color::BLACK, } } } /// A headless renderer is a renderer that can render offscreen without /// a window nor a compositor. pub trait Headless { /// Creates a new [`Headless`] renderer; fn new( default_font: Font, default_text_size: Pixels, backend: Option<&str>, ) -> impl Future<Output = Option<Self>> where Self: Sized; /// Returns the unique name of the renderer. /// /// This name may be used by testing libraries to uniquely identify /// snapshots. fn name(&self) -> String; /// Draws offscreen into a screenshot, returning a collection of /// bytes representing the rendered pixels in RGBA order. fn screenshot( &mut self, size: Size<u32>, scale_factor: f32, background_color: Color, ) -> Vec<u8>; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse.rs
core/src/mouse.rs
//! Handle mouse events. pub mod click; mod button; mod cursor; mod event; mod interaction; pub use button::Button; pub use click::Click; pub use cursor::Cursor; pub use event::{Event, ScrollDelta}; pub use interaction::Interaction;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/clipboard.rs
core/src/clipboard.rs
//! Access the clipboard. /// A buffer for short-term storage and transfer within and between /// applications. pub trait Clipboard { /// Reads the current content of the [`Clipboard`] as text. fn read(&self, kind: Kind) -> Option<String>; /// Writes the given text contents to the [`Clipboard`]. fn write(&mut self, kind: Kind, contents: String); } /// The kind of [`Clipboard`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { /// The standard clipboard. Standard, /// The primary clipboard. /// /// Normally only present in X11 and Wayland. Primary, } /// A null implementation of the [`Clipboard`] trait. #[derive(Debug, Clone, Copy)] pub struct Null; impl Clipboard for Null { fn read(&self, _kind: Kind) -> Option<String> { None } fn write(&mut self, _kind: Kind, _contents: String) {} }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/animation.rs
core/src/animation.rs
//! Animate your applications. use crate::time::{Duration, Instant}; pub use lilt::{Easing, FloatRepresentable as Float, Interpolable}; /// The animation of some particular state. /// /// It tracks state changes and allows projecting interpolated values /// through time. #[derive(Debug, Clone)] pub struct Animation<T> where T: Clone + Copy + PartialEq + Float, { raw: lilt::Animated<T, Instant>, duration: Duration, // TODO: Expose duration getter in `lilt` } impl<T> Animation<T> where T: Clone + Copy + PartialEq + Float, { /// Creates a new [`Animation`] with the given initial state. pub fn new(state: T) -> Self { Self { raw: lilt::Animated::new(state), duration: Duration::from_millis(100), } } /// Sets the [`Easing`] function of the [`Animation`]. /// /// See the [Easing Functions Cheat Sheet](https://easings.net) for /// details! pub fn easing(mut self, easing: Easing) -> Self { self.raw = self.raw.easing(easing); self } /// Sets the duration of the [`Animation`] to 100ms. pub fn very_quick(self) -> Self { self.duration(Duration::from_millis(100)) } /// Sets the duration of the [`Animation`] to 200ms. pub fn quick(self) -> Self { self.duration(Duration::from_millis(200)) } /// Sets the duration of the [`Animation`] to 400ms. pub fn slow(self) -> Self { self.duration(Duration::from_millis(400)) } /// Sets the duration of the [`Animation`] to 500ms. pub fn very_slow(self) -> Self { self.duration(Duration::from_millis(500)) } /// Sets the duration of the [`Animation`] to the given value. pub fn duration(mut self, duration: Duration) -> Self { self.raw = self.raw.duration(duration.as_secs_f32() * 1_000.0); self.duration = duration; self } /// Sets a delay for the [`Animation`]. pub fn delay(mut self, duration: Duration) -> Self { self.raw = self.raw.delay(duration.as_secs_f64() as f32 * 1000.0); self } /// Makes the [`Animation`] repeat a given amount of times. /// /// Providing 1 repetition plays the animation twice in total. pub fn repeat(mut self, repetitions: u32) -> Self { self.raw = self.raw.repeat(repetitions); self } /// Makes the [`Animation`] repeat forever. pub fn repeat_forever(mut self) -> Self { self.raw = self.raw.repeat_forever(); self } /// Makes the [`Animation`] automatically reverse when repeating. pub fn auto_reverse(mut self) -> Self { self.raw = self.raw.auto_reverse(); self } /// Transitions the [`Animation`] from its current state to the given new state /// at the given time. pub fn go(mut self, new_state: T, at: Instant) -> Self { self.go_mut(new_state, at); self } /// Transitions the [`Animation`] from its current state to the given new state /// at the given time, by reference. pub fn go_mut(&mut self, new_state: T, at: Instant) { self.raw.transition(new_state, at); } /// Returns true if the [`Animation`] is currently in progress. /// /// An [`Animation`] is in progress when it is transitioning to a different state. pub fn is_animating(&self, at: Instant) -> bool { self.raw.in_progress(at) } /// Projects the [`Animation`] into an interpolated value at the given [`Instant`]; using the /// closure provided to calculate the different keyframes of interpolated values. /// /// If the [`Animation`] state is a `bool`, you can use the simpler [`interpolate`] method. /// /// [`interpolate`]: Animation::interpolate pub fn interpolate_with<I>(&self, f: impl Fn(T) -> I, at: Instant) -> I where I: Interpolable, { self.raw.animate(f, at) } /// Retuns the current state of the [`Animation`]. pub fn value(&self) -> T { self.raw.value } } impl Animation<bool> { /// Projects the [`Animation`] into an interpolated value at the given [`Instant`]; using the /// `start` and `end` values as the origin and destination keyframes. pub fn interpolate<I>(&self, start: I, end: I, at: Instant) -> I where I: Interpolable + Clone, { self.raw.animate_bool(start, end, at) } /// Returns the remaining [`Duration`] of the [`Animation`]. pub fn remaining(&self, at: Instant) -> Duration { Duration::from_secs_f32(self.interpolate(self.duration.as_secs_f32(), 0.0, at)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/rectangle.rs
core/src/rectangle.rs
use crate::alignment; use crate::{Padding, Point, Radians, Size, Vector}; /// An axis-aligned rectangle. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Rectangle<T = f32> { /// X coordinate of the top-left corner. pub x: T, /// Y coordinate of the top-left corner. pub y: T, /// Width of the rectangle. pub width: T, /// Height of the rectangle. pub height: T, } impl<T> Rectangle<T> where T: Default, { /// Creates a new [`Rectangle`] with its top-left corner at the origin /// and with the provided [`Size`]. pub fn with_size(size: Size<T>) -> Self { Self { x: T::default(), y: T::default(), width: size.width, height: size.height, } } } impl Rectangle<f32> { /// A rectangle starting at negative infinity and with infinite width and height. pub const INFINITE: Self = Self::new( Point::new(f32::NEG_INFINITY, f32::NEG_INFINITY), Size::INFINITE, ); /// Creates a new [`Rectangle`] with its top-left corner in the given /// [`Point`] and with the provided [`Size`]. pub const fn new(top_left: Point, size: Size) -> Self { Self { x: top_left.x, y: top_left.y, width: size.width, height: size.height, } } /// Creates a new square [`Rectangle`] with the center at the origin and /// with the given radius. pub fn with_radius(radius: f32) -> Self { Self { x: -radius, y: -radius, width: radius * 2.0, height: radius * 2.0, } } /// Creates a new axis-aligned [`Rectangle`] from the given vertices; returning the /// rotation in [`Radians`] that must be applied to the axis-aligned [`Rectangle`] /// to obtain the desired result. pub fn with_vertices( top_left: Point, top_right: Point, bottom_left: Point, ) -> (Rectangle, Radians) { let width = (top_right.x - top_left.x).hypot(top_right.y - top_left.y); let height = (bottom_left.x - top_left.x).hypot(bottom_left.y - top_left.y); let rotation = (top_right.y - top_left.y).atan2(top_right.x - top_left.x); let rotation = if rotation < 0.0 { 2.0 * std::f32::consts::PI + rotation } else { rotation }; let position = { let center = Point::new( (top_right.x + bottom_left.x) / 2.0, (top_right.y + bottom_left.y) / 2.0, ); let rotation = -rotation - std::f32::consts::PI * 2.0; Point::new( center.x + (top_left.x - center.x) * rotation.cos() - (top_left.y - center.y) * rotation.sin(), center.y + (top_left.x - center.x) * rotation.sin() + (top_left.y - center.y) * rotation.cos(), ) }; ( Rectangle::new(position, Size::new(width, height)), Radians(rotation), ) } /// Returns the [`Point`] at the center of the [`Rectangle`]. pub fn center(&self) -> Point { Point::new(self.center_x(), self.center_y()) } /// Returns the X coordinate of the [`Point`] at the center of the /// [`Rectangle`]. pub fn center_x(&self) -> f32 { self.x + self.width / 2.0 } /// Returns the Y coordinate of the [`Point`] at the center of the /// [`Rectangle`]. pub fn center_y(&self) -> f32 { self.y + self.height / 2.0 } /// Returns the position of the top left corner of the [`Rectangle`]. pub fn position(&self) -> Point { Point::new(self.x, self.y) } /// Returns the [`Size`] of the [`Rectangle`]. pub fn size(&self) -> Size { Size::new(self.width, self.height) } /// Returns the area of the [`Rectangle`]. pub fn area(&self) -> f32 { self.width * self.height } /// Returns true if the given [`Point`] is contained in the [`Rectangle`]. /// Excludes the right and bottom edges. pub fn contains(&self, point: Point) -> bool { self.x <= point.x && point.x < self.x + self.width && self.y <= point.y && point.y < self.y + self.height } /// Returns the minimum distance from the given [`Point`] to any of the edges /// of the [`Rectangle`]. pub fn distance(&self, point: Point) -> f32 { let center = self.center(); let distance_x = ((point.x - center.x).abs() - self.width / 2.0).max(0.0); let distance_y = ((point.y - center.y).abs() - self.height / 2.0).max(0.0); distance_x.hypot(distance_y) } /// Computes the offset that must be applied to the [`Rectangle`] to be placed /// inside the given `container`. pub fn offset(&self, container: &Rectangle) -> Vector { let Some(intersection) = self.intersection(container) else { return Vector::ZERO; }; let left = intersection.x - self.x; let top = intersection.y - self.y; Vector::new( if left > 0.0 { left } else { intersection.x + intersection.width - self.x - self.width }, if top > 0.0 { top } else { intersection.y + intersection.height - self.y - self.height }, ) } /// Returns true if the current [`Rectangle`] is within the given /// `container`. Includes the right and bottom edges. pub fn is_within(&self, container: &Rectangle) -> bool { self.x >= container.x && self.y >= container.y && self.x + self.width <= container.x + container.width && self.y + self.height <= container.y + container.height } /// Computes the intersection with the given [`Rectangle`]. pub fn intersection(&self, other: &Rectangle<f32>) -> Option<Rectangle<f32>> { let x = self.x.max(other.x); let y = self.y.max(other.y); let lower_right_x = (self.x + self.width).min(other.x + other.width); let lower_right_y = (self.y + self.height).min(other.y + other.height); let width = lower_right_x - x; let height = lower_right_y - y; if width > 0.0 && height > 0.0 { Some(Rectangle { x, y, width, height, }) } else { None } } /// Returns whether the [`Rectangle`] intersects with the given one. pub fn intersects(&self, other: &Self) -> bool { self.intersection(other).is_some() } /// Computes the union with the given [`Rectangle`]. pub fn union(&self, other: &Self) -> Self { let x = self.x.min(other.x); let y = self.y.min(other.y); let lower_right_x = (self.x + self.width).max(other.x + other.width); let lower_right_y = (self.y + self.height).max(other.y + other.height); let width = lower_right_x - x; let height = lower_right_y - y; Rectangle { x, y, width, height, } } /// Rounds the [`Rectangle`] coordinates. pub fn round(self) -> Self { let top_left = self.position().round(); let bottom_right = (self.position() + Vector::from(self.size())).round(); Self { x: top_left.x, y: top_left.y, width: bottom_right.x - top_left.x, height: bottom_right.y - top_left.y, } } /// Snaps the [`Rectangle`] to __unsigned__ integer coordinates. pub fn snap(self) -> Option<Rectangle<u32>> { let rounded = self.round(); if rounded.width < 1.0 || rounded.height < 1.0 { return None; } Some(Rectangle { x: rounded.x as u32, y: rounded.y as u32, width: rounded.width as u32, height: rounded.height as u32, }) } /// Expands the [`Rectangle`] a given amount. pub fn expand(self, padding: impl Into<Padding>) -> Self { let padding = padding.into(); Self { x: self.x - padding.left, y: self.y - padding.top, width: self.width + padding.x(), height: self.height + padding.y(), } } /// Shrinks the [`Rectangle`] a given amount. pub fn shrink(self, padding: impl Into<Padding>) -> Self { let padding = padding.into(); Self { x: self.x + padding.left, y: self.y + padding.top, width: self.width - padding.x(), height: self.height - padding.y(), } } /// Rotates the [`Rectangle`] and returns the smallest [`Rectangle`] /// containing it. pub fn rotate(self, rotation: Radians) -> Self { let size = self.size().rotate(rotation); let position = Point::new( self.center_x() - size.width / 2.0, self.center_y() - size.height / 2.0, ); Self::new(position, size) } /// Scales the [`Rectangle`] without changing its position, effectively /// "zooming" it. pub fn zoom(self, zoom: f32) -> Self { Self { x: self.x - (self.width * (zoom - 1.0)) / 2.0, y: self.y - (self.height * (zoom - 1.0)) / 2.0, width: self.width * zoom, height: self.height * zoom, } } /// Returns the top-left position to render an object of the given [`Size`]. /// inside the [`Rectangle`] that is anchored to the edge or corner /// defined by the alignment arguments. pub fn anchor( &self, size: Size, align_x: impl Into<alignment::Horizontal>, align_y: impl Into<alignment::Vertical>, ) -> Point { let x = match align_x.into() { alignment::Horizontal::Left => self.x, alignment::Horizontal::Center => self.x + (self.width - size.width) / 2.0, alignment::Horizontal::Right => self.x + self.width - size.width, }; let y = match align_y.into() { alignment::Vertical::Top => self.y, alignment::Vertical::Center => self.y + (self.height - size.height) / 2.0, alignment::Vertical::Bottom => self.y + self.height - size.height, }; Point::new(x, y) } } impl std::ops::Mul<f32> for Rectangle<f32> { type Output = Self; fn mul(self, scale: f32) -> Self { Self { x: self.x * scale, y: self.y * scale, width: self.width * scale, height: self.height * scale, } } } impl From<Rectangle<u32>> for Rectangle<f32> { fn from(rectangle: Rectangle<u32>) -> Rectangle<f32> { Rectangle { x: rectangle.x as f32, y: rectangle.y as f32, width: rectangle.width as f32, height: rectangle.height as f32, } } } impl<T> std::ops::Add<Vector<T>> for Rectangle<T> where T: std::ops::Add<Output = T>, { type Output = Rectangle<T>; fn add(self, translation: Vector<T>) -> Self { Rectangle { x: self.x + translation.x, y: self.y + translation.y, ..self } } } impl<T> std::ops::Sub<Vector<T>> for Rectangle<T> where T: std::ops::Sub<Output = T>, { type Output = Rectangle<T>; fn sub(self, translation: Vector<T>) -> Self { Rectangle { x: self.x - translation.x, y: self.y - translation.y, ..self } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/time.rs
core/src/time.rs
//! Keep track of time, both in native and web platforms! pub use web_time::Duration; pub use web_time::Instant; pub use web_time::SystemTime; /// Creates a [`Duration`] representing the given amount of milliseconds. pub fn milliseconds(milliseconds: u64) -> Duration { Duration::from_millis(milliseconds) } /// Creates a [`Duration`] representing the given amount of seconds. pub fn seconds(seconds: u64) -> Duration { Duration::from_secs(seconds) } /// Creates a [`Duration`] representing the given amount of minutes. pub fn minutes(minutes: u64) -> Duration { seconds(minutes * 60) } /// Creates a [`Duration`] representing the given amount of hours. pub fn hours(hours: u64) -> Duration { minutes(hours * 60) } /// Creates a [`Duration`] representing the given amount of days. pub fn days(days: u64) -> Duration { hours(days * 24) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/alignment.rs
core/src/alignment.rs
//! Align and position widgets. /// Alignment on the axis of a container. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Alignment { /// Align at the start of the axis. Start, /// Align at the center of the axis. Center, /// Align at the end of the axis. End, } impl From<Horizontal> for Alignment { fn from(horizontal: Horizontal) -> Self { match horizontal { Horizontal::Left => Self::Start, Horizontal::Center => Self::Center, Horizontal::Right => Self::End, } } } impl From<Vertical> for Alignment { fn from(vertical: Vertical) -> Self { match vertical { Vertical::Top => Self::Start, Vertical::Center => Self::Center, Vertical::Bottom => Self::End, } } } /// The horizontal [`Alignment`] of some resource. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Horizontal { /// Align left Left, /// Horizontally centered Center, /// Align right Right, } impl From<Alignment> for Horizontal { fn from(alignment: Alignment) -> Self { match alignment { Alignment::Start => Self::Left, Alignment::Center => Self::Center, Alignment::End => Self::Right, } } } /// The vertical [`Alignment`] of some resource. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Vertical { /// Align top Top, /// Vertically centered Center, /// Align bottom Bottom, } impl From<Alignment> for Vertical { fn from(alignment: Alignment) -> Self { match alignment { Alignment::Start => Self::Top, Alignment::Center => Self::Center, Alignment::End => Self::Bottom, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/shell.rs
core/src/shell.rs
use crate::InputMethod; use crate::event; use crate::window; /// A connection to the state of a shell. /// /// A [`Widget`] can leverage a [`Shell`] to trigger changes in an application, /// like publishing messages or invalidating the current layout. /// /// [`Widget`]: crate::Widget #[derive(Debug)] pub struct Shell<'a, Message> { messages: &'a mut Vec<Message>, event_status: event::Status, redraw_request: window::RedrawRequest, input_method: InputMethod, is_layout_invalid: bool, are_widgets_invalid: bool, } impl<'a, Message> Shell<'a, Message> { /// Creates a new [`Shell`] with the provided buffer of messages. pub fn new(messages: &'a mut Vec<Message>) -> Self { Self { messages, event_status: event::Status::Ignored, redraw_request: window::RedrawRequest::Wait, is_layout_invalid: false, are_widgets_invalid: false, input_method: InputMethod::Disabled, } } /// Returns true if the [`Shell`] contains no published messages #[must_use] pub fn is_empty(&self) -> bool { self.messages.is_empty() } /// Publish the given `Message` for an application to process it. pub fn publish(&mut self, message: Message) { self.messages.push(message); } /// Marks the current event as captured. Prevents "event bubbling". /// /// A widget should capture an event when no ancestor should /// handle it. pub fn capture_event(&mut self) { self.event_status = event::Status::Captured; } /// Returns the current [`event::Status`] of the [`Shell`]. #[must_use] pub fn event_status(&self) -> event::Status { self.event_status } /// Returns whether the current event has been captured. #[must_use] pub fn is_event_captured(&self) -> bool { self.event_status == event::Status::Captured } /// Requests a new frame to be drawn as soon as possible. pub fn request_redraw(&mut self) { self.redraw_request = window::RedrawRequest::NextFrame; } /// Requests a new frame to be drawn at the given [`window::RedrawRequest`]. pub fn request_redraw_at(&mut self, redraw_request: impl Into<window::RedrawRequest>) { self.redraw_request = self.redraw_request.min(redraw_request.into()); } /// Returns the request a redraw should happen, if any. #[must_use] pub fn redraw_request(&self) -> window::RedrawRequest { self.redraw_request } /// Replaces the redraw request of the [`Shell`]; without conflict resolution. /// /// This is useful if you want to overwrite the redraw request to a previous value. /// Since it's a fairly advanced use case and should rarely be used, it is a static /// method. pub fn replace_redraw_request(shell: &mut Self, redraw_request: window::RedrawRequest) { shell.redraw_request = redraw_request; } /// Requests the current [`InputMethod`] strategy. /// /// __Important__: This request will only be honored by the /// [`Shell`] only during a [`window::Event::RedrawRequested`]. pub fn request_input_method<T: AsRef<str>>(&mut self, ime: &InputMethod<T>) { self.input_method.merge(ime); } /// Returns the current [`InputMethod`] strategy. #[must_use] pub fn input_method(&self) -> &InputMethod { &self.input_method } /// Returns the current [`InputMethod`] strategy. #[must_use] pub fn input_method_mut(&mut self) -> &mut InputMethod { &mut self.input_method } /// Returns whether the current layout is invalid or not. #[must_use] pub fn is_layout_invalid(&self) -> bool { self.is_layout_invalid } /// Invalidates the current application layout. /// /// The shell will relayout the application widgets. pub fn invalidate_layout(&mut self) { self.is_layout_invalid = true; } /// Triggers the given function if the layout is invalid, cleaning it in the /// process. pub fn revalidate_layout(&mut self, f: impl FnOnce()) { if self.is_layout_invalid { self.is_layout_invalid = false; f(); } } /// Returns whether the widgets of the current application have been /// invalidated. #[must_use] pub fn are_widgets_invalid(&self) -> bool { self.are_widgets_invalid } /// Invalidates the current application widgets. /// /// The shell will rebuild and relayout the widget tree. pub fn invalidate_widgets(&mut self) { self.are_widgets_invalid = true; } /// Merges the current [`Shell`] with another one by applying the given /// function to the messages of the latter. /// /// This method is useful for composition. pub fn merge<B>(&mut self, other: Shell<'_, B>, f: impl Fn(B) -> Message) { self.messages.extend(other.messages.drain(..).map(f)); self.is_layout_invalid = self.is_layout_invalid || other.is_layout_invalid; self.are_widgets_invalid = self.are_widgets_invalid || other.are_widgets_invalid; self.redraw_request = self.redraw_request.min(other.redraw_request); self.event_status = self.event_status.merge(other.event_status); self.input_method.merge(&other.input_method); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/input_method.rs
core/src/input_method.rs
//! Listen to input method events. use crate::{Pixels, Rectangle}; use std::ops::Range; /// The input method strategy of a widget. #[derive(Debug, Clone, PartialEq)] pub enum InputMethod<T = String> { /// Input method is disabled. Disabled, /// Input method is enabled. Enabled { /// The area of the cursor of the input method. /// /// This area should not be covered. cursor: Rectangle, /// The [`Purpose`] of the input method. purpose: Purpose, /// The preedit to overlay on top of the input method dialog, if needed. /// /// Ideally, your widget will show pre-edits on-the-spot; but, since that can /// be tricky, you can instead provide the current pre-edit here and the /// runtime will display it as an overlay (i.e. "Over-the-spot IME"). preedit: Option<Preedit<T>>, }, } /// The pre-edit of an [`InputMethod`]. #[derive(Debug, Clone, PartialEq, Default)] pub struct Preedit<T = String> { /// The current content. pub content: T, /// The selected range of the content. pub selection: Option<Range<usize>>, /// The text size of the content. pub text_size: Option<Pixels>, } impl<T> Preedit<T> { /// Creates a new empty [`Preedit`]. pub fn new() -> Self where T: Default, { Self::default() } /// Turns a [`Preedit`] into its owned version. pub fn to_owned(&self) -> Preedit where T: AsRef<str>, { Preedit { content: self.content.as_ref().to_owned(), selection: self.selection.clone(), text_size: self.text_size, } } } impl Preedit { /// Borrows the contents of a [`Preedit`]. pub fn as_ref(&self) -> Preedit<&str> { Preedit { content: &self.content, selection: self.selection.clone(), text_size: self.text_size, } } } /// The purpose of an [`InputMethod`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Purpose { /// No special hints for the IME (default). #[default] Normal, /// The IME is used for secure input (e.g. passwords). Secure, /// The IME is used to input into a terminal. /// /// For example, that could alter OSK on Wayland to show extra buttons. Terminal, } impl InputMethod { /// Merges two [`InputMethod`] strategies, prioritizing the first one when both open: /// ``` /// # use iced_core::input_method::{InputMethod, Purpose, Preedit}; /// # use iced_core::{Point, Rectangle, Size}; /// /// let open = InputMethod::Enabled { /// cursor: Rectangle::new(Point::ORIGIN, Size::UNIT), /// purpose: Purpose::Normal, /// preedit: Some(Preedit { content: "1".to_owned(), selection: None, text_size: None }), /// }; /// /// let open_2 = InputMethod::Enabled { /// cursor: Rectangle::new(Point::ORIGIN, Size::UNIT), /// purpose: Purpose::Secure, /// preedit: Some(Preedit { content: "2".to_owned(), selection: None, text_size: None }), /// }; /// /// let mut ime = InputMethod::Disabled; /// /// ime.merge(&open); /// assert_eq!(ime, open); /// /// ime.merge(&open_2); /// assert_eq!(ime, open); /// ``` pub fn merge<T: AsRef<str>>(&mut self, other: &InputMethod<T>) { if let InputMethod::Enabled { .. } = self { return; } *self = other.to_owned(); } /// Returns true if the [`InputMethod`] is open. pub fn is_enabled(&self) -> bool { matches!(self, Self::Enabled { .. }) } } impl<T> InputMethod<T> { /// Turns an [`InputMethod`] into its owned version. pub fn to_owned(&self) -> InputMethod where T: AsRef<str>, { match self { Self::Disabled => InputMethod::Disabled, Self::Enabled { cursor, purpose, preedit, } => InputMethod::Enabled { cursor: *cursor, purpose: *purpose, preedit: preedit.as_ref().map(Preedit::to_owned), }, } } } /// Describes [input method](https://en.wikipedia.org/wiki/Input_method) events. /// /// This is also called a "composition event". /// /// Most keypresses using a latin-like keyboard layout simply generate a /// [`keyboard::Event::KeyPressed`](crate::keyboard::Event::KeyPressed). /// However, one couldn't possibly have a key for every single /// unicode character that the user might want to type. The solution operating systems employ is /// to allow the user to type these using _a sequence of keypresses_ instead. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Event { /// Notifies when the IME was opened. /// /// After getting this event you could receive [`Preedit`][Self::Preedit] and /// [`Commit`][Self::Commit] events. You should also start performing IME related requests /// like [`Shell::request_input_method`]. /// /// [`Shell::request_input_method`]: crate::Shell::request_input_method Opened, /// Notifies when a new composing text should be set at the cursor position. /// /// The value represents a pair of the preedit string and the cursor begin position and end /// position. When it's `None`, the cursor should be hidden. When `String` is an empty string /// this indicates that preedit was cleared. /// /// The cursor range is byte-wise indexed. Preedit(String, Option<Range<usize>>), /// Notifies when text should be inserted into the editor widget. /// /// Right before this event, an empty [`Self::Preedit`] event will be issued. Commit(String), /// Notifies when the IME was disabled. /// /// After receiving this event you won't get any more [`Preedit`][Self::Preedit] or /// [`Commit`][Self::Commit] events until the next [`Opened`][Self::Opened] event. You should /// also stop issuing IME related requests like [`Shell::request_input_method`] and clear /// pending preedit text. /// /// [`Shell::request_input_method`]: crate::Shell::request_input_method Closed, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/text.rs
core/src/text.rs
//! Draw and interact with text. pub mod editor; pub mod highlighter; pub mod paragraph; pub use editor::Editor; pub use highlighter::Highlighter; pub use paragraph::Paragraph; use crate::alignment; use crate::{Background, Border, Color, Padding, Pixels, Point, Rectangle, Size}; use std::borrow::Cow; use std::hash::{Hash, Hasher}; /// A paragraph. #[derive(Debug, Clone, Copy)] pub struct Text<Content = String, Font = crate::Font> { /// The content of the paragraph. pub content: Content, /// The bounds of the paragraph. pub bounds: Size, /// The size of the [`Text`] in logical pixels. pub size: Pixels, /// The line height of the [`Text`]. pub line_height: LineHeight, /// The font of the [`Text`]. pub font: Font, /// The horizontal alignment of the [`Text`]. pub align_x: Alignment, /// The vertical alignment of the [`Text`]. pub align_y: alignment::Vertical, /// The [`Shaping`] strategy of the [`Text`]. pub shaping: Shaping, /// The [`Wrapping`] strategy of the [`Text`]. pub wrapping: Wrapping, /// The scale factor that may be used to internally scale the layout /// calculation of the [`Paragraph`] and leverage metrics hinting. /// /// Effectively, this defines the "base" layout that will be used for /// linear scaling. /// /// If `None`, hinting will be disabled and subpixel positioning will be /// performed. pub hint_factor: Option<f32>, } impl<Content, Font> Text<Content, Font> where Font: Copy, { /// Returns a new [`Text`] replacing only the content with the /// given value. pub fn with_content<T>(&self, content: T) -> Text<T, Font> { Text { content, bounds: self.bounds, size: self.size, line_height: self.line_height, font: self.font, align_x: self.align_x, align_y: self.align_y, shaping: self.shaping, wrapping: self.wrapping, hint_factor: self.hint_factor, } } } impl<Content, Font> Text<Content, Font> where Content: AsRef<str>, Font: Copy, { /// Returns a borrowed version of [`Text`]. pub fn as_ref(&self) -> Text<&str, Font> { self.with_content(self.content.as_ref()) } } /// The alignment of some text. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Alignment { /// No specific alignment. /// /// Left-to-right text will be aligned to the left, while /// right-to-left text will be aligned to the right. #[default] Default, /// Align text to the left. Left, /// Center text. Center, /// Align text to the right. Right, /// Justify text. Justified, } impl From<alignment::Horizontal> for Alignment { fn from(alignment: alignment::Horizontal) -> Self { match alignment { alignment::Horizontal::Left => Self::Left, alignment::Horizontal::Center => Self::Center, alignment::Horizontal::Right => Self::Right, } } } impl From<crate::Alignment> for Alignment { fn from(alignment: crate::Alignment) -> Self { match alignment { crate::Alignment::Start => Self::Left, crate::Alignment::Center => Self::Center, crate::Alignment::End => Self::Right, } } } impl From<Alignment> for alignment::Horizontal { fn from(alignment: Alignment) -> Self { match alignment { Alignment::Default | Alignment::Left | Alignment::Justified => { alignment::Horizontal::Left } Alignment::Center => alignment::Horizontal::Center, Alignment::Right => alignment::Horizontal::Right, } } } /// The shaping strategy of some text. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Shaping { /// Auto-detect the best shaping strategy from the text. /// /// This strategy will use [`Basic`](Self::Basic) shaping if the /// text consists of only ASCII characters; otherwise, it will /// use [`Advanced`](Self::Advanced) shaping. /// /// This is the default, if neither the `basic-shaping` nor `advanced-shaping` /// features are enabled. Auto, /// No shaping and no font fallback. /// /// This shaping strategy is very cheap, but it will not display complex /// scripts properly nor try to find missing glyphs in your system fonts. /// /// You should use this strategy when you have complete control of the text /// and the font you are displaying in your application. /// /// This will be the default if the `basic-shaping` feature is enabled and /// the `advanced-shaping` feature is disabled. Basic, /// Advanced text shaping and font fallback. /// /// You will need to enable this flag if the text contains a complex /// script, the font used needs it, and/or multiple fonts in your system /// may be needed to display all of the glyphs. /// /// Advanced shaping is expensive! You should only enable it when necessary. /// /// This will be the default if the `advanced-shaping` feature is enabled. Advanced, } impl Default for Shaping { fn default() -> Self { if cfg!(feature = "advanced-shaping") { Self::Advanced } else if cfg!(feature = "basic-shaping") { Self::Basic } else { Self::Auto } } } /// The wrapping strategy of some text. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Wrapping { /// No wrapping. None, /// Wraps at the word level. /// /// This is the default. #[default] Word, /// Wraps at the glyph level. Glyph, /// Wraps at the word level, or fallback to glyph level if a word can't fit on a line by itself. WordOrGlyph, } /// The height of a line of text in a paragraph. #[derive(Debug, Clone, Copy, PartialEq)] pub enum LineHeight { /// A factor of the size of the text. Relative(f32), /// An absolute height in logical pixels. Absolute(Pixels), } impl LineHeight { /// Returns the [`LineHeight`] in absolute logical pixels. pub fn to_absolute(self, text_size: Pixels) -> Pixels { match self { Self::Relative(factor) => Pixels(factor * text_size.0), Self::Absolute(pixels) => pixels, } } } impl Default for LineHeight { fn default() -> Self { Self::Relative(1.3) } } impl From<f32> for LineHeight { fn from(factor: f32) -> Self { Self::Relative(factor) } } impl From<Pixels> for LineHeight { fn from(pixels: Pixels) -> Self { Self::Absolute(pixels) } } impl Hash for LineHeight { fn hash<H: Hasher>(&self, state: &mut H) { match self { Self::Relative(factor) => { state.write_u8(0); factor.to_bits().hash(state); } Self::Absolute(pixels) => { state.write_u8(1); f32::from(*pixels).to_bits().hash(state); } } } } /// The result of hit testing on text. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Hit { /// The point was within the bounds of the returned character index. CharOffset(usize), } impl Hit { /// Computes the cursor position of the [`Hit`] . pub fn cursor(self) -> usize { match self { Self::CharOffset(i) => i, } } } /// The difference detected in some text. /// /// You will obtain a [`Difference`] when you [`compare`] a [`Paragraph`] with some /// [`Text`]. /// /// [`compare`]: Paragraph::compare #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Difference { /// No difference. /// /// The text can be reused as it is! None, /// A bounds difference. /// /// This normally means a relayout is necessary, but the shape of the text can /// be reused. Bounds, /// A shape difference. /// /// The contents, alignment, sizes, fonts, or any other essential attributes /// of the shape of the text have changed. A complete reshape and relayout of /// the text is necessary. Shape, } /// A renderer capable of measuring and drawing [`Text`]. pub trait Renderer: crate::Renderer { /// The font type used. type Font: Copy + PartialEq; /// The [`Paragraph`] of this [`Renderer`]. type Paragraph: Paragraph<Font = Self::Font> + 'static; /// The [`Editor`] of this [`Renderer`]. type Editor: Editor<Font = Self::Font> + 'static; /// The icon font of the backend. const ICON_FONT: Self::Font; /// The `char` representing a ✔ icon in the [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const CHECKMARK_ICON: char; /// The `char` representing a ▼ icon in the built-in [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const ARROW_DOWN_ICON: char; /// The `char` representing a ^ icon in the built-in [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const SCROLL_UP_ICON: char; /// The `char` representing a v icon in the built-in [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const SCROLL_DOWN_ICON: char; /// The `char` representing a < icon in the built-in [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const SCROLL_LEFT_ICON: char; /// The `char` representing a > icon in the built-in [`ICON_FONT`]. /// /// [`ICON_FONT`]: Self::ICON_FONT const SCROLL_RIGHT_ICON: char; /// The 'char' representing the iced logo in the built-in ['ICON_FONT']. /// /// ['ICON_FONT']: Self::ICON_FONT const ICED_LOGO: char; /// Returns the default [`Self::Font`]. fn default_font(&self) -> Self::Font; /// Returns the default size of [`Text`]. fn default_size(&self) -> Pixels; /// Draws the given [`Paragraph`] at the given position and with the given /// [`Color`]. fn fill_paragraph( &mut self, text: &Self::Paragraph, position: Point, color: Color, clip_bounds: Rectangle, ); /// Draws the given [`Editor`] at the given position and with the given /// [`Color`]. fn fill_editor( &mut self, editor: &Self::Editor, position: Point, color: Color, clip_bounds: Rectangle, ); /// Draws the given [`Text`] at the given position and with the given /// [`Color`]. fn fill_text( &mut self, text: Text<String, Self::Font>, position: Point, color: Color, clip_bounds: Rectangle, ); } /// A span of text. #[derive(Debug, Clone)] pub struct Span<'a, Link = (), Font = crate::Font> { /// The [`Fragment`] of text. pub text: Fragment<'a>, /// The size of the [`Span`] in [`Pixels`]. pub size: Option<Pixels>, /// The [`LineHeight`] of the [`Span`]. pub line_height: Option<LineHeight>, /// The font of the [`Span`]. pub font: Option<Font>, /// The [`Color`] of the [`Span`]. pub color: Option<Color>, /// The link of the [`Span`]. pub link: Option<Link>, /// The [`Highlight`] of the [`Span`]. pub highlight: Option<Highlight>, /// The [`Padding`] of the [`Span`]. /// /// Currently, it only affects the bounds of the [`Highlight`]. pub padding: Padding, /// Whether the [`Span`] should be underlined or not. pub underline: bool, /// Whether the [`Span`] should be struck through or not. pub strikethrough: bool, } /// A text highlight. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Highlight { /// The [`Background`] of the highlight. pub background: Background, /// The [`Border`] of the highlight. pub border: Border, } impl<'a, Link, Font> Span<'a, Link, Font> { /// Creates a new [`Span`] of text with the given text fragment. pub fn new(fragment: impl IntoFragment<'a>) -> Self { Self { text: fragment.into_fragment(), ..Self::default() } } /// Sets the size of the [`Span`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = Some(size.into()); self } /// Sets the [`LineHeight`] of the [`Span`]. pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self { self.line_height = Some(line_height.into()); self } /// Sets the font of the [`Span`]. pub fn font(mut self, font: impl Into<Font>) -> Self { self.font = Some(font.into()); self } /// Sets the font of the [`Span`], if any. pub fn font_maybe(mut self, font: Option<impl Into<Font>>) -> Self { self.font = font.map(Into::into); self } /// Sets the [`Color`] of the [`Span`]. pub fn color(mut self, color: impl Into<Color>) -> Self { self.color = Some(color.into()); self } /// Sets the [`Color`] of the [`Span`], if any. pub fn color_maybe(mut self, color: Option<impl Into<Color>>) -> Self { self.color = color.map(Into::into); self } /// Sets the link of the [`Span`]. pub fn link(mut self, link: impl Into<Link>) -> Self { self.link = Some(link.into()); self } /// Sets the link of the [`Span`], if any. pub fn link_maybe(mut self, link: Option<impl Into<Link>>) -> Self { self.link = link.map(Into::into); self } /// Sets the [`Background`] of the [`Span`]. pub fn background(self, background: impl Into<Background>) -> Self { self.background_maybe(Some(background)) } /// Sets the [`Background`] of the [`Span`], if any. pub fn background_maybe(mut self, background: Option<impl Into<Background>>) -> Self { let Some(background) = background else { return self; }; match &mut self.highlight { Some(highlight) => { highlight.background = background.into(); } None => { self.highlight = Some(Highlight { background: background.into(), border: Border::default(), }); } } self } /// Sets the [`Border`] of the [`Span`]. pub fn border(self, border: impl Into<Border>) -> Self { self.border_maybe(Some(border)) } /// Sets the [`Border`] of the [`Span`], if any. pub fn border_maybe(mut self, border: Option<impl Into<Border>>) -> Self { let Some(border) = border else { return self; }; match &mut self.highlight { Some(highlight) => { highlight.border = border.into(); } None => { self.highlight = Some(Highlight { border: border.into(), background: Background::Color(Color::TRANSPARENT), }); } } self } /// Sets the [`Padding`] of the [`Span`]. /// /// It only affects the [`background`] and [`border`] of the /// [`Span`], currently. /// /// [`background`]: Self::background /// [`border`]: Self::border pub fn padding(mut self, padding: impl Into<Padding>) -> Self { self.padding = padding.into(); self } /// Sets whether the [`Span`] should be underlined or not. pub fn underline(mut self, underline: bool) -> Self { self.underline = underline; self } /// Sets whether the [`Span`] should be struck through or not. pub fn strikethrough(mut self, strikethrough: bool) -> Self { self.strikethrough = strikethrough; self } /// Turns the [`Span`] into a static one. pub fn to_static(self) -> Span<'static, Link, Font> { Span { text: Cow::Owned(self.text.into_owned()), size: self.size, line_height: self.line_height, font: self.font, color: self.color, link: self.link, highlight: self.highlight, padding: self.padding, underline: self.underline, strikethrough: self.strikethrough, } } } impl<Link, Font> Default for Span<'_, Link, Font> { fn default() -> Self { Self { text: Cow::default(), size: None, line_height: None, font: None, color: None, link: None, highlight: None, padding: Padding::default(), underline: false, strikethrough: false, } } } impl<'a, Link, Font> From<&'a str> for Span<'a, Link, Font> { fn from(value: &'a str) -> Self { Span::new(value) } } impl<Link, Font: PartialEq> PartialEq for Span<'_, Link, Font> { fn eq(&self, other: &Self) -> bool { self.text == other.text && self.size == other.size && self.line_height == other.line_height && self.font == other.font && self.color == other.color } } /// A fragment of [`Text`]. /// /// This is just an alias to a string that may be either /// borrowed or owned. pub type Fragment<'a> = Cow<'a, str>; /// A trait for converting a value to some text [`Fragment`]. pub trait IntoFragment<'a> { /// Converts the value to some text [`Fragment`]. fn into_fragment(self) -> Fragment<'a>; } impl<'a> IntoFragment<'a> for Fragment<'a> { fn into_fragment(self) -> Fragment<'a> { self } } impl<'a> IntoFragment<'a> for &'a Fragment<'_> { fn into_fragment(self) -> Fragment<'a> { Fragment::Borrowed(self) } } impl<'a> IntoFragment<'a> for &'a str { fn into_fragment(self) -> Fragment<'a> { Fragment::Borrowed(self) } } impl<'a> IntoFragment<'a> for &'a String { fn into_fragment(self) -> Fragment<'a> { Fragment::Borrowed(self.as_str()) } } impl<'a> IntoFragment<'a> for String { fn into_fragment(self) -> Fragment<'a> { Fragment::Owned(self) } } macro_rules! into_fragment { ($type:ty) => { impl<'a> IntoFragment<'a> for $type { fn into_fragment(self) -> Fragment<'a> { Fragment::Owned(self.to_string()) } } impl<'a> IntoFragment<'a> for &$type { fn into_fragment(self) -> Fragment<'a> { Fragment::Owned(self.to_string()) } } }; } into_fragment!(char); into_fragment!(bool); into_fragment!(u8); into_fragment!(u16); into_fragment!(u32); into_fragment!(u64); into_fragment!(u128); into_fragment!(usize); into_fragment!(i8); into_fragment!(i16); into_fragment!(i32); into_fragment!(i64); into_fragment!(i128); into_fragment!(isize); into_fragment!(f32); into_fragment!(f64);
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/font.rs
core/src/font.rs
//! Load and use fonts. use std::hash::Hash; /// A font. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct Font { /// The [`Family`] of the [`Font`]. pub family: Family, /// The [`Weight`] of the [`Font`]. pub weight: Weight, /// The [`Stretch`] of the [`Font`]. pub stretch: Stretch, /// The [`Style`] of the [`Font`]. pub style: Style, } impl Font { /// A non-monospaced sans-serif font with normal [`Weight`]. pub const DEFAULT: Font = Font { family: Family::SansSerif, weight: Weight::Normal, stretch: Stretch::Normal, style: Style::Normal, }; /// A monospaced font with normal [`Weight`]. pub const MONOSPACE: Font = Font { family: Family::Monospace, ..Self::DEFAULT }; /// Creates a non-monospaced [`Font`] with the given [`Family::Name`] and /// normal [`Weight`]. pub const fn with_name(name: &'static str) -> Self { Font { family: Family::Name(name), ..Self::DEFAULT } } } /// A font family. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Family { /// The name of a font family of choice. Name(&'static str), /// Serif fonts represent the formal text style for a script. Serif, /// Glyphs in sans-serif fonts, as the term is used in CSS, are generally low /// contrast and have stroke endings that are plain — without any flaring, /// cross stroke, or other ornamentation. #[default] SansSerif, /// Glyphs in cursive fonts generally use a more informal script style, and /// the result looks more like handwritten pen or brush writing than printed /// letterwork. Cursive, /// Fantasy fonts are primarily decorative or expressive fonts that contain /// decorative or expressive representations of characters. Fantasy, /// The sole criterion of a monospace font is that all glyphs have the same /// fixed width. Monospace, } /// The weight of some text. #[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Weight { Thin, ExtraLight, Light, #[default] Normal, Medium, Semibold, Bold, ExtraBold, Black, } /// The width of some text. #[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Stretch { UltraCondensed, ExtraCondensed, Condensed, SemiCondensed, #[default] Normal, SemiExpanded, Expanded, ExtraExpanded, UltraExpanded, } /// The style of some text. #[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Style { #[default] Normal, Italic, Oblique, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/transformation.rs
core/src/transformation.rs
use crate::{Point, Rectangle, Size, Vector}; use glam::{Mat4, Vec3, Vec4}; use std::ops::Mul; /// A 2D transformation matrix. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Transformation(Mat4); impl Transformation { /// A [`Transformation`] that preserves whatever is transformed. pub const IDENTITY: Self = Self(Mat4::IDENTITY); /// Creates an orthographic projection. #[rustfmt::skip] pub fn orthographic(width: u32, height: u32) -> Self{ Self(Mat4::orthographic_rh_gl( 0.0, width as f32, height as f32, 0.0, -1.0, 1.0 )) } /// Creates a translate transformation. pub fn translate(x: f32, y: f32) -> Self { Self(Mat4::from_translation(Vec3::new(x, y, 0.0))) } /// Creates a uniform scaling transformation. pub fn scale(scaling: f32) -> Self { Self(Mat4::from_scale(Vec3::new(scaling, scaling, 1.0))) } /// Returns the inverse of the [`Transformation`]. pub fn inverse(self) -> Self { Self(self.0.inverse()) } /// Returns the scale factor of the [`Transformation`]. pub fn scale_factor(&self) -> f32 { self.0.x_axis.x } /// Returns the translation of the [`Transformation`]. pub fn translation(&self) -> Vector { Vector::new(self.0.w_axis.x, self.0.w_axis.y) } } impl Default for Transformation { fn default() -> Self { Transformation::IDENTITY } } impl Mul for Transformation { type Output = Self; fn mul(self, rhs: Self) -> Self { Self(self.0 * rhs.0) } } impl Mul<Transformation> for Point { type Output = Self; fn mul(self, transformation: Transformation) -> Self { let point = transformation .0 .mul_vec4(Vec4::new(self.x, self.y, 1.0, 1.0)); Point::new(point.x, point.y) } } impl Mul<Transformation> for Vector { type Output = Self; fn mul(self, transformation: Transformation) -> Self { let new_vector = transformation .0 .mul_vec4(Vec4::new(self.x, self.y, 1.0, 0.0)); Vector::new(new_vector.x, new_vector.y) } } impl Mul<Transformation> for Size { type Output = Self; fn mul(self, transformation: Transformation) -> Self { let new_size = transformation .0 .mul_vec4(Vec4::new(self.width, self.height, 1.0, 0.0)); Size::new(new_size.x, new_size.y) } } impl Mul<Transformation> for Rectangle { type Output = Self; fn mul(self, transformation: Transformation) -> Self { let position = self.position(); let size = self.size(); Self::new(position * transformation, size * transformation) } } impl AsRef<[f32; 16]> for Transformation { fn as_ref(&self) -> &[f32; 16] { self.0.as_ref() } } impl From<Transformation> for [f32; 16] { fn from(t: Transformation) -> [f32; 16] { *t.as_ref() } } impl From<Transformation> for Mat4 { fn from(transformation: Transformation) -> Self { transformation.0 } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/angle.rs
core/src/angle.rs
use crate::{Point, Rectangle, Vector}; use std::f32::consts::{FRAC_PI_2, PI}; use std::fmt::Display; use std::ops::{Add, AddAssign, Div, Mul, RangeInclusive, Rem, Sub, SubAssign}; /// Degrees #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] pub struct Degrees(pub f32); impl Degrees { /// The range of degrees of a circle. pub const RANGE: RangeInclusive<Self> = Self(0.0)..=Self(360.0); } impl PartialEq<f32> for Degrees { fn eq(&self, other: &f32) -> bool { self.0.eq(other) } } impl PartialOrd<f32> for Degrees { fn partial_cmp(&self, other: &f32) -> Option<std::cmp::Ordering> { self.0.partial_cmp(other) } } impl From<f32> for Degrees { fn from(degrees: f32) -> Self { Self(degrees) } } impl From<u8> for Degrees { fn from(degrees: u8) -> Self { Self(f32::from(degrees)) } } impl From<Degrees> for f32 { fn from(degrees: Degrees) -> Self { degrees.0 } } impl From<Degrees> for f64 { fn from(degrees: Degrees) -> Self { Self::from(degrees.0) } } impl Mul<f32> for Degrees { type Output = Degrees; fn mul(self, rhs: f32) -> Self::Output { Self(self.0 * rhs) } } impl num_traits::FromPrimitive for Degrees { fn from_i64(n: i64) -> Option<Self> { Some(Self(n as f32)) } fn from_u64(n: u64) -> Option<Self> { Some(Self(n as f32)) } fn from_f64(n: f64) -> Option<Self> { Some(Self(n as f32)) } } /// Radians #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] pub struct Radians(pub f32); impl Radians { /// The range of radians of a circle. pub const RANGE: RangeInclusive<Self> = Self(0.0)..=Self(2.0 * PI); /// The amount of radians in half a circle. pub const PI: Self = Self(PI); /// Calculates the line in which the angle intercepts the `bounds`. pub fn to_distance(&self, bounds: &Rectangle) -> (Point, Point) { let angle = self.0 - FRAC_PI_2; let r = Vector::new(f32::cos(angle), f32::sin(angle)); let distance_to_rect = f32::max( f32::abs(r.x * bounds.width / 2.0), f32::abs(r.y * bounds.height / 2.0), ); let start = bounds.center() - r * distance_to_rect; let end = bounds.center() + r * distance_to_rect; (start, end) } } impl From<Degrees> for Radians { fn from(degrees: Degrees) -> Self { Self(degrees.0 * PI / 180.0) } } impl From<f32> for Radians { fn from(radians: f32) -> Self { Self(radians) } } impl From<u8> for Radians { fn from(radians: u8) -> Self { Self(f32::from(radians)) } } impl From<Radians> for f32 { fn from(radians: Radians) -> Self { radians.0 } } impl From<Radians> for f64 { fn from(radians: Radians) -> Self { Self::from(radians.0) } } impl num_traits::FromPrimitive for Radians { fn from_i64(n: i64) -> Option<Self> { Some(Self(n as f32)) } fn from_u64(n: u64) -> Option<Self> { Some(Self(n as f32)) } fn from_f64(n: f64) -> Option<Self> { Some(Self(n as f32)) } } impl Sub for Radians { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { Self(self.0 - rhs.0) } } impl SubAssign for Radians { fn sub_assign(&mut self, rhs: Self) { self.0 = self.0 - rhs.0; } } impl Add for Radians { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0) } } impl Add<Degrees> for Radians { type Output = Self; fn add(self, rhs: Degrees) -> Self::Output { Self(self.0 + rhs.0.to_radians()) } } impl AddAssign for Radians { fn add_assign(&mut self, rhs: Radians) { self.0 = self.0 + rhs.0; } } impl Mul for Radians { type Output = Self; fn mul(self, rhs: Radians) -> Self::Output { Radians(self.0 * rhs.0) } } impl Mul<f32> for Radians { type Output = Self; fn mul(self, rhs: f32) -> Self::Output { Self(self.0 * rhs) } } impl Mul<Radians> for f32 { type Output = Radians; fn mul(self, rhs: Radians) -> Self::Output { Radians(self * rhs.0) } } impl Div<f32> for Radians { type Output = Self; fn div(self, rhs: f32) -> Self::Output { Radians(self.0 / rhs) } } impl Div for Radians { type Output = Self; fn div(self, rhs: Self) -> Self::Output { Self(self.0 / rhs.0) } } impl Rem for Radians { type Output = Self; fn rem(self, rhs: Self) -> Self::Output { Self(self.0 % rhs.0) } } impl PartialEq<f32> for Radians { fn eq(&self, other: &f32) -> bool { self.0.eq(other) } } impl PartialOrd<f32> for Radians { fn partial_cmp(&self, other: &f32) -> Option<std::cmp::Ordering> { self.0.partial_cmp(other) } } impl Display for Radians { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} rad", self.0) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/rotation.rs
core/src/rotation.rs
//! Control the rotation of some content (like an image) within a space. use crate::{Degrees, Radians, Size}; /// The strategy used to rotate the content. /// /// This is used to control the behavior of the layout when the content is rotated /// by a certain angle. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Rotation { /// The element will float while rotating. The layout will be kept exactly as it was /// before the rotation. /// /// This is especially useful when used for animations, as it will avoid the /// layout being shifted or resized when smoothly i.e. an icon. /// /// This is the default. Floating(Radians), /// The element will be solid while rotating. The layout will be adjusted to fit /// the rotated content. /// /// This allows you to rotate an image and have the layout adjust to fit the new /// size of the image. Solid(Radians), } impl Rotation { /// Returns the angle of the [`Rotation`] in [`Radians`]. pub fn radians(self) -> Radians { match self { Rotation::Floating(radians) | Rotation::Solid(radians) => radians, } } /// Returns a mutable reference to the angle of the [`Rotation`] in [`Radians`]. pub fn radians_mut(&mut self) -> &mut Radians { match self { Rotation::Floating(radians) | Rotation::Solid(radians) => radians, } } /// Returns the angle of the [`Rotation`] in [`Degrees`]. pub fn degrees(self) -> Degrees { Degrees(self.radians().0.to_degrees()) } /// Applies the [`Rotation`] to the given [`Size`], returning /// the minimum [`Size`] containing the rotated one. pub fn apply(self, size: Size) -> Size { match self { Self::Floating(_) => size, Self::Solid(rotation) => size.rotate(rotation), } } } impl Default for Rotation { fn default() -> Self { Self::Floating(Radians(0.0)) } } impl From<Radians> for Rotation { fn from(radians: Radians) -> Self { Self::Floating(radians) } } impl From<f32> for Rotation { fn from(radians: f32) -> Self { Self::Floating(Radians(radians)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/layout.rs
core/src/layout.rs
//! Position your widgets properly. mod limits; mod node; pub mod flex; pub use limits::Limits; pub use node::Node; use crate::{Length, Padding, Point, Rectangle, Size, Vector}; /// The bounds of a [`Node`] and its children, using absolute coordinates. #[derive(Debug, Clone, Copy)] pub struct Layout<'a> { position: Point, node: &'a Node, } impl<'a> Layout<'a> { /// Creates a new [`Layout`] for the given [`Node`] at the origin. pub fn new(node: &'a Node) -> Self { Self::with_offset(Vector::new(0.0, 0.0), node) } /// Creates a new [`Layout`] for the given [`Node`] with the provided offset /// from the origin. pub fn with_offset(offset: Vector, node: &'a Node) -> Self { let bounds = node.bounds(); Self { position: Point::new(bounds.x, bounds.y) + offset, node, } } /// Returns the position of the [`Layout`]. pub fn position(&self) -> Point { self.position } /// Returns the bounds of the [`Layout`]. /// /// The returned [`Rectangle`] describes the position and size of a /// [`Node`]. pub fn bounds(&self) -> Rectangle { let bounds = self.node.bounds(); Rectangle { x: self.position.x, y: self.position.y, width: bounds.width, height: bounds.height, } } /// Returns an iterator over the children of this [`Layout`]. pub fn children(self) -> impl DoubleEndedIterator<Item = Layout<'a>> + ExactSizeIterator { self.node.children().iter().map(move |node| { Layout::with_offset(Vector::new(self.position.x, self.position.y), node) }) } /// Returns the [`Layout`] of the child at the given index. /// /// This can be useful if you ever need to access children out of order /// for layering purposes. /// /// # Panics /// Panics if index is out of bounds. pub fn child(self, index: usize) -> Layout<'a> { let node = &self.node.children()[index]; Layout::with_offset(Vector::new(self.position.x, self.position.y), node) } } /// Produces a [`Node`] with two children nodes one right next to each other. pub fn next_to_each_other( limits: &Limits, spacing: f32, left: impl FnOnce(&Limits) -> Node, right: impl FnOnce(&Limits) -> Node, ) -> Node { let left_node = left(limits); let left_size = left_node.size(); let right_limits = limits.shrink(Size::new(left_size.width + spacing, 0.0)); let right_node = right(&right_limits); let right_size = right_node.size(); let (left_y, right_y) = if left_size.height > right_size.height { (0.0, (left_size.height - right_size.height) / 2.0) } else { ((right_size.height - left_size.height) / 2.0, 0.0) }; Node::with_children( Size::new( left_size.width + spacing + right_size.width, left_size.height.max(right_size.height), ), vec![ left_node.move_to(Point::new(0.0, left_y)), right_node.move_to(Point::new(left_size.width + spacing, right_y)), ], ) } /// Computes the resulting [`Node`] that fits the [`Limits`] given /// some width and height requirements and no intrinsic size. pub fn atomic(limits: &Limits, width: impl Into<Length>, height: impl Into<Length>) -> Node { let width = width.into(); let height = height.into(); Node::new(limits.resolve(width, height, Size::ZERO)) } /// Computes the resulting [`Node`] that fits the [`Limits`] given /// some width and height requirements and a closure that produces /// the intrinsic [`Size`] inside the given [`Limits`]. pub fn sized( limits: &Limits, width: impl Into<Length>, height: impl Into<Length>, f: impl FnOnce(&Limits) -> Size, ) -> Node { let width = width.into(); let height = height.into(); let limits = limits.width(width).height(height); let intrinsic_size = f(&limits); Node::new(limits.resolve(width, height, intrinsic_size)) } /// Computes the resulting [`Node`] that fits the [`Limits`] given /// some width and height requirements and a closure that produces /// the content [`Node`] inside the given [`Limits`]. pub fn contained( limits: &Limits, width: impl Into<Length>, height: impl Into<Length>, f: impl FnOnce(&Limits) -> Node, ) -> Node { let width = width.into(); let height = height.into(); let limits = limits.width(width).height(height); let content = f(&limits); Node::with_children(limits.resolve(width, height, content.size()), vec![content]) } /// Computes the [`Node`] that fits the [`Limits`] given some width, height, and /// [`Padding`] requirements and a closure that produces the content [`Node`] /// inside the given [`Limits`]. pub fn padded( limits: &Limits, width: impl Into<Length>, height: impl Into<Length>, padding: impl Into<Padding>, layout: impl FnOnce(&Limits) -> Node, ) -> Node { positioned(limits, width, height, padding, layout, |content, _| content) } /// Computes a [`padded`] [`Node`] with a positioning step. pub fn positioned( limits: &Limits, width: impl Into<Length>, height: impl Into<Length>, padding: impl Into<Padding>, layout: impl FnOnce(&Limits) -> Node, position: impl FnOnce(Node, Size) -> Node, ) -> Node { let width = width.into(); let height = height.into(); let padding = padding.into(); let limits = limits.width(width).height(height); let content = layout(&limits.shrink(padding)); let padding = padding.fit(content.size(), limits.max()); let size = limits .shrink(padding) .resolve(width, height, content.size()); Node::with_children( size.expand(padding), vec![position(content.move_to((padding.left, padding.top)), size)], ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window.rs
core/src/window.rs
//! Build window-based GUI applications. pub mod icon; pub mod screenshot; pub mod settings; mod direction; mod event; mod id; mod level; mod mode; mod position; mod redraw_request; mod user_attention; pub use direction::Direction; pub use event::Event; pub use icon::Icon; pub use id::Id; pub use level::Level; pub use mode::Mode; pub use position::Position; pub use redraw_request::RedrawRequest; pub use screenshot::Screenshot; pub use settings::Settings; pub use user_attention::UserAttention;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/overlay.rs
core/src/overlay.rs
//! Display interactive elements on top of other widgets. mod element; mod group; mod nested; pub use element::Element; pub use group::Group; pub use nested::Nested; use crate::layout; use crate::mouse; use crate::renderer; use crate::widget; use crate::widget::Tree; use crate::{Clipboard, Event, Layout, Rectangle, Shell, Size, Vector}; /// An interactive component that can be displayed on top of other widgets. pub trait Overlay<Message, Theme, Renderer> where Renderer: crate::Renderer, { /// Returns the layout [`Node`] of the [`Overlay`]. /// /// This [`Node`] is used by the runtime to compute the [`Layout`] of the /// user interface. /// /// [`Node`]: layout::Node fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node; /// Draws the [`Overlay`] using the associated `Renderer`. fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ); /// Applies a [`widget::Operation`] to the [`Overlay`]. fn operate( &mut self, _layout: Layout<'_>, _renderer: &Renderer, _operation: &mut dyn widget::Operation, ) { } /// Processes a runtime [`Event`]. /// /// It receives: /// * an [`Event`] describing user interaction /// * the computed [`Layout`] of the [`Overlay`] /// * the current cursor position /// * a mutable `Message` list, allowing the [`Overlay`] to produce /// new messages based on user interaction. /// * the `Renderer` /// * a [`Clipboard`], if available /// /// By default, it does nothing. fn update( &mut self, _event: &Event, _layout: Layout<'_>, _cursor: mouse::Cursor, _renderer: &Renderer, _clipboard: &mut dyn Clipboard, _shell: &mut Shell<'_, Message>, ) { } /// Returns the current [`mouse::Interaction`] of the [`Overlay`]. /// /// By default, it returns [`mouse::Interaction::None`]. fn mouse_interaction( &self, _layout: Layout<'_>, _cursor: mouse::Cursor, _renderer: &Renderer, ) -> mouse::Interaction { mouse::Interaction::None } /// Returns the nested overlay of the [`Overlay`], if there is any. fn overlay<'a>( &'a mut self, _layout: Layout<'a>, _renderer: &Renderer, ) -> Option<Element<'a, Message, Theme, Renderer>> { None } /// The index of the overlay. /// /// Overlays with a higher index will be rendered on top of overlays with /// a lower index. /// /// By default, it returns `1.0`. fn index(&self) -> f32 { 1.0 } } /// Returns a [`Group`] of overlay [`Element`] children. /// /// This method will generally only be used by advanced users that are /// implementing the [`Widget`](crate::Widget) trait. pub fn from_children<'a, Message, Theme, Renderer>( children: &'a mut [crate::Element<'_, Message, Theme, Renderer>], tree: &'a mut Tree, layout: Layout<'a>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<Element<'a, Message, Theme, Renderer>> where Renderer: crate::Renderer, { let children = children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .filter_map(|((child, state), layout)| { child .as_widget_mut() .overlay(state, layout, renderer, viewport, translation) }) .collect::<Vec<_>>(); (!children.is_empty()).then(|| Group::with_children(children).overlay()) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/keyboard.rs
core/src/keyboard.rs
//! Listen to keyboard events. pub mod key; mod event; mod location; mod modifiers; pub use event::Event; pub use key::Key; pub use location::Location; pub use modifiers::Modifiers;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/length.rs
core/src/length.rs
use crate::Pixels; /// The strategy used to fill space in a specific dimension. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Length { /// Fill all the remaining space Fill, /// Fill a portion of the remaining space relative to other elements. /// /// Let's say we have two elements: one with `FillPortion(2)` and one with /// `FillPortion(3)`. The first will get 2 portions of the available space, /// while the second one would get 3. /// /// `Length::Fill` is equivalent to `Length::FillPortion(1)`. FillPortion(u16), /// Fill the least amount of space Shrink, /// Fill a fixed amount of space Fixed(f32), } impl Length { /// Returns the _fill factor_ of the [`Length`]. /// /// The _fill factor_ is a relative unit describing how much of the /// remaining space should be filled when compared to other elements. It /// is only meant to be used by layout engines. pub fn fill_factor(&self) -> u16 { match self { Length::Fill => 1, Length::FillPortion(factor) => *factor, Length::Shrink => 0, Length::Fixed(_) => 0, } } /// Returns `true` if the [`Length`] is either [`Length::Fill`] or /// [`Length::FillPortion`]. pub fn is_fill(&self) -> bool { self.fill_factor() != 0 } /// Returns the "fluid" variant of the [`Length`]. /// /// Specifically: /// - [`Length::Shrink`] if [`Length::Shrink`] or [`Length::Fixed`]. /// - [`Length::Fill`] otherwise. pub fn fluid(&self) -> Self { match self { Length::Fill | Length::FillPortion(_) => Length::Fill, Length::Shrink | Length::Fixed(_) => Length::Shrink, } } /// Adapts the [`Length`] so it can contain the other [`Length`] and /// match its fluidity. #[inline] pub fn enclose(self, other: Length) -> Self { match (self, other) { (Length::Shrink, Length::Fill | Length::FillPortion(_)) => other, _ => self, } } } impl From<Pixels> for Length { fn from(amount: Pixels) -> Self { Length::Fixed(f32::from(amount)) } } impl From<f32> for Length { fn from(amount: f32) -> Self { Length::Fixed(amount) } } impl From<u32> for Length { fn from(units: u32) -> Self { Length::Fixed(units as f32) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/border.rs
core/src/border.rs
//! Draw lines around containers. use crate::{Color, Pixels}; /// A border. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Border { /// The color of the border. pub color: Color, /// The width of the border. pub width: f32, /// The [`Radius`] of the border. pub radius: Radius, } /// Creates a new [`Border`] with the given [`Radius`]. /// /// ``` /// # use iced_core::border::{self, Border}; /// # /// assert_eq!(border::rounded(10), Border::default().rounded(10)); /// ``` pub fn rounded(radius: impl Into<Radius>) -> Border { Border::default().rounded(radius) } /// Creates a new [`Border`] with the given [`Color`]. /// /// ``` /// # use iced_core::border::{self, Border}; /// # use iced_core::Color; /// # /// assert_eq!(border::color(Color::BLACK), Border::default().color(Color::BLACK)); /// ``` pub fn color(color: impl Into<Color>) -> Border { Border::default().color(color) } /// Creates a new [`Border`] with the given `width`. /// /// ``` /// # use iced_core::border::{self, Border}; /// # use iced_core::Color; /// # /// assert_eq!(border::width(10), Border::default().width(10)); /// ``` pub fn width(width: impl Into<Pixels>) -> Border { Border::default().width(width) } impl Border { /// Sets the [`Color`] of the [`Border`]. pub fn color(self, color: impl Into<Color>) -> Self { Self { color: color.into(), ..self } } /// Sets the [`Radius`] of the [`Border`]. pub fn rounded(self, radius: impl Into<Radius>) -> Self { Self { radius: radius.into(), ..self } } /// Sets the width of the [`Border`]. pub fn width(self, width: impl Into<Pixels>) -> Self { Self { width: width.into().0, ..self } } } /// The border radii for the corners of a graphics primitive in the order: /// top-left, top-right, bottom-right, bottom-left. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Radius { /// Top left radius pub top_left: f32, /// Top right radius pub top_right: f32, /// Bottom right radius pub bottom_right: f32, /// Bottom left radius pub bottom_left: f32, } /// Creates a new [`Radius`] with the same value for each corner. pub fn radius(value: impl Into<Pixels>) -> Radius { Radius::new(value) } /// Creates a new [`Radius`] with the given top left value. pub fn top_left(value: impl Into<Pixels>) -> Radius { Radius::default().top_left(value) } /// Creates a new [`Radius`] with the given top right value. pub fn top_right(value: impl Into<Pixels>) -> Radius { Radius::default().top_right(value) } /// Creates a new [`Radius`] with the given bottom right value. pub fn bottom_right(value: impl Into<Pixels>) -> Radius { Radius::default().bottom_right(value) } /// Creates a new [`Radius`] with the given bottom left value. pub fn bottom_left(value: impl Into<Pixels>) -> Radius { Radius::default().bottom_left(value) } /// Creates a new [`Radius`] with the given value as top left and top right. pub fn top(value: impl Into<Pixels>) -> Radius { Radius::default().top(value) } /// Creates a new [`Radius`] with the given value as bottom left and bottom right. pub fn bottom(value: impl Into<Pixels>) -> Radius { Radius::default().bottom(value) } /// Creates a new [`Radius`] with the given value as top left and bottom left. pub fn left(value: impl Into<Pixels>) -> Radius { Radius::default().left(value) } /// Creates a new [`Radius`] with the given value as top right and bottom right. pub fn right(value: impl Into<Pixels>) -> Radius { Radius::default().right(value) } impl Radius { /// Creates a new [`Radius`] with the same value for each corner. pub fn new(value: impl Into<Pixels>) -> Self { let value = value.into().0; Self { top_left: value, top_right: value, bottom_right: value, bottom_left: value, } } /// Sets the top left value of the [`Radius`]. pub fn top_left(self, value: impl Into<Pixels>) -> Self { Self { top_left: value.into().0, ..self } } /// Sets the top right value of the [`Radius`]. pub fn top_right(self, value: impl Into<Pixels>) -> Self { Self { top_right: value.into().0, ..self } } /// Sets the bottom right value of the [`Radius`]. pub fn bottom_right(self, value: impl Into<Pixels>) -> Self { Self { bottom_right: value.into().0, ..self } } /// Sets the bottom left value of the [`Radius`]. pub fn bottom_left(self, value: impl Into<Pixels>) -> Self { Self { bottom_left: value.into().0, ..self } } /// Sets the top left and top right values of the [`Radius`]. pub fn top(self, value: impl Into<Pixels>) -> Self { let value = value.into().0; Self { top_left: value, top_right: value, ..self } } /// Sets the bottom left and bottom right values of the [`Radius`]. pub fn bottom(self, value: impl Into<Pixels>) -> Self { let value = value.into().0; Self { bottom_left: value, bottom_right: value, ..self } } /// Sets the top left and bottom left values of the [`Radius`]. pub fn left(self, value: impl Into<Pixels>) -> Self { let value = value.into().0; Self { top_left: value, bottom_left: value, ..self } } /// Sets the top right and bottom right values of the [`Radius`]. pub fn right(self, value: impl Into<Pixels>) -> Self { let value = value.into().0; Self { top_right: value, bottom_right: value, ..self } } } impl From<f32> for Radius { fn from(radius: f32) -> Self { Self { top_left: radius, top_right: radius, bottom_right: radius, bottom_left: radius, } } } impl From<u8> for Radius { fn from(w: u8) -> Self { Self::from(f32::from(w)) } } impl From<u32> for Radius { fn from(w: u32) -> Self { Self::from(w as f32) } } impl From<i32> for Radius { fn from(w: i32) -> Self { Self::from(w as f32) } } impl From<Radius> for [f32; 4] { fn from(radi: Radius) -> Self { [ radi.top_left, radi.top_right, radi.bottom_right, radi.bottom_left, ] } } impl std::ops::Mul<f32> for Radius { type Output = Self; fn mul(self, scale: f32) -> Self::Output { Self { top_left: self.top_left * scale, top_right: self.top_right * scale, bottom_right: self.bottom_right * scale, bottom_left: self.bottom_left * scale, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/color.rs
core/src/color.rs
/// A color in the `sRGB` color space. /// /// # String Representation /// /// A color can be represented in either of the following valid formats: `#rrggbb`, `#rrggbbaa`, `#rgb`, and `#rgba`. /// Where `rgba` represent hexadecimal digits. Both uppercase and lowercase letters are supported. /// /// If `a` (transparency) is not specified, `1.0` (completely opaque) would be used by default. /// /// If you have a static color string, using the [`color!`] macro should be preferred /// since it leverages hexadecimal literal notation and arithmetic directly. /// /// [`color!`]: crate::color! #[derive(Debug, Clone, Copy, PartialEq, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Color { /// Red component, 0.0 - 1.0 pub r: f32, /// Green component, 0.0 - 1.0 pub g: f32, /// Blue component, 0.0 - 1.0 pub b: f32, /// Transparency, 0.0 - 1.0 pub a: f32, } impl Color { /// The black color. pub const BLACK: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }; /// The white color. pub const WHITE: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0, }; /// A color with no opacity. pub const TRANSPARENT: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0, }; /// Creates a new [`Color`]. /// /// In debug mode, it will panic if the values are not in the correct /// range: 0.0 - 1.0 const fn new(r: f32, g: f32, b: f32, a: f32) -> Color { debug_assert!( r >= 0.0 && r <= 1.0, "Red component must be in [0, 1] range." ); debug_assert!( g >= 0.0 && g <= 1.0, "Green component must be in [0, 1] range." ); debug_assert!( b >= 0.0 && b <= 1.0, "Blue component must be in [0, 1] range." ); Color { r, g, b, a } } /// Creates a [`Color`] from its RGB components. pub const fn from_rgb(r: f32, g: f32, b: f32) -> Color { Color::from_rgba(r, g, b, 1.0f32) } /// Creates a [`Color`] from its RGBA components. pub const fn from_rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color::new(r, g, b, a) } /// Creates a [`Color`] from its RGB8 components. pub const fn from_rgb8(r: u8, g: u8, b: u8) -> Color { Color::from_rgba8(r, g, b, 1.0) } /// Creates a [`Color`] from its RGB8 components and an alpha value. pub const fn from_rgba8(r: u8, g: u8, b: u8, a: f32) -> Color { Color::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a) } /// Creates a [`Color`] from its linear RGBA components. pub fn from_linear_rgba(r: f32, g: f32, b: f32, a: f32) -> Self { // As described in: // https://en.wikipedia.org/wiki/SRGB fn gamma_component(u: f32) -> f32 { if u < 0.0031308 { 12.92 * u } else { 1.055 * u.powf(1.0 / 2.4) - 0.055 } } Self::new( gamma_component(r), gamma_component(g), gamma_component(b), a, ) } /// Converts the [`Color`] into its RGBA8 equivalent. #[must_use] pub fn into_rgba8(self) -> [u8; 4] { [ (self.r * 255.0).round() as u8, (self.g * 255.0).round() as u8, (self.b * 255.0).round() as u8, (self.a * 255.0).round() as u8, ] } /// Converts the [`Color`] into its linear values. pub fn into_linear(self) -> [f32; 4] { // As described in: // https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation fn linear_component(u: f32) -> f32 { if u < 0.04045 { u / 12.92 } else { ((u + 0.055) / 1.055).powf(2.4) } } [ linear_component(self.r), linear_component(self.g), linear_component(self.b), self.a, ] } /// Inverts the [`Color`] in-place. pub fn invert(&mut self) { self.r = 1.0f32 - self.r; self.b = 1.0f32 - self.g; self.g = 1.0f32 - self.b; } /// Returns the inverted [`Color`]. pub fn inverse(self) -> Color { Color::new(1.0f32 - self.r, 1.0f32 - self.g, 1.0f32 - self.b, self.a) } /// Scales the alpha channel of the [`Color`] by the given factor. pub fn scale_alpha(self, factor: f32) -> Color { Self { a: self.a * factor, ..self } } /// Returns the relative luminance of the [`Color`]. /// <https://www.w3.org/TR/WCAG21/#dfn-relative-luminance> pub fn relative_luminance(self) -> f32 { let linear = self.into_linear(); 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2] } /// Returns the [relative contrast ratio] of the [`Color`] against another one. /// /// [relative contrast ratio]: https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio pub fn relative_contrast(self, b: Color) -> f32 { let lum_a = self.relative_luminance(); let lum_b = b.relative_luminance(); (lum_a.max(lum_b) + 0.05) / (lum_a.min(lum_b) + 0.05) } /// Returns true if the current [`Color`] is readable on top /// of the given background [`Color`]. pub fn is_readable_on(self, background: Color) -> bool { background.relative_contrast(self) >= 6.0 } } impl From<[f32; 3]> for Color { fn from([r, g, b]: [f32; 3]) -> Self { Color::new(r, g, b, 1.0) } } impl From<[f32; 4]> for Color { fn from([r, g, b, a]: [f32; 4]) -> Self { Color::new(r, g, b, a) } } /// An error which can be returned when parsing color from an RGB hexadecimal string. /// /// See [`Color`] for specifications for the string. #[derive(Debug, thiserror::Error)] pub enum ParseError { /// The string could not be parsed to valid integers. #[error(transparent)] ParseIntError(#[from] std::num::ParseIntError), /// The string is of invalid length. #[error("expected hex string of length 3, 4, 6 or 8 excluding optional prefix '#', found {0}")] InvalidLength(usize), } impl std::str::FromStr for Color { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let hex = s.strip_prefix('#').unwrap_or(s); let parse_channel = |from: usize, to: usize| -> Result<f32, std::num::ParseIntError> { let num = usize::from_str_radix(&hex[from..=to], 16)? as f32 / 255.0; // If we only got half a byte (one letter), expand it into a full byte (two letters) Ok(if from == to { num + num * 16.0 } else { num }) }; let val = match hex.len() { 3 => Color::from_rgb( parse_channel(0, 0)?, parse_channel(1, 1)?, parse_channel(2, 2)?, ), 4 => Color::from_rgba( parse_channel(0, 0)?, parse_channel(1, 1)?, parse_channel(2, 2)?, parse_channel(3, 3)?, ), 6 => Color::from_rgb( parse_channel(0, 1)?, parse_channel(2, 3)?, parse_channel(4, 5)?, ), 8 => Color::from_rgba( parse_channel(0, 1)?, parse_channel(2, 3)?, parse_channel(4, 5)?, parse_channel(6, 7)?, ), _ => return Err(ParseError::InvalidLength(hex.len())), }; Ok(val) } } impl std::fmt::Display for Color { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let [r, g, b, a] = self.into_rgba8(); if self.a == 1.0 { return write!(f, "#{r:02x}{g:02x}{b:02x}"); } write!(f, "#{r:02x}{g:02x}{b:02x}{a:02x}") } } /// Creates a [`Color`] with shorter and cleaner syntax. /// /// # Examples /// /// ``` /// # use iced_core::{Color, color}; /// assert_eq!(color!(0, 0, 0), Color::BLACK); /// assert_eq!(color!(0, 0, 0, 0.0), Color::TRANSPARENT); /// assert_eq!(color!(0xffffff), Color::from_rgb(1.0, 1.0, 1.0)); /// assert_eq!(color!(0xffffff, 0.), Color::from_rgba(1.0, 1.0, 1.0, 0.0)); /// assert_eq!(color!(0x0000ff), Color::from_rgba(0.0, 0.0, 1.0, 1.0)); /// ``` #[macro_export] macro_rules! color { ($r:expr, $g:expr, $b:expr) => { $crate::Color::from_rgb8($r, $g, $b) }; ($r:expr, $g:expr, $b:expr, $a:expr) => {{ $crate::Color::from_rgba8($r, $g, $b, $a) }}; ($hex:literal) => {{ $crate::color!($hex, 1.0) }}; ($hex:literal, $a:expr) => {{ let mut hex = $hex as u32; // Shorthand notation: 0x123 if stringify!($hex).len() == 5 { let r = hex & 0xF00; let g = hex & 0xF0; let b = hex & 0xF; hex = (r << 12) | (r << 8) | (g << 8) | (g << 4) | (b << 4) | b; } debug_assert!(hex <= 0xffffff, "color! value must not exceed 0xffffff"); let r = (hex & 0xff0000) >> 16; let g = (hex & 0xff00) >> 8; let b = (hex & 0xff); $crate::color!(r as u8, g as u8, b as u8, $a) }}; } #[cfg(test)] mod tests { use super::*; #[test] fn parse() { let tests = [ ("#ff0000", [255, 0, 0, 255], "#ff0000"), ("00ff0080", [0, 255, 0, 128], "#00ff0080"), ("#F80", [255, 136, 0, 255], "#ff8800"), ("#00f1", [0, 0, 255, 17], "#0000ff11"), ("#00ff", [0, 0, 255, 255], "#0000ff"), ]; for (arg, expected_rgba8, expected_str) in tests { let color = arg.parse::<Color>().expect("color must parse"); assert_eq!(color.into_rgba8(), expected_rgba8); assert_eq!(color.to_string(), expected_str); } assert!("invalid".parse::<Color>().is_err()); } const SHORTHAND: Color = color!(0x123); #[test] fn shorthand_notation() { assert_eq!(SHORTHAND, Color::from_rgb8(0x11, 0x22, 0x33)); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/background.rs
core/src/background.rs
use crate::Color; use crate::gradient::{self, Gradient}; /// The background of some element. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Background { /// A solid color. Color(Color), /// Linearly interpolate between several colors. Gradient(Gradient), // TODO: Add image variant } impl Background { /// Scales the alpha channel of the [`Background`] by the given /// factor. pub fn scale_alpha(self, factor: f32) -> Self { match self { Self::Color(color) => Self::Color(color.scale_alpha(factor)), Self::Gradient(gradient) => Self::Gradient(gradient.scale_alpha(factor)), } } } impl From<Color> for Background { fn from(color: Color) -> Self { Background::Color(color) } } impl From<Gradient> for Background { fn from(gradient: Gradient) -> Self { Background::Gradient(gradient) } } impl From<gradient::Linear> for Background { fn from(gradient: gradient::Linear) -> Self { Background::Gradient(Gradient::Linear(gradient)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/point.rs
core/src/point.rs
use crate::Vector; use num_traits::{Float, Num}; use std::fmt; /// A 2D point. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Point<T = f32> { /// The X coordinate. pub x: T, /// The Y coordinate. pub y: T, } impl Point { /// The origin (i.e. a [`Point`] at (0, 0)). pub const ORIGIN: Self = Self::new(0.0, 0.0); } impl<T: Num> Point<T> { /// Creates a new [`Point`] with the given coordinates. pub const fn new(x: T, y: T) -> Self { Self { x, y } } /// Computes the distance to another [`Point`]. pub fn distance(&self, to: Self) -> T where T: Float, { let a = self.x - to.x; let b = self.y - to.y; a.hypot(b) } } impl<T> From<[T; 2]> for Point<T> where T: Num, { fn from([x, y]: [T; 2]) -> Self { Point { x, y } } } impl<T> From<(T, T)> for Point<T> where T: Num, { fn from((x, y): (T, T)) -> Self { Self { x, y } } } impl<T> From<Point<T>> for [T; 2] { fn from(point: Point<T>) -> [T; 2] { [point.x, point.y] } } impl<T> std::ops::Add<Vector<T>> for Point<T> where T: std::ops::Add<Output = T>, { type Output = Self; fn add(self, vector: Vector<T>) -> Self { Self { x: self.x + vector.x, y: self.y + vector.y, } } } impl<T> std::ops::AddAssign<Vector<T>> for Point<T> where T: std::ops::AddAssign, { fn add_assign(&mut self, vector: Vector<T>) { self.x += vector.x; self.y += vector.y; } } impl<T> std::ops::Sub<Vector<T>> for Point<T> where T: std::ops::Sub<Output = T>, { type Output = Self; fn sub(self, vector: Vector<T>) -> Self { Self { x: self.x - vector.x, y: self.y - vector.y, } } } impl<T> std::ops::SubAssign<Vector<T>> for Point<T> where T: std::ops::SubAssign, { fn sub_assign(&mut self, vector: Vector<T>) { self.x -= vector.x; self.y -= vector.y; } } impl<T> std::ops::Sub<Point<T>> for Point<T> where T: std::ops::Sub<Output = T>, { type Output = Vector<T>; fn sub(self, point: Self) -> Vector<T> { Vector::new(self.x - point.x, self.y - point.y) } } impl<T> fmt::Display for Point<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y) } } impl Point<f32> { /// Rounds the [`Point`] coordinates. pub fn round(self) -> Self { Point { x: self.x.round(), y: self.y.round(), } } /// Snaps the [`Point`] to __unsigned__ integer coordinates. pub fn snap(self) -> Point<u32> { Point { x: self.x.round() as u32, y: self.y.round() as u32, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/padding.rs
core/src/padding.rs
//! Space stuff around the perimeter. use crate::{Pixels, Size}; /// An amount of space to pad for each side of a box /// /// You can leverage the `From` trait to build [`Padding`] conveniently: /// /// ``` /// # use iced_core::Padding; /// # /// let padding = Padding::from(20); // 20px on all sides /// let padding = Padding::from([10, 20]); // top/bottom, left/right /// ``` /// /// Normally, the `padding` method of a widget will ask for an `Into<Padding>`, /// so you can easily write: /// /// ``` /// # use iced_core::Padding; /// # /// # struct Widget; /// # /// impl Widget { /// # pub fn new() -> Self { Self } /// # /// pub fn padding(mut self, padding: impl Into<Padding>) -> Self { /// // ... /// self /// } /// } /// /// let widget = Widget::new().padding(20); // 20px on all sides /// let widget = Widget::new().padding([10, 20]); // top/bottom, left/right /// ``` #[derive(Debug, Copy, Clone, PartialEq, Default)] pub struct Padding { /// Top padding pub top: f32, /// Right padding pub right: f32, /// Bottom padding pub bottom: f32, /// Left padding pub left: f32, } /// Create a [`Padding`] that is equal on all sides. pub fn all(padding: impl Into<Pixels>) -> Padding { Padding::new(padding.into().0) } /// Create some top [`Padding`]. pub fn top(padding: impl Into<Pixels>) -> Padding { Padding::default().top(padding) } /// Create some bottom [`Padding`]. pub fn bottom(padding: impl Into<Pixels>) -> Padding { Padding::default().bottom(padding) } /// Create some left [`Padding`]. pub fn left(padding: impl Into<Pixels>) -> Padding { Padding::default().left(padding) } /// Create some right [`Padding`]. pub fn right(padding: impl Into<Pixels>) -> Padding { Padding::default().right(padding) } /// Create some [`Padding`] with equal left and right sides. pub fn horizontal(padding: impl Into<Pixels>) -> Padding { Padding::default().horizontal(padding) } /// Create some [`Padding`] with equal top and bottom sides. pub fn vertical(padding: impl Into<Pixels>) -> Padding { Padding::default().vertical(padding) } impl Padding { /// Padding of zero pub const ZERO: Padding = Padding { top: 0.0, right: 0.0, bottom: 0.0, left: 0.0, }; /// Create a [`Padding`] that is equal on all sides. pub const fn new(padding: f32) -> Padding { Padding { top: padding, right: padding, bottom: padding, left: padding, } } /// Sets the [`top`] of the [`Padding`]. /// /// [`top`]: Self::top pub fn top(self, top: impl Into<Pixels>) -> Self { Self { top: top.into().0, ..self } } /// Sets the [`bottom`] of the [`Padding`]. /// /// [`bottom`]: Self::bottom pub fn bottom(self, bottom: impl Into<Pixels>) -> Self { Self { bottom: bottom.into().0, ..self } } /// Sets the [`left`] of the [`Padding`]. /// /// [`left`]: Self::left pub fn left(self, left: impl Into<Pixels>) -> Self { Self { left: left.into().0, ..self } } /// Sets the [`right`] of the [`Padding`]. /// /// [`right`]: Self::right pub fn right(self, right: impl Into<Pixels>) -> Self { Self { right: right.into().0, ..self } } /// Sets the [`left`] and [`right`] of the [`Padding`]. /// /// [`left`]: Self::left /// [`right`]: Self::right pub fn horizontal(self, horizontal: impl Into<Pixels>) -> Self { let horizontal = horizontal.into(); Self { left: horizontal.0, right: horizontal.0, ..self } } /// Sets the [`top`] and [`bottom`] of the [`Padding`]. /// /// [`top`]: Self::top /// [`bottom`]: Self::bottom pub fn vertical(self, vertical: impl Into<Pixels>) -> Self { let vertical = vertical.into(); Self { top: vertical.0, bottom: vertical.0, ..self } } /// Returns the total amount of horizontal [`Padding`]. pub fn x(self) -> f32 { self.left + self.right } /// Returns the total amount of vertical [`Padding`]. pub fn y(self) -> f32 { self.top + self.bottom } /// Fits the [`Padding`] between the provided `inner` and `outer` [`Size`]. pub fn fit(self, inner: Size, outer: Size) -> Self { let available = (outer - inner).max(Size::ZERO); let new_top = self.top.min(available.height); let new_left = self.left.min(available.width); Padding { top: new_top, bottom: self.bottom.min(available.height - new_top), left: new_left, right: self.right.min(available.width - new_left), } } } impl From<u16> for Padding { fn from(p: u16) -> Self { Padding { top: f32::from(p), right: f32::from(p), bottom: f32::from(p), left: f32::from(p), } } } impl From<[u16; 2]> for Padding { fn from(p: [u16; 2]) -> Self { Padding { top: f32::from(p[0]), right: f32::from(p[1]), bottom: f32::from(p[0]), left: f32::from(p[1]), } } } impl From<f32> for Padding { fn from(p: f32) -> Self { Padding { top: p, right: p, bottom: p, left: p, } } } impl From<[f32; 2]> for Padding { fn from(p: [f32; 2]) -> Self { Padding { top: p[0], right: p[1], bottom: p[0], left: p[1], } } } impl From<Padding> for Size { fn from(padding: Padding) -> Self { Self::new(padding.x(), padding.y()) } } impl From<Pixels> for Padding { fn from(pixels: Pixels) -> Self { Self::from(pixels.0) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/touch.rs
core/src/touch.rs
//! Build touch events. use crate::Point; /// A touch interaction. #[derive(Debug, Clone, Copy, PartialEq)] #[allow(missing_docs)] pub enum Event { /// A touch interaction was started. FingerPressed { id: Finger, position: Point }, /// An on-going touch interaction was moved. FingerMoved { id: Finger, position: Point }, /// A touch interaction was ended. FingerLifted { id: Finger, position: Point }, /// A touch interaction was canceled. FingerLost { id: Finger, position: Point }, } /// A unique identifier representing a finger on a touch interaction. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Finger(pub u64);
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/size.rs
core/src/size.rs
use crate::{Length, Radians, Vector}; /// An amount of space in 2 dimensions. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct Size<T = f32> { /// The width. pub width: T, /// The height. pub height: T, } impl<T> Size<T> { /// Creates a new [`Size`] with the given width and height. pub const fn new(width: T, height: T) -> Self { Size { width, height } } } impl Size { /// A [`Size`] with zero width and height. pub const ZERO: Size = Size::new(0., 0.); /// A [`Size`] with a width and height of 1 unit. pub const UNIT: Size = Size::new(1., 1.); /// A [`Size`] with infinite width and height. pub const INFINITE: Size = Size::new(f32::INFINITY, f32::INFINITY); /// Returns the minimum of each component of this size and another. pub fn min(self, other: Self) -> Self { Size { width: self.width.min(other.width), height: self.height.min(other.height), } } /// Returns the maximum of each component of this size and another. pub fn max(self, other: Self) -> Self { Size { width: self.width.max(other.width), height: self.height.max(other.height), } } /// Expands this [`Size`] by the given amount. pub fn expand(self, other: impl Into<Size>) -> Self { let other = other.into(); Size { width: self.width + other.width, height: self.height + other.height, } } /// Rotates this [`Size`] and returns the minimum [`Size`] /// containing it. pub fn rotate(self, rotation: Radians) -> Size { let radians = f32::from(rotation); Size { width: (self.width * radians.cos()).abs() + (self.height * radians.sin()).abs(), height: (self.width * radians.sin()).abs() + (self.height * radians.cos()).abs(), } } /// Applies an aspect ratio to this [`Size`] without /// exceeding its bounds. pub const fn ratio(self, aspect_ratio: f32) -> Size { Size { width: (self.height * aspect_ratio).min(self.width), height: (self.width / aspect_ratio).min(self.height), } } } impl Size<Length> { /// Returns true if either `width` or `height` are 0-sized. #[inline] pub fn is_void(&self) -> bool { matches!(self.width, Length::Fixed(0.0)) || matches!(self.height, Length::Fixed(0.0)) } } impl<T> From<[T; 2]> for Size<T> { fn from([width, height]: [T; 2]) -> Self { Size { width, height } } } impl<T> From<(T, T)> for Size<T> { fn from((width, height): (T, T)) -> Self { Self { width, height } } } impl From<(u32, u32)> for Size { fn from((width, height): (u32, u32)) -> Self { Size::new(width as f32, height as f32) } } impl<T> From<Vector<T>> for Size<T> { fn from(vector: Vector<T>) -> Self { Size { width: vector.x, height: vector.y, } } } impl<T> From<Size<T>> for [T; 2] { fn from(size: Size<T>) -> Self { [size.width, size.height] } } impl<T> From<Size<T>> for Vector<T> { fn from(size: Size<T>) -> Self { Vector::new(size.width, size.height) } } impl<T> std::ops::Add for Size<T> where T: std::ops::Add<Output = T>, { type Output = Size<T>; fn add(self, rhs: Self) -> Self::Output { Size { width: self.width + rhs.width, height: self.height + rhs.height, } } } impl<T> std::ops::Sub for Size<T> where T: std::ops::Sub<Output = T>, { type Output = Size<T>; fn sub(self, rhs: Self) -> Self::Output { Size { width: self.width - rhs.width, height: self.height - rhs.height, } } } impl<T> std::ops::Mul<T> for Size<T> where T: std::ops::Mul<Output = T> + Copy, { type Output = Size<T>; fn mul(self, rhs: T) -> Self::Output { Size { width: self.width * rhs, height: self.height * rhs, } } } impl<T> std::ops::Div<T> for Size<T> where T: std::ops::Div<Output = T> + Copy, { type Output = Size<T>; fn div(self, rhs: T) -> Self::Output { Size { width: self.width / rhs, height: self.height / rhs, } } } impl<T> std::ops::Mul<Vector<T>> for Size<T> where T: std::ops::Mul<Output = T> + Copy, { type Output = Size<T>; fn mul(self, scale: Vector<T>) -> Self::Output { Size { width: self.width * scale.x, height: self.height * scale.y, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/gradient.rs
core/src/gradient.rs
//! Colors that transition progressively. use crate::{Color, Radians}; use std::cmp::Ordering; #[derive(Debug, Clone, Copy, PartialEq)] /// A fill which transitions colors progressively along a direction, either linearly, radially (TBD), /// or conically (TBD). pub enum Gradient { /// A linear gradient interpolates colors along a direction at a specific angle. Linear(Linear), } impl Gradient { /// Scales the alpha channel of the [`Gradient`] by the given factor. pub fn scale_alpha(self, factor: f32) -> Self { match self { Gradient::Linear(linear) => Gradient::Linear(linear.scale_alpha(factor)), } } } impl From<Linear> for Gradient { fn from(gradient: Linear) -> Self { Self::Linear(gradient) } } #[derive(Debug, Default, Clone, Copy, PartialEq)] /// A point along the gradient vector where the specified [`color`] is unmixed. /// /// [`color`]: Self::color pub struct ColorStop { /// Offset along the gradient vector. pub offset: f32, /// The color of the gradient at the specified [`offset`]. /// /// [`offset`]: Self::offset pub color: Color, } /// A linear gradient. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Linear { /// How the [`Gradient`] is angled within its bounds. pub angle: Radians, /// [`ColorStop`]s along the linear gradient path. pub stops: [Option<ColorStop>; 8], } impl Linear { /// Creates a new [`Linear`] gradient with the given angle in [`Radians`]. pub fn new(angle: impl Into<Radians>) -> Self { Self { angle: angle.into(), stops: [None; 8], } } /// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient. /// /// Any `offset` that is not within `0.0..=1.0` will be silently ignored. /// /// Any stop added after the 8th will be silently ignored. pub fn add_stop(mut self, offset: f32, color: Color) -> Self { if offset.is_finite() && (0.0..=1.0).contains(&offset) { let (Ok(index) | Err(index)) = self.stops.binary_search_by(|stop| match stop { None => Ordering::Greater, Some(stop) => stop.offset.partial_cmp(&offset).unwrap(), }); if index < 8 { self.stops[index] = Some(ColorStop { offset, color }); } } else { log::warn!("Gradient color stop must be within 0.0..=1.0 range."); }; self } /// Adds multiple [`ColorStop`]s to the gradient. /// /// Any stop added after the 8th will be silently ignored. pub fn add_stops(mut self, stops: impl IntoIterator<Item = ColorStop>) -> Self { for stop in stops { self = self.add_stop(stop.offset, stop.color); } self } /// Scales the alpha channel of the [`Linear`] gradient by the given /// factor. pub fn scale_alpha(mut self, factor: f32) -> Self { for stop in self.stops.iter_mut().flatten() { stop.color.a *= factor; } self } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/renderer/null.rs
core/src/renderer/null.rs
use crate::alignment; use crate::image::{self, Image}; use crate::renderer::{self, Renderer}; use crate::svg; use crate::text::{self, Text}; use crate::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation}; impl Renderer for () { fn start_layer(&mut self, _bounds: Rectangle) {} fn end_layer(&mut self) {} fn start_transformation(&mut self, _transformation: Transformation) {} fn end_transformation(&mut self) {} fn fill_quad(&mut self, _quad: renderer::Quad, _background: impl Into<Background>) {} fn allocate_image( &mut self, handle: &image::Handle, callback: impl FnOnce(Result<image::Allocation, image::Error>) + Send + 'static, ) { #[allow(unsafe_code)] callback(Ok(unsafe { image::allocate(handle, Size::new(100, 100)) })); } fn hint(&mut self, _scale_factor: f32) {} fn scale_factor(&self) -> Option<f32> { None } fn reset(&mut self, _new_bounds: Rectangle) {} } impl text::Renderer for () { type Font = Font; type Paragraph = (); type Editor = (); const ICON_FONT: Font = Font::DEFAULT; const CHECKMARK_ICON: char = '0'; const ARROW_DOWN_ICON: char = '0'; const SCROLL_UP_ICON: char = '0'; const SCROLL_DOWN_ICON: char = '0'; const SCROLL_LEFT_ICON: char = '0'; const SCROLL_RIGHT_ICON: char = '0'; const ICED_LOGO: char = '0'; fn default_font(&self) -> Self::Font { Font::default() } fn default_size(&self) -> Pixels { Pixels(16.0) } fn fill_paragraph( &mut self, _paragraph: &Self::Paragraph, _position: Point, _color: Color, _clip_bounds: Rectangle, ) { } fn fill_editor( &mut self, _editor: &Self::Editor, _position: Point, _color: Color, _clip_bounds: Rectangle, ) { } fn fill_text( &mut self, _paragraph: Text, _position: Point, _color: Color, _clip_bounds: Rectangle, ) { } } impl text::Paragraph for () { type Font = Font; fn with_text(_text: Text<&str>) -> Self {} fn with_spans<Link>(_text: Text<&[text::Span<'_, Link, Self::Font>], Self::Font>) -> Self {} fn resize(&mut self, _new_bounds: Size) {} fn compare(&self, _text: Text<()>) -> text::Difference { text::Difference::None } fn hint_factor(&self) -> Option<f32> { None } fn size(&self) -> Pixels { Pixels(16.0) } fn font(&self) -> Font { Font::DEFAULT } fn line_height(&self) -> text::LineHeight { text::LineHeight::default() } fn align_x(&self) -> text::Alignment { text::Alignment::Default } fn align_y(&self) -> alignment::Vertical { alignment::Vertical::Top } fn wrapping(&self) -> text::Wrapping { text::Wrapping::default() } fn shaping(&self) -> text::Shaping { text::Shaping::default() } fn grapheme_position(&self, _line: usize, _index: usize) -> Option<Point> { None } fn bounds(&self) -> Size { Size::ZERO } fn min_bounds(&self) -> Size { Size::ZERO } fn hit_test(&self, _point: Point) -> Option<text::Hit> { None } fn hit_span(&self, _point: Point) -> Option<usize> { None } fn span_bounds(&self, _index: usize) -> Vec<Rectangle> { vec![] } } impl text::Editor for () { type Font = Font; fn with_text(_text: &str) -> Self {} fn is_empty(&self) -> bool { true } fn cursor(&self) -> text::editor::Cursor { text::editor::Cursor { position: text::editor::Position { line: 0, column: 0 }, selection: None, } } fn selection(&self) -> text::editor::Selection { text::editor::Selection::Caret(Point::ORIGIN) } fn copy(&self) -> Option<String> { None } fn line(&self, _index: usize) -> Option<text::editor::Line<'_>> { None } fn line_count(&self) -> usize { 0 } fn perform(&mut self, _action: text::editor::Action) {} fn move_to(&mut self, _cursor: text::editor::Cursor) {} fn bounds(&self) -> Size { Size::ZERO } fn hint_factor(&self) -> Option<f32> { None } fn min_bounds(&self) -> Size { Size::ZERO } fn update( &mut self, _new_bounds: Size, _new_font: Self::Font, _new_size: Pixels, _new_line_height: text::LineHeight, _new_wrapping: text::Wrapping, _new_hint_factor: Option<f32>, _new_highlighter: &mut impl text::Highlighter, ) { } fn highlight<H: text::Highlighter>( &mut self, _font: Self::Font, _highlighter: &mut H, _format_highlight: impl Fn(&H::Highlight) -> text::highlighter::Format<Self::Font>, ) { } } impl image::Renderer for () { type Handle = image::Handle; fn load_image(&self, handle: &Self::Handle) -> Result<image::Allocation, image::Error> { #[allow(unsafe_code)] Ok(unsafe { image::allocate(handle, Size::new(100, 100)) }) } fn measure_image(&self, _handle: &Self::Handle) -> Option<Size<u32>> { Some(Size::new(100, 100)) } fn draw_image(&mut self, _image: Image, _bounds: Rectangle, _clip_bounds: Rectangle) {} } impl svg::Renderer for () { fn measure_svg(&self, _handle: &svg::Handle) -> Size<u32> { Size::default() } fn draw_svg(&mut self, _svg: svg::Svg, _bounds: Rectangle, _clip_bounds: Rectangle) {} } impl renderer::Headless for () { async fn new( _default_font: Font, _default_text_size: Pixels, _backend: Option<&str>, ) -> Option<Self> where Self: Sized, { Some(()) } fn name(&self) -> String { "null renderer".to_owned() } fn screenshot( &mut self, _size: Size<u32>, _scale_factor: f32, _background_color: Color, ) -> Vec<u8> { Vec::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/overlay/element.rs
core/src/overlay/element.rs
pub use crate::Overlay; use crate::layout; use crate::mouse; use crate::renderer; use crate::widget; use crate::{Clipboard, Event, Layout, Shell, Size}; /// A generic [`Overlay`]. pub struct Element<'a, Message, Theme, Renderer> { overlay: Box<dyn Overlay<Message, Theme, Renderer> + 'a>, } impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> where Renderer: crate::Renderer, { /// Creates a new [`Element`] containing the given [`Overlay`]. pub fn new(overlay: Box<dyn Overlay<Message, Theme, Renderer> + 'a>) -> Self { Self { overlay } } /// Returns a reference to the [`Overlay`] of the [`Element`], pub fn as_overlay(&self) -> &dyn Overlay<Message, Theme, Renderer> { self.overlay.as_ref() } /// Returns a mutable reference to the [`Overlay`] of the [`Element`], pub fn as_overlay_mut(&mut self) -> &mut dyn Overlay<Message, Theme, Renderer> { self.overlay.as_mut() } /// Applies a transformation to the produced message of the [`Element`]. pub fn map<B>(self, f: &'a dyn Fn(Message) -> B) -> Element<'a, B, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: 'a, B: 'a, { Element { overlay: Box::new(Map::new(self.overlay, f)), } } } struct Map<'a, A, B, Theme, Renderer> { content: Box<dyn Overlay<A, Theme, Renderer> + 'a>, mapper: &'a dyn Fn(A) -> B, } impl<'a, A, B, Theme, Renderer> Map<'a, A, B, Theme, Renderer> { pub fn new( content: Box<dyn Overlay<A, Theme, Renderer> + 'a>, mapper: &'a dyn Fn(A) -> B, ) -> Map<'a, A, B, Theme, Renderer> { Map { content, mapper } } } impl<A, B, Theme, Renderer> Overlay<B, Theme, Renderer> for Map<'_, A, B, Theme, Renderer> where Renderer: crate::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { self.content.layout(renderer, bounds) } fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content.operate(layout, renderer, operation); } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, B>, ) { let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); self.content .update(event, layout, cursor, renderer, clipboard, &mut local_shell); shell.merge(local_shell, self.mapper); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.content.mouse_interaction(layout, cursor, renderer) } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { self.content.draw(renderer, theme, style, layout, cursor); } fn overlay<'a>( &'a mut self, layout: Layout<'a>, renderer: &Renderer, ) -> Option<Element<'a, B, Theme, Renderer>> { self.content .overlay(layout, renderer) .map(|overlay| overlay.map(self.mapper)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/overlay/group.rs
core/src/overlay/group.rs
use crate::layout; use crate::mouse; use crate::overlay; use crate::renderer; use crate::widget; use crate::{Clipboard, Event, Layout, Overlay, Shell, Size}; /// An [`Overlay`] container that displays multiple overlay [`overlay::Element`] /// children. pub struct Group<'a, Message, Theme, Renderer> { children: Vec<overlay::Element<'a, Message, Theme, Renderer>>, } impl<'a, Message, Theme, Renderer> Group<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: 'a + crate::Renderer, { /// Creates an empty [`Group`]. pub fn new() -> Self { Self::default() } /// Creates a [`Group`] with the given elements. pub fn with_children( mut children: Vec<overlay::Element<'a, Message, Theme, Renderer>>, ) -> Self { use std::cmp; children.sort_unstable_by(|a, b| { a.as_overlay() .index() .partial_cmp(&b.as_overlay().index()) .unwrap_or(cmp::Ordering::Equal) }); Group { children } } /// Turns the [`Group`] into an overlay [`overlay::Element`]. pub fn overlay(self) -> overlay::Element<'a, Message, Theme, Renderer> { overlay::Element::new(Box::new(self)) } } impl<'a, Message, Theme, Renderer> Default for Group<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: 'a + crate::Renderer, { fn default() -> Self { Self::with_children(Vec::new()) } } impl<Message, Theme, Renderer> Overlay<Message, Theme, Renderer> for Group<'_, Message, Theme, Renderer> where Renderer: crate::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { layout::Node::with_children( bounds, self.children .iter_mut() .map(|child| child.as_overlay_mut().layout(renderer, bounds)) .collect(), ) } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { for (child, layout) in self.children.iter_mut().zip(layout.children()) { child .as_overlay_mut() .update(event, layout, cursor, renderer, clipboard, shell); } } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { for (child, layout) in self.children.iter().zip(layout.children()) { child .as_overlay() .draw(renderer, theme, style, layout, cursor); } } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .zip(layout.children()) .map(|(child, layout)| { child .as_overlay() .mouse_interaction(layout, cursor, renderer) }) .max() .unwrap_or_default() } fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { operation.traverse(&mut |operation| { self.children .iter_mut() .zip(layout.children()) .for_each(|(child, layout)| { child.as_overlay_mut().operate(layout, renderer, operation); }); }); } fn overlay<'a>( &'a mut self, layout: Layout<'a>, renderer: &Renderer, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { let children = self .children .iter_mut() .zip(layout.children()) .filter_map(|(child, layout)| child.as_overlay_mut().overlay(layout, renderer)) .collect::<Vec<_>>(); (!children.is_empty()).then(|| Group::with_children(children).overlay()) } fn index(&self) -> f32 { self.children .first() .map(|child| child.as_overlay().index()) .unwrap_or(1.0) } } impl<'a, Message, Theme, Renderer> From<Group<'a, Message, Theme, Renderer>> for overlay::Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: 'a + crate::Renderer, { fn from(group: Group<'a, Message, Theme, Renderer>) -> Self { group.overlay() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/overlay/nested.rs
core/src/overlay/nested.rs
use crate::event; use crate::layout; use crate::mouse; use crate::overlay; use crate::renderer; use crate::widget; use crate::{Clipboard, Event, Layout, Shell, Size}; /// An overlay container that displays nested overlays pub struct Nested<'a, Message, Theme, Renderer> { overlay: overlay::Element<'a, Message, Theme, Renderer>, } impl<'a, Message, Theme, Renderer> Nested<'a, Message, Theme, Renderer> where Renderer: renderer::Renderer, { /// Creates a nested overlay from the provided [`overlay::Element`] pub fn new(element: overlay::Element<'a, Message, Theme, Renderer>) -> Self { Self { overlay: element } } /// Returns the layout [`Node`] of the [`Nested`] overlay. /// /// [`Node`]: layout::Node pub fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { fn recurse<Message, Theme, Renderer>( element: &mut overlay::Element<'_, Message, Theme, Renderer>, renderer: &Renderer, bounds: Size, ) -> layout::Node where Renderer: renderer::Renderer, { let overlay = element.as_overlay_mut(); let node = overlay.layout(renderer, bounds); let nested_node = overlay .overlay(Layout::new(&node), renderer) .as_mut() .map(|nested| recurse(nested, renderer, bounds)); if let Some(nested_node) = nested_node { layout::Node::with_children(node.size(), vec![node, nested_node]) } else { layout::Node::with_children(node.size(), vec![node]) } } recurse(&mut self.overlay, renderer, bounds) } /// Draws the [`Nested`] overlay using the associated `Renderer`. pub fn draw( &mut self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { fn recurse<Message, Theme, Renderer>( element: &mut overlay::Element<'_, Message, Theme, Renderer>, layout: Layout<'_>, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, cursor: mouse::Cursor, ) where Renderer: renderer::Renderer, { let mut layouts = layout.children(); if let Some(layout) = layouts.next() { let nested_layout = layouts.next(); let overlay = element.as_overlay_mut(); let is_over = cursor .position() .zip(nested_layout) .and_then(|(cursor_position, nested_layout)| { overlay.overlay(layout, renderer).map(|nested| { nested.as_overlay().mouse_interaction( nested_layout.children().next().unwrap(), mouse::Cursor::Available(cursor_position), renderer, ) != mouse::Interaction::None }) }) .unwrap_or_default(); renderer.with_layer(layout.bounds(), |renderer| { overlay.draw( renderer, theme, style, layout, if is_over { mouse::Cursor::Unavailable } else { cursor }, ); }); if let Some((mut nested, nested_layout)) = overlay.overlay(layout, renderer).zip(nested_layout) { recurse(&mut nested, nested_layout, renderer, theme, style, cursor); } } } recurse(&mut self.overlay, layout, renderer, theme, style, cursor); } /// Applies a [`widget::Operation`] to the [`Nested`] overlay. pub fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { fn recurse<Message, Theme, Renderer>( element: &mut overlay::Element<'_, Message, Theme, Renderer>, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) where Renderer: renderer::Renderer, { let mut layouts = layout.children(); if let Some(layout) = layouts.next() { let overlay = element.as_overlay_mut(); overlay.operate(layout, renderer, operation); if let Some((mut nested, nested_layout)) = overlay.overlay(layout, renderer).zip(layouts.next()) { recurse(&mut nested, nested_layout, renderer, operation); } } } recurse(&mut self.overlay, layout, renderer, operation); } /// Processes a runtime [`Event`]. pub fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { fn recurse<Message, Theme, Renderer>( element: &mut overlay::Element<'_, Message, Theme, Renderer>, layout: Layout<'_>, event: &Event, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) -> bool where Renderer: renderer::Renderer, { let mut layouts = layout.children(); if let Some(layout) = layouts.next() { let overlay = element.as_overlay_mut(); let nested_is_over = if let Some((mut nested, nested_layout)) = overlay.overlay(layout, renderer).zip(layouts.next()) { recurse( &mut nested, nested_layout, event, cursor, renderer, clipboard, shell, ) } else { false }; if shell.event_status() == event::Status::Ignored { let is_over = nested_is_over || cursor .position() .map(|cursor_position| { overlay.mouse_interaction( layout, mouse::Cursor::Available(cursor_position), renderer, ) != mouse::Interaction::None }) .unwrap_or_default(); overlay.update( event, layout, if nested_is_over { mouse::Cursor::Unavailable } else { cursor }, renderer, clipboard, shell, ); is_over } else { nested_is_over } } else { false } } let _ = recurse( &mut self.overlay, layout, event, cursor, renderer, clipboard, shell, ); } /// Returns the current [`mouse::Interaction`] of the [`Nested`] overlay. pub fn mouse_interaction( &mut self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { fn recurse<Message, Theme, Renderer>( element: &mut overlay::Element<'_, Message, Theme, Renderer>, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> Option<mouse::Interaction> where Renderer: renderer::Renderer, { let mut layouts = layout.children(); let layout = layouts.next()?; let overlay = element.as_overlay_mut(); Some( overlay .overlay(layout, renderer) .zip(layouts.next()) .and_then(|(mut overlay, layout)| { recurse(&mut overlay, layout, cursor, renderer) }) .unwrap_or_else(|| overlay.mouse_interaction(layout, cursor, renderer)), ) } recurse(&mut self.overlay, layout, cursor, renderer).unwrap_or_default() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/icon.rs
core/src/window/icon.rs
//! Change the icon of a window. use crate::Size; use std::mem; /// Builds an [`Icon`] from its RGBA pixels in the `sRGB` color space. pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Icon, Error> { const PIXEL_SIZE: usize = mem::size_of::<u8>() * 4; if !rgba.len().is_multiple_of(PIXEL_SIZE) { return Err(Error::ByteCountNotDivisibleBy4 { byte_count: rgba.len(), }); } let pixel_count = rgba.len() / PIXEL_SIZE; if pixel_count != (width * height) as usize { return Err(Error::DimensionsVsPixelCount { width, height, width_x_height: (width * height) as usize, pixel_count, }); } Ok(Icon { rgba, size: Size::new(width, height), }) } /// An window icon normally used for the titlebar or taskbar. #[derive(Clone)] pub struct Icon { rgba: Vec<u8>, size: Size<u32>, } impl Icon { /// Returns the raw data of the [`Icon`]. pub fn into_raw(self) -> (Vec<u8>, Size<u32>) { (self.rgba, self.size) } } impl std::fmt::Debug for Icon { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Icon") .field("rgba", &format!("{} pixels", self.rgba.len() / 4)) .field("size", &self.size) .finish() } } #[derive(Debug, thiserror::Error)] /// An error produced when using [`from_rgba`] with invalid arguments. pub enum Error { /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be /// safely interpreted as 32bpp RGBA pixels. #[error( "The provided RGBA data (with length {byte_count}) isn't divisible \ by 4. Therefore, it cannot be safely interpreted as 32bpp RGBA pixels" )] ByteCountNotDivisibleBy4 { /// The length of the provided RGBA data. byte_count: usize, }, /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. /// At least one of your arguments is incorrect. #[error( "The number of RGBA pixels ({pixel_count}) does not match the \ provided dimensions ({width}x{height})." )] DimensionsVsPixelCount { /// The provided width. width: u32, /// The provided height. height: u32, /// The product of `width` and `height`. width_x_height: usize, /// The amount of pixels of the provided RGBA data. pixel_count: usize, }, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings.rs
core/src/window/settings.rs
//! Configure your windows. #[cfg(target_os = "windows")] #[path = "settings/windows.rs"] pub mod platform; #[cfg(target_os = "macos")] #[path = "settings/macos.rs"] mod platform; #[cfg(target_os = "linux")] #[path = "settings/linux.rs"] mod platform; #[cfg(target_arch = "wasm32")] #[path = "settings/wasm.rs"] mod platform; #[cfg(not(any( target_os = "windows", target_os = "macos", target_os = "linux", target_arch = "wasm32" )))] #[path = "settings/other.rs"] mod platform; use crate::Size; use crate::window::{Icon, Level, Position}; pub use platform::PlatformSpecific; /// The window settings of an application. #[derive(Debug, Clone)] pub struct Settings { /// The initial logical dimensions of the window. pub size: Size, /// Whether the window should start maximized. pub maximized: bool, /// Whether the window should start fullscreen. pub fullscreen: bool, /// The initial position of the window. pub position: Position, /// The minimum size of the window. pub min_size: Option<Size>, /// The maximum size of the window. pub max_size: Option<Size>, /// Whether the window should be visible or not. pub visible: bool, /// Whether the window should be resizable or not. pub resizable: bool, /// Whether the title bar has Close button or not pub closeable: bool, /// Whether the title bar has Minimize button or not pub minimizable: bool, /// Whether the window should have a border, a title bar, etc. or not. pub decorations: bool, /// Whether the window should be transparent. pub transparent: bool, /// Whether the window should have blurry background. /// /// Note that the blurry effect is applied to the transparent window. You need to enable /// [`Settings::transparent`] and set a proper opacity value to the background color with /// `Application::style`. /// /// This option is only supported on macOS and Linux. Please read the [winit document][winit] /// for more details. /// /// [winit]: https://docs.rs/winit/0.30/winit/window/struct.Window.html#method.set_blur pub blur: bool, /// The window [`Level`]. pub level: Level, /// The icon of the window. pub icon: Option<Icon>, /// Platform specific settings. pub platform_specific: PlatformSpecific, /// Whether the window will close when the user requests it, e.g. when a user presses the /// close button. /// /// This can be useful if you want to have some behavior that executes before the window is /// actually destroyed. If you disable this, you must manually close the window with the /// `window::close` command. /// /// By default this is enabled. pub exit_on_close_request: bool, } impl Default for Settings { fn default() -> Self { Self { size: Size::new(1024.0, 768.0), maximized: false, fullscreen: false, position: Position::default(), min_size: None, max_size: None, visible: true, resizable: true, minimizable: true, closeable: true, decorations: true, transparent: false, blur: false, level: Level::default(), icon: None, exit_on_close_request: true, platform_specific: PlatformSpecific::default(), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/event.rs
core/src/window/event.rs
use crate::time::Instant; use crate::{Point, Size}; use std::path::PathBuf; /// A window-related event. #[derive(PartialEq, Clone, Debug)] pub enum Event { /// A window was opened. Opened { /// The position of the opened window. This is relative to the top-left corner of the desktop /// the window is on, including virtual desktops. Refers to window's "outer" position, /// or the window area, in logical pixels. /// /// **Note**: Not available in Wayland. position: Option<Point>, /// The size of the created window. This is its "inner" size, or the size of the /// client area, in logical pixels. size: Size, }, /// A window was closed. Closed, /// A window was moved. Moved(Point), /// A window was resized. Resized(Size), /// A window changed its scale factor. Rescaled(f32), /// A window redraw was requested. /// /// The [`Instant`] contains the current time. RedrawRequested(Instant), /// The user has requested for the window to close. CloseRequested, /// A window was focused. Focused, /// A window was unfocused. Unfocused, /// A file is being hovered over the window. /// /// When the user hovers multiple files at once, this event will be emitted /// for each file separately. /// /// ## Platform-specific /// /// - **Wayland:** Not implemented. FileHovered(PathBuf), /// A file has been dropped into the window. /// /// When the user drops multiple files at once, this event will be emitted /// for each file separately. /// /// ## Platform-specific /// /// - **Wayland:** Not implemented. FileDropped(PathBuf), /// A file was hovered, but has exited the window. /// /// There will be a single `FilesHoveredLeft` event triggered even if /// multiple files were hovered. /// /// ## Platform-specific /// /// - **Wayland:** Not implemented. FilesHoveredLeft, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/id.rs
core/src/window/id.rs
use std::fmt; use std::hash::Hash; use std::sync::atomic::{self, AtomicU64}; /// The id of the window. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Id(u64); static COUNT: AtomicU64 = AtomicU64::new(1); impl Id { /// Creates a new unique window [`Id`]. pub fn unique() -> Id { Id(COUNT.fetch_add(1, atomic::Ordering::Relaxed)) } } impl fmt::Display for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/user_attention.rs
core/src/window/user_attention.rs
/// The type of user attention to request. /// /// ## Platform-specific /// /// - **X11:** Sets the WM's `XUrgencyHint`. No distinction between [`Critical`] and [`Informational`]. /// /// [`Critical`]: Self::Critical /// [`Informational`]: Self::Informational #[derive(Debug, Clone, Copy)] pub enum UserAttention { /// ## Platform-specific /// /// - **macOS:** Bounces the dock icon until the application is in focus. /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus. Critical, /// ## Platform-specific /// /// - **macOS:** Bounces the dock icon once. /// - **Windows:** Flashes the taskbar button until the application is in focus. Informational, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/redraw_request.rs
core/src/window/redraw_request.rs
use crate::time::Instant; /// A request to redraw a window. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum RedrawRequest { /// Redraw the next frame. NextFrame, /// Redraw at the given time. At(Instant), /// No redraw is needed. Wait, } impl From<Instant> for RedrawRequest { fn from(time: Instant) -> Self { Self::At(time) } } #[cfg(test)] mod tests { use super::*; use crate::time::Duration; #[test] fn ordering() { let now = Instant::now(); let later = now + Duration::from_millis(10); assert_eq!(RedrawRequest::NextFrame, RedrawRequest::NextFrame); assert_eq!(RedrawRequest::At(now), RedrawRequest::At(now)); assert!(RedrawRequest::NextFrame < RedrawRequest::At(now)); assert!(RedrawRequest::At(now) > RedrawRequest::NextFrame); assert!(RedrawRequest::At(now) < RedrawRequest::At(later)); assert!(RedrawRequest::At(later) > RedrawRequest::At(now)); assert!(RedrawRequest::NextFrame <= RedrawRequest::NextFrame); assert!(RedrawRequest::NextFrame <= RedrawRequest::At(now)); assert!(RedrawRequest::At(now) >= RedrawRequest::NextFrame); assert!(RedrawRequest::At(now) <= RedrawRequest::At(now)); assert!(RedrawRequest::At(now) <= RedrawRequest::At(later)); assert!(RedrawRequest::At(later) >= RedrawRequest::At(now)); assert!(RedrawRequest::Wait > RedrawRequest::NextFrame); assert!(RedrawRequest::Wait > RedrawRequest::At(later)); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/level.rs
core/src/window/level.rs
/// A window level groups windows with respect to their z-position. /// /// The relative ordering between windows in different window levels is fixed. /// The z-order of a window within the same window level may change dynamically /// on user interaction. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Level { /// The default behavior. #[default] Normal, /// The window will always be below normal windows. /// /// This is useful for a widget-based app. AlwaysOnBottom, /// The window will always be on top of normal windows. AlwaysOnTop, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/screenshot.rs
core/src/window/screenshot.rs
//! Take screenshots of a window. use crate::{Bytes, Rectangle, Size}; use std::fmt::{Debug, Formatter}; /// Data of a screenshot, captured with `window::screenshot()`. /// /// The `bytes` of this screenshot will always be ordered as `RGBA` in the `sRGB` color space. #[derive(Clone)] pub struct Screenshot { /// The RGBA bytes of the [`Screenshot`]. pub rgba: Bytes, /// The size of the [`Screenshot`] in physical pixels. pub size: Size<u32>, /// The scale factor of the [`Screenshot`]. This can be useful when converting between widget /// bounds (which are in logical pixels) to crop screenshots. pub scale_factor: f32, } impl Debug for Screenshot { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Screenshot: {{ \n bytes: {}\n scale: {}\n size: {:?} }}", self.rgba.len(), self.scale_factor, self.size ) } } impl Screenshot { /// Creates a new [`Screenshot`]. pub fn new(rgba: impl Into<Bytes>, size: Size<u32>, scale_factor: f32) -> Self { Self { rgba: rgba.into(), size, scale_factor, } } /// Crops a [`Screenshot`] to the provided `region`. This will always be relative to the /// top-left corner of the [`Screenshot`]. pub fn crop(&self, region: Rectangle<u32>) -> Result<Self, CropError> { if region.width == 0 || region.height == 0 { return Err(CropError::Zero); } if region.x + region.width > self.size.width || region.y + region.height > self.size.height { return Err(CropError::OutOfBounds); } // Image is always RGBA8 = 4 bytes per pixel const PIXEL_SIZE: usize = 4; let bytes_per_row = self.size.width as usize * PIXEL_SIZE; let row_range = region.y as usize..(region.y + region.height) as usize; let column_range = region.x as usize * PIXEL_SIZE..(region.x + region.width) as usize * PIXEL_SIZE; let chopped = self.rgba .chunks(bytes_per_row) .enumerate() .fold(vec![], |mut acc, (row, bytes)| { if row_range.contains(&row) { acc.extend(&bytes[column_range.clone()]); } acc }); Ok(Self { rgba: Bytes::from(chopped), size: Size::new(region.width, region.height), scale_factor: self.scale_factor, }) } } impl AsRef<[u8]> for Screenshot { fn as_ref(&self) -> &[u8] { &self.rgba } } impl From<Screenshot> for Bytes { fn from(screenshot: Screenshot) -> Self { screenshot.rgba } } #[derive(Debug, thiserror::Error)] /// Errors that can occur when cropping a [`Screenshot`]. pub enum CropError { #[error("The cropped region is out of bounds.")] /// The cropped region's size is out of bounds. OutOfBounds, #[error("The cropped region is not visible.")] /// The cropped region's size is zero. Zero, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/position.rs
core/src/window/position.rs
use crate::{Point, Size}; /// The position of a window in a given screen. #[derive(Debug, Clone, Copy, Default)] pub enum Position { /// The platform-specific default position for a new window. #[default] Default, /// The window is completely centered on the screen. Centered, /// The window is positioned with specific coordinates: `(X, Y)`. /// /// When the decorations of the window are enabled, Windows 10 will add some /// invisible padding to the window. This padding gets included in the /// position. So if you have decorations enabled and want the window to be /// at (0, 0) you would have to set the position to /// `(PADDING_X, PADDING_Y)`. Specific(Point), /// Like [`Specific`], but the window is positioned with the specific coordinates returned by the function. /// /// The function receives the window size and the monitor's resolution as input. /// /// [`Specific`]: Self::Specific SpecificWith(fn(Size, Size) -> Point), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/mode.rs
core/src/window/mode.rs
/// The mode of a window-based application. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { /// The application appears in its own window. Windowed, /// The application takes the whole screen of its current monitor. Fullscreen, /// The application is hidden Hidden, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/direction.rs
core/src/window/direction.rs
/// The cardinal directions relative to the center of a window. #[derive(Debug, Clone, Copy)] pub enum Direction { /// Points to the top edge of a window. North, /// Points to the bottom edge of a window. South, /// Points to the right edge of a window. East, /// Points to the left edge of a window. West, /// Points to the top-right corner of a window. NorthEast, /// Points to the top-left corner of a window. NorthWest, /// Points to the bottom-right corner of a window. SouthEast, /// Points to the bottom-left corner of a window. SouthWest, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings/macos.rs
core/src/window/settings/macos.rs
//! Platform specific settings for macOS. /// The platform specific window settings of an application. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct PlatformSpecific { /// Hides the window title. pub title_hidden: bool, /// Makes the titlebar transparent and allows the content to appear behind it. pub titlebar_transparent: bool, /// Makes the window content appear behind the titlebar. pub fullsize_content_view: bool, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings/linux.rs
core/src/window/settings/linux.rs
//! Platform specific settings for Linux. /// The platform specific window settings of an application. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct PlatformSpecific { /// Sets the application id of the window. /// /// As a best practice, it is suggested to select an application id that match /// the basename of the application’s .desktop file. pub application_id: String, /// Whether bypass the window manager mapping for x11 windows /// /// This flag is particularly useful for creating UI elements that need precise /// positioning and immediate display without window manager interference. pub override_redirect: bool, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings/windows.rs
core/src/window/settings/windows.rs
//! Platform specific settings for Windows. /// The platform specific window settings of an application. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PlatformSpecific { /// Drag and drop support pub drag_and_drop: bool, /// Whether show or hide the window icon in the taskbar. pub skip_taskbar: bool, /// Shows or hides the background drop shadow for undecorated windows. /// /// The shadow is hidden by default. /// Enabling the shadow causes a thin 1px line to appear on the top of the window. pub undecorated_shadow: bool, /// Sets the preferred style of the window corners. /// /// Supported starting with Windows 11 Build 22000. pub corner_preference: CornerPreference, } impl Default for PlatformSpecific { fn default() -> Self { Self { drag_and_drop: true, skip_taskbar: false, undecorated_shadow: false, corner_preference: Default::default(), } } } /// Describes how the corners of a window should look like. #[repr(i32)] #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub enum CornerPreference { /// Corresponds to `DWMWCP_DEFAULT`. /// /// Let the system decide when to round window corners. #[default] Default = 0, /// Corresponds to `DWMWCP_DONOTROUND`. /// /// Never round window corners. DoNotRound = 1, /// Corresponds to `DWMWCP_ROUND`. /// /// Round the corners, if appropriate. Round = 2, /// Corresponds to `DWMWCP_ROUNDSMALL`. /// /// Round the corners if appropriate, with a small radius. RoundSmall = 3, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings/other.rs
core/src/window/settings/other.rs
/// The platform specific window settings of an application. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct PlatformSpecific;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/window/settings/wasm.rs
core/src/window/settings/wasm.rs
//! Platform specific settings for WebAssembly. /// The platform specific window settings of an application. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PlatformSpecific { /// The identifier of a DOM element that will be replaced with the /// application. /// /// If set to `None`, the application will be appended to the HTML body. /// /// By default, it is set to `"iced"`. pub target: Option<String>, } impl Default for PlatformSpecific { fn default() -> Self { Self { target: Some(String::from("iced")), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/layout/node.rs
core/src/layout/node.rs
use crate::{Alignment, Padding, Point, Rectangle, Size, Vector}; /// The bounds of an element and its children. #[derive(Debug, Clone, Default)] pub struct Node { bounds: Rectangle, children: Vec<Node>, } impl Node { /// Creates a new [`Node`] with the given [`Size`]. pub const fn new(size: Size) -> Self { Self::with_children(size, Vec::new()) } /// Creates a new [`Node`] with the given [`Size`] and children. pub const fn with_children(size: Size, children: Vec<Node>) -> Self { Node { bounds: Rectangle { x: 0.0, y: 0.0, width: size.width, height: size.height, }, children, } } /// Creates a new [`Node`] that wraps a single child with some [`Padding`]. pub fn container(child: Self, padding: Padding) -> Self { Self::with_children( child.bounds.size().expand(padding), vec![child.move_to(Point::new(padding.left, padding.top))], ) } /// Returns the [`Size`] of the [`Node`]. pub fn size(&self) -> Size { Size::new(self.bounds.width, self.bounds.height) } /// Returns the bounds of the [`Node`]. pub fn bounds(&self) -> Rectangle { self.bounds } /// Returns the children of the [`Node`]. pub fn children(&self) -> &[Node] { &self.children } /// Aligns the [`Node`] in the given space. pub fn align(mut self, align_x: Alignment, align_y: Alignment, space: Size) -> Self { self.align_mut(align_x, align_y, space); self } /// Mutable reference version of [`Self::align`]. pub fn align_mut(&mut self, align_x: Alignment, align_y: Alignment, space: Size) { match align_x { Alignment::Start => {} Alignment::Center => { self.bounds.x += (space.width - self.bounds.width) / 2.0; } Alignment::End => { self.bounds.x += space.width - self.bounds.width; } } match align_y { Alignment::Start => {} Alignment::Center => { self.bounds.y += (space.height - self.bounds.height) / 2.0; } Alignment::End => { self.bounds.y += space.height - self.bounds.height; } } } /// Moves the [`Node`] to the given position. pub fn move_to(mut self, position: impl Into<Point>) -> Self { self.move_to_mut(position); self } /// Mutable reference version of [`Self::move_to`]. pub fn move_to_mut(&mut self, position: impl Into<Point>) { let position = position.into(); self.bounds.x = position.x; self.bounds.y = position.y; } /// Translates the [`Node`] by the given translation. pub fn translate(mut self, translation: impl Into<Vector>) -> Self { self.translate_mut(translation); self } /// Translates the [`Node`] by the given translation. pub fn translate_mut(&mut self, translation: impl Into<Vector>) { self.bounds = self.bounds + translation.into(); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/layout/flex.rs
core/src/layout/flex.rs
//! Distribute elements using a flex-based layout. // This code is heavily inspired by the [`druid`] codebase. // // [`druid`]: https://github.com/xi-editor/druid // // Copyright 2018 The xi-editor Authors, Héctor Ramón // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::Element; use crate::layout::{Limits, Node}; use crate::widget; use crate::{Alignment, Length, Padding, Point, Size}; /// The main axis of a flex layout. #[derive(Debug)] pub enum Axis { /// The horizontal axis Horizontal, /// The vertical axis Vertical, } impl Axis { fn main(&self, size: Size) -> f32 { match self { Axis::Horizontal => size.width, Axis::Vertical => size.height, } } fn cross(&self, size: Size) -> f32 { match self { Axis::Horizontal => size.height, Axis::Vertical => size.width, } } fn pack<T>(&self, main: T, cross: T) -> (T, T) { match self { Axis::Horizontal => (main, cross), Axis::Vertical => (cross, main), } } } /// Computes the flex layout with the given axis and limits, applying spacing, /// padding and alignment to the items as needed. /// /// It returns a new layout [`Node`]. pub fn resolve<Message, Theme, Renderer>( axis: Axis, renderer: &Renderer, limits: &Limits, width: Length, height: Length, padding: Padding, spacing: f32, align_items: Alignment, items: &mut [Element<'_, Message, Theme, Renderer>], trees: &mut [widget::Tree], ) -> Node where Renderer: crate::Renderer, { let limits = limits.width(width).height(height).shrink(padding); let total_spacing = spacing * items.len().saturating_sub(1) as f32; let max_cross = axis.cross(limits.max()); let (main_compress, cross_compress) = { let compression = limits.compression(); axis.pack(compression.width, compression.height) }; let compression = { let (compress_x, compress_y) = axis.pack(main_compress, false); Size::new(compress_x, compress_y) }; let mut fill_main_sum = 0; let mut some_fill_cross = false; let mut cross = if cross_compress { 0.0 } else { max_cross }; let mut available = axis.main(limits.max()) - total_spacing; let mut nodes: Vec<Node> = Vec::with_capacity(items.len()); nodes.resize(items.len(), Node::default()); // FIRST PASS // We lay out non-fluid elements in the main axis. // If we need to compress the cross axis, then we skip any of these elements // that are also fluid in the cross axis. for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (fill_main_factor, fill_cross_factor) = { let size = child.as_widget().size(); axis.pack(size.width.fill_factor(), size.height.fill_factor()) }; if (main_compress || fill_main_factor == 0) && (!cross_compress || fill_cross_factor == 0) { let (max_width, max_height) = axis.pack( available, if fill_cross_factor == 0 { max_cross } else { cross }, ); let child_limits = Limits::with_compression(Size::ZERO, Size::new(max_width, max_height), compression); let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); available -= axis.main(size); cross = cross.max(axis.cross(size)); nodes[i] = layout; } else { fill_main_sum += fill_main_factor; some_fill_cross = some_fill_cross || fill_cross_factor != 0; } } // SECOND PASS (conditional) // If we must compress the cross axis and there are fluid elements in the // cross axis, we lay out any of these elements that are also non-fluid in // the main axis (i.e. the ones we deliberately skipped in the first pass). // // We use the maximum cross length obtained in the first pass as the maximum // cross limit. // // We can defer the layout of any elements that have a fixed size in the main axis, // allowing them to use the cross calculations of the next pass. if cross_compress && some_fill_cross { for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (main_size, cross_size) = { let size = child.as_widget().size(); axis.pack(size.width, size.height) }; if (main_compress || main_size.fill_factor() == 0) && cross_size.fill_factor() != 0 { if let Length::Fixed(main) = main_size { available -= main; continue; } let (max_width, max_height) = axis.pack(available, cross); let child_limits = Limits::with_compression( Size::ZERO, Size::new(max_width, max_height), compression, ); let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); available -= axis.main(size); cross = cross.max(axis.cross(size)); nodes[i] = layout; } } } let remaining = available.max(0.0); // THIRD PASS (conditional) // We lay out the elements that are fluid in the main axis. // We use the remaining space to evenly allocate space based on fill factors. if !main_compress { for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (fill_main_factor, fill_cross_factor) = { let size = child.as_widget().size(); axis.pack(size.width.fill_factor(), size.height.fill_factor()) }; if fill_main_factor != 0 { let max_main = remaining * fill_main_factor as f32 / fill_main_sum as f32; let max_main = if max_main.is_nan() { f32::INFINITY } else { max_main }; let min_main = if max_main.is_infinite() { 0.0 } else { max_main }; let (min_width, min_height) = axis.pack(min_main, 0.0); let (max_width, max_height) = axis.pack( max_main, if fill_cross_factor == 0 { max_cross } else { cross }, ); let child_limits = Limits::with_compression( Size::new(min_width, min_height), Size::new(max_width, max_height), compression, ); let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); cross = cross.max(axis.cross(layout.size())); nodes[i] = layout; } } } // FOURTH PASS (conditional) // We lay out any elements that were deferred in the second pass. // These are elements that must be compressed in their cross axis and have // a fixed length in the main axis. if cross_compress && some_fill_cross { for (i, (child, tree)) in items.iter_mut().zip(trees).enumerate() { let (main_size, cross_size) = { let size = child.as_widget().size(); axis.pack(size.width, size.height) }; if cross_size.fill_factor() != 0 { let Length::Fixed(main) = main_size else { continue; }; let (max_width, max_height) = axis.pack(main, cross); let child_limits = Limits::new(Size::ZERO, Size::new(max_width, max_height)); let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); cross = cross.max(axis.cross(size)); nodes[i] = layout; } } } let pad = axis.pack(padding.left, padding.top); let mut main = pad.0; // FIFTH PASS // We align all the laid out nodes in the cross axis, if needed. for (i, node) in nodes.iter_mut().enumerate() { if i > 0 { main += spacing; } let (x, y) = axis.pack(main, pad.1); node.move_to_mut(Point::new(x, y)); match axis { Axis::Horizontal => { node.align_mut(Alignment::Start, align_items, Size::new(0.0, cross)); } Axis::Vertical => { node.align_mut(align_items, Alignment::Start, Size::new(cross, 0.0)); } } let size = node.size(); main += axis.main(size); } let (intrinsic_width, intrinsic_height) = axis.pack(main - pad.0, cross); let size = limits.resolve(width, height, Size::new(intrinsic_width, intrinsic_height)); Node::with_children(size.expand(padding), nodes) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/layout/limits.rs
core/src/layout/limits.rs
#![allow(clippy::manual_clamp)] use crate::{Length, Size}; /// A set of size constraints for layouting. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Limits { min: Size, max: Size, compression: Size<bool>, } impl Limits { /// No limits pub const NONE: Limits = Limits { min: Size::ZERO, max: Size::INFINITE, compression: Size::new(false, false), }; /// Creates new [`Limits`] with the given minimum and maximum [`Size`]. pub const fn new(min: Size, max: Size) -> Limits { Limits::with_compression(min, max, Size::new(false, false)) } /// Creates new [`Limits`] with the given minimun and maximum [`Size`], and /// whether fluid lengths should be compressed to intrinsic dimensions. pub const fn with_compression(min: Size, max: Size, compress: Size<bool>) -> Self { Limits { min, max, compression: compress, } } /// Returns the minimum [`Size`] of the [`Limits`]. pub fn min(&self) -> Size { self.min } /// Returns the maximum [`Size`] of the [`Limits`]. pub fn max(&self) -> Size { self.max } /// Returns the compression of the [`Limits`]. pub fn compression(&self) -> Size<bool> { self.compression } /// Applies a width constraint to the current [`Limits`]. pub fn width(mut self, width: impl Into<Length>) -> Limits { match width.into() { Length::Shrink => { self.compression.width = true; } Length::Fixed(amount) => { let new_width = amount.min(self.max.width).max(self.min.width); self.min.width = new_width; self.max.width = new_width; self.compression.width = false; } Length::Fill | Length::FillPortion(_) => {} } self } /// Applies a height constraint to the current [`Limits`]. pub fn height(mut self, height: impl Into<Length>) -> Limits { match height.into() { Length::Shrink => { self.compression.height = true; } Length::Fixed(amount) => { let new_height = amount.min(self.max.height).max(self.min.height); self.min.height = new_height; self.max.height = new_height; self.compression.height = false; } Length::Fill | Length::FillPortion(_) => {} } self } /// Applies a minimum width constraint to the current [`Limits`]. pub fn min_width(mut self, min_width: f32) -> Limits { self.min.width = self.min.width.max(min_width).min(self.max.width); self } /// Applies a maximum width constraint to the current [`Limits`]. pub fn max_width(mut self, max_width: f32) -> Limits { self.max.width = self.max.width.min(max_width).max(self.min.width); self } /// Applies a minimum height constraint to the current [`Limits`]. pub fn min_height(mut self, min_height: f32) -> Limits { self.min.height = self.min.height.max(min_height).min(self.max.height); self } /// Applies a maximum height constraint to the current [`Limits`]. pub fn max_height(mut self, max_height: f32) -> Limits { self.max.height = self.max.height.min(max_height).max(self.min.height); self } /// Shrinks the current [`Limits`] by the given [`Size`]. pub fn shrink(&self, size: impl Into<Size>) -> Limits { let size = size.into(); let min = Size::new( (self.min().width - size.width).max(0.0), (self.min().height - size.height).max(0.0), ); let max = Size::new( (self.max().width - size.width).max(0.0), (self.max().height - size.height).max(0.0), ); Limits { min, max, compression: self.compression, } } /// Removes the minimum [`Size`] constraint for the current [`Limits`]. pub fn loose(&self) -> Limits { Limits { min: Size::ZERO, max: self.max, compression: self.compression, } } /// Computes the resulting [`Size`] that fits the [`Limits`] given /// some width and height requirements and the intrinsic size of /// some content. pub fn resolve( &self, width: impl Into<Length>, height: impl Into<Length>, intrinsic_size: Size, ) -> Size { let width = match width.into() { Length::Fill | Length::FillPortion(_) if !self.compression.width => self.max.width, Length::Fixed(amount) => amount.min(self.max.width).max(self.min.width), _ => intrinsic_size.width.min(self.max.width).max(self.min.width), }; let height = match height.into() { Length::Fill | Length::FillPortion(_) if !self.compression.height => self.max.height, Length::Fixed(amount) => amount.min(self.max.height).max(self.min.height), _ => intrinsic_size .height .min(self.max.height) .max(self.min.height), }; Size::new(width, height) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/theme/palette.rs
core/src/theme/palette.rs
//! Define the colors of a theme. use crate::{Color, color}; use std::sync::LazyLock; /// A color palette. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Palette { /// The background [`Color`] of the [`Palette`]. pub background: Color, /// The text [`Color`] of the [`Palette`]. pub text: Color, /// The primary [`Color`] of the [`Palette`]. pub primary: Color, /// The success [`Color`] of the [`Palette`]. pub success: Color, /// The warning [`Color`] of the [`Palette`]. pub warning: Color, /// The danger [`Color`] of the [`Palette`]. pub danger: Color, } impl Palette { /// The built-in light variant of a [`Palette`]. pub const LIGHT: Self = Self { background: Color::WHITE, text: Color::BLACK, primary: color!(0x5865F2), success: color!(0x12664f), warning: color!(0xb77e33), danger: color!(0xc3423f), }; /// The built-in dark variant of a [`Palette`]. pub const DARK: Self = Self { background: color!(0x2B2D31), text: Color::from_rgb(0.90, 0.90, 0.90), primary: color!(0x5865F2), success: color!(0x12664f), warning: color!(0xffc14e), danger: color!(0xc3423f), }; /// The built-in [Dracula] variant of a [`Palette`]. /// /// [Dracula]: https://draculatheme.com pub const DRACULA: Self = Self { background: color!(0x282A36), // BACKGROUND text: color!(0xf8f8f2), // FOREGROUND primary: color!(0xbd93f9), // PURPLE success: color!(0x50fa7b), // GREEN warning: color!(0xf1fa8c), // YELLOW danger: color!(0xff5555), // RED }; /// The built-in [Nord] variant of a [`Palette`]. /// /// [Nord]: https://www.nordtheme.com/docs/colors-and-palettes pub const NORD: Self = Self { background: color!(0x2e3440), // nord0 text: color!(0xeceff4), // nord6 primary: color!(0x8fbcbb), // nord7 success: color!(0xa3be8c), // nord14 warning: color!(0xebcb8b), // nord13 danger: color!(0xbf616a), // nord11 }; /// The built-in [Solarized] Light variant of a [`Palette`]. /// /// [Solarized]: https://ethanschoonover.com/solarized pub const SOLARIZED_LIGHT: Self = Self { background: color!(0xfdf6e3), // base3 text: color!(0x657b83), // base00 primary: color!(0x2aa198), // cyan success: color!(0x859900), // green warning: color!(0xb58900), // yellow danger: color!(0xdc322f), // red }; /// The built-in [Solarized] Dark variant of a [`Palette`]. /// /// [Solarized]: https://ethanschoonover.com/solarized pub const SOLARIZED_DARK: Self = Self { background: color!(0x002b36), // base03 text: color!(0x839496), // base0 primary: color!(0x2aa198), // cyan success: color!(0x859900), // green warning: color!(0xb58900), // yellow danger: color!(0xdc322f), // red }; /// The built-in [Gruvbox] Light variant of a [`Palette`]. /// /// [Gruvbox]: https://github.com/morhetz/gruvbox pub const GRUVBOX_LIGHT: Self = Self { background: color!(0xfbf1c7), // light BG_0 text: color!(0x282828), // light FG0_29 primary: color!(0x458588), // light BLUE_4 success: color!(0x98971a), // light GREEN_2 warning: color!(0xd79921), // light YELLOW_3 danger: color!(0xcc241d), // light RED_1 }; /// The built-in [Gruvbox] Dark variant of a [`Palette`]. /// /// [Gruvbox]: https://github.com/morhetz/gruvbox pub const GRUVBOX_DARK: Self = Self { background: color!(0x282828), // dark BG_0 text: color!(0xfbf1c7), // dark FG0_29 primary: color!(0x458588), // dark BLUE_4 success: color!(0x98971a), // dark GREEN_2 warning: color!(0xd79921), // dark YELLOW_3 danger: color!(0xcc241d), // dark RED_1 }; /// The built-in [Catppuccin] Latte variant of a [`Palette`]. /// /// [Catppuccin]: https://github.com/catppuccin/catppuccin pub const CATPPUCCIN_LATTE: Self = Self { background: color!(0xeff1f5), // Base text: color!(0x4c4f69), // Text primary: color!(0x1e66f5), // Blue success: color!(0x40a02b), // Green warning: color!(0xdf8e1d), // Yellow danger: color!(0xd20f39), // Red }; /// The built-in [Catppuccin] Frappé variant of a [`Palette`]. /// /// [Catppuccin]: https://github.com/catppuccin/catppuccin pub const CATPPUCCIN_FRAPPE: Self = Self { background: color!(0x303446), // Base text: color!(0xc6d0f5), // Text primary: color!(0x8caaee), // Blue success: color!(0xa6d189), // Green warning: color!(0xe5c890), // Yellow danger: color!(0xe78284), // Red }; /// The built-in [Catppuccin] Macchiato variant of a [`Palette`]. /// /// [Catppuccin]: https://github.com/catppuccin/catppuccin pub const CATPPUCCIN_MACCHIATO: Self = Self { background: color!(0x24273a), // Base text: color!(0xcad3f5), // Text primary: color!(0x8aadf4), // Blue success: color!(0xa6da95), // Green warning: color!(0xeed49f), // Yellow danger: color!(0xed8796), // Red }; /// The built-in [Catppuccin] Mocha variant of a [`Palette`]. /// /// [Catppuccin]: https://github.com/catppuccin/catppuccin pub const CATPPUCCIN_MOCHA: Self = Self { background: color!(0x1e1e2e), // Base text: color!(0xcdd6f4), // Text primary: color!(0x89b4fa), // Blue success: color!(0xa6e3a1), // Green warning: color!(0xf9e2af), // Yellow danger: color!(0xf38ba8), // Red }; /// The built-in [Tokyo Night] variant of a [`Palette`]. /// /// [Tokyo Night]: https://github.com/enkia/tokyo-night-vscode-theme pub const TOKYO_NIGHT: Self = Self { background: color!(0x1a1b26), // Background (Night) text: color!(0x9aa5ce), // Text primary: color!(0x2ac3de), // Blue success: color!(0x9ece6a), // Green warning: color!(0xe0af68), // Yellow danger: color!(0xf7768e), // Red }; /// The built-in [Tokyo Night] Storm variant of a [`Palette`]. /// /// [Tokyo Night]: https://github.com/enkia/tokyo-night-vscode-theme pub const TOKYO_NIGHT_STORM: Self = Self { background: color!(0x24283b), // Background (Storm) text: color!(0x9aa5ce), // Text primary: color!(0x2ac3de), // Blue success: color!(0x9ece6a), // Green warning: color!(0xe0af68), // Yellow danger: color!(0xf7768e), // Red }; /// The built-in [Tokyo Night] Light variant of a [`Palette`]. /// /// [Tokyo Night]: https://github.com/enkia/tokyo-night-vscode-theme pub const TOKYO_NIGHT_LIGHT: Self = Self { background: color!(0xd5d6db), // Background text: color!(0x565a6e), // Text primary: color!(0x166775), // Blue success: color!(0x485e30), // Green warning: color!(0x8f5e15), // Yellow danger: color!(0x8c4351), // Red }; /// The built-in [Kanagawa] Wave variant of a [`Palette`]. /// /// [Kanagawa]: https://github.com/rebelot/kanagawa.nvim pub const KANAGAWA_WAVE: Self = Self { background: color!(0x1f1f28), // Sumi Ink 3 text: color!(0xDCD7BA), // Fuji White primary: color!(0x7FB4CA), // Wave Blue success: color!(0x76946A), // Autumn Green warning: color!(0xff9e3b), // Ronin Yellow danger: color!(0xC34043), // Autumn Red }; /// The built-in [Kanagawa] Dragon variant of a [`Palette`]. /// /// [Kanagawa]: https://github.com/rebelot/kanagawa.nvim pub const KANAGAWA_DRAGON: Self = Self { background: color!(0x181616), // Dragon Black 3 text: color!(0xc5c9c5), // Dragon White primary: color!(0x223249), // Wave Blue 1 success: color!(0x8a9a7b), // Dragon Green 2 warning: color!(0xff9e3b), // Ronin Yellow danger: color!(0xc4746e), // Dragon Red }; /// The built-in [Kanagawa] Lotus variant of a [`Palette`]. /// /// [Kanagawa]: https://github.com/rebelot/kanagawa.nvim pub const KANAGAWA_LOTUS: Self = Self { background: color!(0xf2ecbc), // Lotus White 3 text: color!(0x545464), // Lotus Ink 1 primary: color!(0x4d699b), // Lotus Blue success: color!(0x6f894e), // Lotus Green warning: color!(0xe98a00), // Lotus Orange 2 danger: color!(0xc84053), // Lotus Red }; /// The built-in [Moonfly] variant of a [`Palette`]. /// /// [Moonfly]: https://github.com/bluz71/vim-moonfly-colors pub const MOONFLY: Self = Self { background: color!(0x080808), // Background text: color!(0xbdbdbd), // Foreground primary: color!(0x80a0ff), // Blue (normal) success: color!(0x8cc85f), // Green (normal) warning: color!(0xe3c78a), // Yellow (normal) danger: color!(0xff5454), // Red (normal) }; /// The built-in [Nightfly] variant of a [`Palette`]. /// /// [Nightfly]: https://github.com/bluz71/vim-nightfly-colors pub const NIGHTFLY: Self = Self { background: color!(0x011627), // Background text: color!(0xbdc1c6), // Foreground primary: color!(0x82aaff), // Blue (normal) success: color!(0xa1cd5e), // Green (normal) warning: color!(0xe3d18a), // Yellow (normal) danger: color!(0xfc514e), // Red (normal) }; /// The built-in [Oxocarbon] variant of a [`Palette`]. /// /// [Oxocarbon]: https://github.com/nyoom-engineering/oxocarbon.nvim pub const OXOCARBON: Self = Self { background: color!(0x232323), text: color!(0xd0d0d0), primary: color!(0x00b4ff), success: color!(0x00c15a), warning: color!(0xbe95ff), // Base 14 danger: color!(0xf62d0f), }; /// The built-in [Ferra] variant of a [`Palette`]. /// /// [Ferra]: https://github.com/casperstorm/ferra pub const FERRA: Self = Self { background: color!(0x2b292d), text: color!(0xfecdb2), primary: color!(0xd1d1e0), success: color!(0xb1b695), warning: color!(0xf5d76e), // Honey danger: color!(0xe06b75), }; } /// An extended set of colors generated from a [`Palette`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Extended { /// The set of background colors. pub background: Background, /// The set of primary colors. pub primary: Primary, /// The set of secondary colors. pub secondary: Secondary, /// The set of success colors. pub success: Success, /// The set of warning colors. pub warning: Warning, /// The set of danger colors. pub danger: Danger, /// Whether the palette is dark or not. pub is_dark: bool, } /// The built-in light variant of an [`Extended`] palette. pub static EXTENDED_LIGHT: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::LIGHT)); /// The built-in dark variant of an [`Extended`] palette. pub static EXTENDED_DARK: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::DARK)); /// The built-in Dracula variant of an [`Extended`] palette. pub static EXTENDED_DRACULA: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::DRACULA)); /// The built-in Nord variant of an [`Extended`] palette. pub static EXTENDED_NORD: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::NORD)); /// The built-in Solarized Light variant of an [`Extended`] palette. pub static EXTENDED_SOLARIZED_LIGHT: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::SOLARIZED_LIGHT)); /// The built-in Solarized Dark variant of an [`Extended`] palette. pub static EXTENDED_SOLARIZED_DARK: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::SOLARIZED_DARK)); /// The built-in Gruvbox Light variant of an [`Extended`] palette. pub static EXTENDED_GRUVBOX_LIGHT: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::GRUVBOX_LIGHT)); /// The built-in Gruvbox Dark variant of an [`Extended`] palette. pub static EXTENDED_GRUVBOX_DARK: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::GRUVBOX_DARK)); /// The built-in Catppuccin Latte variant of an [`Extended`] palette. pub static EXTENDED_CATPPUCCIN_LATTE: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::CATPPUCCIN_LATTE)); /// The built-in Catppuccin Frappé variant of an [`Extended`] palette. pub static EXTENDED_CATPPUCCIN_FRAPPE: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::CATPPUCCIN_FRAPPE)); /// The built-in Catppuccin Macchiato variant of an [`Extended`] palette. pub static EXTENDED_CATPPUCCIN_MACCHIATO: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::CATPPUCCIN_MACCHIATO)); /// The built-in Catppuccin Mocha variant of an [`Extended`] palette. pub static EXTENDED_CATPPUCCIN_MOCHA: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::CATPPUCCIN_MOCHA)); /// The built-in Tokyo Night variant of an [`Extended`] palette. pub static EXTENDED_TOKYO_NIGHT: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::TOKYO_NIGHT)); /// The built-in Tokyo Night Storm variant of an [`Extended`] palette. pub static EXTENDED_TOKYO_NIGHT_STORM: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::TOKYO_NIGHT_STORM)); /// The built-in Tokyo Night variant of an [`Extended`] palette. pub static EXTENDED_TOKYO_NIGHT_LIGHT: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::TOKYO_NIGHT_LIGHT)); /// The built-in Kanagawa Wave variant of an [`Extended`] palette. pub static EXTENDED_KANAGAWA_WAVE: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::KANAGAWA_WAVE)); /// The built-in Kanagawa Dragon variant of an [`Extended`] palette. pub static EXTENDED_KANAGAWA_DRAGON: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::KANAGAWA_DRAGON)); /// The built-in Kanagawa Lotus variant of an [`Extended`] palette. pub static EXTENDED_KANAGAWA_LOTUS: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::KANAGAWA_LOTUS)); /// The built-in Moonfly variant of an [`Extended`] palette. pub static EXTENDED_MOONFLY: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::MOONFLY)); /// The built-in Nightfly variant of an [`Extended`] palette. pub static EXTENDED_NIGHTFLY: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::NIGHTFLY)); /// The built-in Oxocarbon variant of an [`Extended`] palette. pub static EXTENDED_OXOCARBON: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::OXOCARBON)); /// The built-in Ferra variant of an [`Extended`] palette. pub static EXTENDED_FERRA: LazyLock<Extended> = LazyLock::new(|| Extended::generate(Palette::FERRA)); impl Extended { /// Generates an [`Extended`] palette from a simple [`Palette`]. pub fn generate(palette: Palette) -> Self { Self { background: Background::new(palette.background, palette.text), primary: Primary::generate(palette.primary, palette.background, palette.text), secondary: Secondary::generate(palette.background, palette.text), success: Success::generate(palette.success, palette.background, palette.text), warning: Warning::generate(palette.warning, palette.background, palette.text), danger: Danger::generate(palette.danger, palette.background, palette.text), is_dark: is_dark(palette.background), } } } /// A pair of background and text colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Pair { /// The background color. pub color: Color, /// The text color. /// /// It's guaranteed to be readable on top of the background [`color`]. /// /// [`color`]: Self::color pub text: Color, } impl Pair { /// Creates a new [`Pair`] from a background [`Color`] and some text [`Color`]. pub fn new(color: Color, text: Color) -> Self { Self { color, text: readable(color, text), } } } /// A set of background colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Background { /// The base background color. pub base: Pair, /// The weakest version of the base background color. pub weakest: Pair, /// A weaker version of the base background color. pub weaker: Pair, /// A weak version of the base background color. pub weak: Pair, /// A neutral version of the base background color, between weak and strong. pub neutral: Pair, /// A strong version of the base background color. pub strong: Pair, /// A stronger version of the base background color. pub stronger: Pair, /// The strongest version of the base background color. pub strongest: Pair, } impl Background { /// Generates a set of [`Background`] colors from the base and text colors. pub fn new(base: Color, text: Color) -> Self { let weakest = deviate(base, 0.03); let weaker = deviate(base, 0.07); let weak = deviate(base, 0.1); let neutral = deviate(base, 0.125); let strong = deviate(base, 0.15); let stronger = deviate(base, 0.175); let strongest = deviate(base, 0.20); Self { base: Pair::new(base, text), weakest: Pair::new(weakest, text), weaker: Pair::new(weaker, text), weak: Pair::new(weak, text), neutral: Pair::new(neutral, text), strong: Pair::new(strong, text), stronger: Pair::new(stronger, text), strongest: Pair::new(strongest, text), } } } /// A set of primary colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Primary { /// The base primary color. pub base: Pair, /// A weaker version of the base primary color. pub weak: Pair, /// A stronger version of the base primary color. pub strong: Pair, } impl Primary { /// Generates a set of [`Primary`] colors from the base, background, and text colors. pub fn generate(base: Color, background: Color, text: Color) -> Self { let weak = mix(base, background, 0.4); let strong = deviate(base, 0.1); Self { base: Pair::new(base, text), weak: Pair::new(weak, text), strong: Pair::new(strong, text), } } } /// A set of secondary colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Secondary { /// The base secondary color. pub base: Pair, /// A weaker version of the base secondary color. pub weak: Pair, /// A stronger version of the base secondary color. pub strong: Pair, } impl Secondary { /// Generates a set of [`Secondary`] colors from the base and text colors. pub fn generate(base: Color, text: Color) -> Self { let factor = if is_dark(base) { 0.2 } else { 0.4 }; let weak = mix(deviate(base, 0.1), text, factor); let strong = mix(deviate(base, 0.3), text, factor); let base = mix(deviate(base, 0.2), text, factor); Self { base: Pair::new(base, text), weak: Pair::new(weak, text), strong: Pair::new(strong, text), } } } /// A set of success colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Success { /// The base success color. pub base: Pair, /// A weaker version of the base success color. pub weak: Pair, /// A stronger version of the base success color. pub strong: Pair, } impl Success { /// Generates a set of [`Success`] colors from the base, background, and text colors. pub fn generate(base: Color, background: Color, text: Color) -> Self { let weak = mix(base, background, 0.4); let strong = deviate(base, 0.1); Self { base: Pair::new(base, text), weak: Pair::new(weak, text), strong: Pair::new(strong, text), } } } /// A set of warning colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Warning { /// The base warning color. pub base: Pair, /// A weaker version of the base warning color. pub weak: Pair, /// A stronger version of the base warning color. pub strong: Pair, } impl Warning { /// Generates a set of [`Warning`] colors from the base, background, and text colors. pub fn generate(base: Color, background: Color, text: Color) -> Self { let weak = mix(base, background, 0.4); let strong = deviate(base, 0.1); Self { base: Pair::new(base, text), weak: Pair::new(weak, text), strong: Pair::new(strong, text), } } } /// A set of danger colors. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Danger { /// The base danger color. pub base: Pair, /// A weaker version of the base danger color. pub weak: Pair, /// A stronger version of the base danger color. pub strong: Pair, } impl Danger { /// Generates a set of [`Danger`] colors from the base, background, and text colors. pub fn generate(base: Color, background: Color, text: Color) -> Self { let weak = mix(base, background, 0.4); let strong = deviate(base, 0.1); Self { base: Pair::new(base, text), weak: Pair::new(weak, text), strong: Pair::new(strong, text), } } } struct Oklch { l: f32, c: f32, h: f32, a: f32, } /// Darkens a [`Color`] by the given factor. pub fn darken(color: Color, amount: f32) -> Color { let mut oklch = to_oklch(color); // We try to bump the chroma a bit for more colorful palettes if oklch.c > 0.0 && oklch.c < (1.0 - oklch.l) / 2.0 { // Formula empirically and cluelessly derived oklch.c *= 1.0 + (0.2 / oklch.c).min(100.0) * amount; } oklch.l = if oklch.l - amount < 0.0 { 0.0 } else { oklch.l - amount }; from_oklch(oklch) } /// Lightens a [`Color`] by the given factor. pub fn lighten(color: Color, amount: f32) -> Color { let mut oklch = to_oklch(color); // We try to bump the chroma a bit for more colorful palettes // Formula empirically and cluelessly derived oklch.c *= 1.0 + 2.0 * amount / oklch.l.max(0.05); oklch.l = if oklch.l + amount > 1.0 { 1.0 } else { oklch.l + amount }; from_oklch(oklch) } /// Deviates a [`Color`] by the given factor. Lightens if the [`Color`] is /// dark, darkens otherwise. pub fn deviate(color: Color, amount: f32) -> Color { if is_dark(color) { lighten(color, amount) } else { darken(color, amount) } } /// Mixes two colors by the given factor. pub fn mix(a: Color, b: Color, factor: f32) -> Color { let b_amount = factor.clamp(0.0, 1.0); let a_amount = 1.0 - b_amount; let a_linear = a.into_linear().map(|c| c * a_amount); let b_linear = b.into_linear().map(|c| c * b_amount); Color::from_linear_rgba( a_linear[0] + b_linear[0], a_linear[1] + b_linear[1], a_linear[2] + b_linear[2], a_linear[3] + b_linear[3], ) } /// Computes a [`Color`] from the given text color that is /// readable on top of the given background color. pub fn readable(background: Color, text: Color) -> Color { if text.is_readable_on(background) { return text; } let improve = if is_dark(background) { lighten } else { darken }; // TODO: Compute factor from relative contrast value let candidate = improve(text, 0.1); if candidate.is_readable_on(background) { return candidate; } let candidate = improve(text, 0.2); if candidate.is_readable_on(background) { return candidate; } let white_contrast = background.relative_contrast(Color::WHITE); let black_contrast = background.relative_contrast(Color::BLACK); if white_contrast >= black_contrast { mix(Color::WHITE, background, 0.05) } else { mix(Color::BLACK, background, 0.05) } } /// Returns true if the [`Color`] is dark. pub fn is_dark(color: Color) -> bool { to_oklch(color).l < 0.6 } // https://en.wikipedia.org/wiki/Oklab_color_space#Conversions_between_color_spaces fn to_oklch(color: Color) -> Oklch { let [r, g, b, alpha] = color.into_linear(); // linear RGB → LMS let l = 0.41222146 * r + 0.53633255 * g + 0.051445995 * b; let m = 0.2119035 * r + 0.6806995 * g + 0.10739696 * b; let s = 0.08830246 * r + 0.28171885 * g + 0.6299787 * b; // Nonlinear transform (cube root) let l_ = l.cbrt(); let m_ = m.cbrt(); let s_ = s.cbrt(); // LMS → Oklab let l = 0.21045426 * l_ + 0.7936178 * m_ - 0.004072047 * s_; let a = 1.9779985 * l_ - 2.4285922 * m_ + 0.4505937 * s_; let b = 0.025904037 * l_ + 0.78277177 * m_ - 0.80867577 * s_; // Oklab → Oklch let c = (a * a + b * b).sqrt(); let h = b.atan2(a); // radians Oklch { l, c, h, a: alpha } } // https://en.wikipedia.org/wiki/Oklab_color_space#Conversions_between_color_spaces fn from_oklch(oklch: Oklch) -> Color { let Oklch { l, c, h, a: alpha } = oklch; let a = c * h.cos(); let b = c * h.sin(); // Oklab → LMS (nonlinear) let l_ = l + 0.39633778 * a + 0.21580376 * b; let m_ = l - 0.105561346 * a - 0.06385417 * b; let s_ = l - 0.08948418 * a - 1.2914855 * b; // Cubing back let l = l_ * l_ * l_; let m = m_ * m_ * m_; let s = s_ * s_ * s_; let r = 4.0767417 * l - 3.3077116 * m + 0.23096994 * s; let g = -1.268438 * l + 2.6097574 * m - 0.34131938 * s; let b = -0.0041960863 * l - 0.7034186 * m + 1.7076147 * s; Color::from_linear_rgba( r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0), alpha, ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse/button.rs
core/src/mouse/button.rs
/// The button of a mouse. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum Button { /// The left mouse button. Left, /// The right mouse button. Right, /// The middle (wheel) button. Middle, /// The back mouse button. Back, /// The forward mouse button. Forward, /// Some other button. Other(u16), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse/event.rs
core/src/mouse/event.rs
use crate::Point; use super::Button; /// A mouse event. /// /// _**Note:** This type is largely incomplete! If you need to track /// additional events, feel free to [open an issue] and share your use case!_ /// /// [open an issue]: https://github.com/iced-rs/iced/issues #[derive(Debug, Clone, Copy, PartialEq)] pub enum Event { /// The mouse cursor entered the window. CursorEntered, /// The mouse cursor left the window. CursorLeft, /// The mouse cursor was moved CursorMoved { /// The new position of the mouse cursor position: Point, }, /// A mouse button was pressed. ButtonPressed(Button), /// A mouse button was released. ButtonReleased(Button), /// The mouse wheel was scrolled. WheelScrolled { /// The scroll movement. delta: ScrollDelta, }, } /// A scroll movement. #[derive(Debug, Clone, Copy, PartialEq)] pub enum ScrollDelta { /// A line-based scroll movement Lines { /// The number of horizontal lines scrolled x: f32, /// The number of vertical lines scrolled y: f32, }, /// A pixel-based scroll movement Pixels { /// The number of horizontal pixels scrolled x: f32, /// The number of vertical pixels scrolled y: f32, }, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse/cursor.rs
core/src/mouse/cursor.rs
use crate::{Point, Rectangle, Transformation, Vector}; /// The mouse cursor state. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub enum Cursor { /// The cursor has a defined position. Available(Point), /// The cursor has a defined position, but it's levitating over a layer above. Levitating(Point), /// The cursor is currently unavailable (i.e. out of bounds or busy). #[default] Unavailable, } impl Cursor { /// Returns the absolute position of the [`Cursor`], if available. pub fn position(self) -> Option<Point> { match self { Cursor::Available(position) => Some(position), Cursor::Levitating(_) | Cursor::Unavailable => None, } } /// Returns the absolute position of the [`Cursor`], if available and inside /// the given bounds. /// /// If the [`Cursor`] is not over the provided bounds, this method will /// return `None`. pub fn position_over(self, bounds: Rectangle) -> Option<Point> { self.position().filter(|p| bounds.contains(*p)) } /// Returns the relative position of the [`Cursor`] inside the given bounds, /// if available. /// /// If the [`Cursor`] is not over the provided bounds, this method will /// return `None`. pub fn position_in(self, bounds: Rectangle) -> Option<Point> { self.position_over(bounds) .map(|p| p - Vector::new(bounds.x, bounds.y)) } /// Returns the relative position of the [`Cursor`] from the given origin, /// if available. pub fn position_from(self, origin: Point) -> Option<Point> { self.position().map(|p| p - Vector::new(origin.x, origin.y)) } /// Returns true if the [`Cursor`] is over the given `bounds`. pub fn is_over(self, bounds: Rectangle) -> bool { self.position_over(bounds).is_some() } /// Returns true if the [`Cursor`] is levitating over a layer above. pub fn is_levitating(self) -> bool { matches!(self, Self::Levitating(_)) } /// Makes the [`Cursor`] levitate over a layer above. pub fn levitate(self) -> Self { match self { Self::Available(position) => Self::Levitating(position), _ => self, } } /// Brings the [`Cursor`] back to the current layer. pub fn land(self) -> Self { match self { Cursor::Levitating(position) => Cursor::Available(position), _ => self, } } } impl std::ops::Add<Vector> for Cursor { type Output = Self; fn add(self, translation: Vector) -> Self::Output { match self { Cursor::Available(point) => Cursor::Available(point + translation), Cursor::Levitating(point) => Cursor::Levitating(point + translation), Cursor::Unavailable => Cursor::Unavailable, } } } impl std::ops::Sub<Vector> for Cursor { type Output = Self; fn sub(self, translation: Vector) -> Self::Output { match self { Cursor::Available(point) => Cursor::Available(point - translation), Cursor::Levitating(point) => Cursor::Levitating(point - translation), Cursor::Unavailable => Cursor::Unavailable, } } } impl std::ops::Mul<Transformation> for Cursor { type Output = Self; fn mul(self, transformation: Transformation) -> Self { match self { Self::Available(position) => Self::Available(position * transformation), Self::Levitating(position) => Self::Levitating(position * transformation), Self::Unavailable => Self::Unavailable, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse/click.rs
core/src/mouse/click.rs
//! Track mouse clicks. use crate::mouse::Button; use crate::time::Instant; use crate::{Point, Transformation}; use std::ops::Mul; /// A mouse click. #[derive(Debug, Clone, Copy)] pub struct Click { kind: Kind, button: Button, position: Point, time: Instant, } /// The kind of mouse click. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { /// A single click Single, /// A double click Double, /// A triple click Triple, } impl Kind { fn next(self) -> Kind { match self { Kind::Single => Kind::Double, Kind::Double => Kind::Triple, Kind::Triple => Kind::Double, } } } impl Click { /// Creates a new [`Click`] with the given position and previous last /// [`Click`]. pub fn new(position: Point, button: Button, previous: Option<Click>) -> Click { let time = Instant::now(); let kind = if let Some(previous) = previous { if previous.is_consecutive(position, time) && button == previous.button { previous.kind.next() } else { Kind::Single } } else { Kind::Single }; Click { kind, button, position, time, } } /// Returns the [`Kind`] of [`Click`]. pub fn kind(&self) -> Kind { self.kind } /// Returns the position of the [`Click`]. pub fn position(&self) -> Point { self.position } fn is_consecutive(&self, new_position: Point, time: Instant) -> bool { let duration = if time > self.time { Some(time - self.time) } else { None }; self.position.distance(new_position) < 6.0 && duration .map(|duration| duration.as_millis() <= 300) .unwrap_or(false) } } impl Mul<Transformation> for Click { type Output = Click; fn mul(self, transformation: Transformation) -> Click { Click { kind: self.kind, button: self.button, position: self.position * transformation, time: self.time, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/mouse/interaction.rs
core/src/mouse/interaction.rs
/// The interaction of a mouse cursor. #[derive(Debug, Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Default)] #[allow(missing_docs)] pub enum Interaction { #[default] None, Hidden, Idle, ContextMenu, Help, Pointer, Progress, Wait, Cell, Crosshair, Text, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, ResizingHorizontally, ResizingVertically, ResizingDiagonallyUp, ResizingDiagonallyDown, ResizingColumn, ResizingRow, AllScroll, ZoomIn, ZoomOut, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/text/editor.rs
core/src/text/editor.rs
//! Edit text. use crate::text::highlighter::{self, Highlighter}; use crate::text::{LineHeight, Wrapping}; use crate::{Pixels, Point, Rectangle, Size}; use std::borrow::Cow; use std::sync::Arc; /// A component that can be used by widgets to edit multi-line text. pub trait Editor: Sized + Default { /// The font of the [`Editor`]. type Font: Copy + PartialEq + Default; /// Creates a new [`Editor`] laid out with the given text. fn with_text(text: &str) -> Self; /// Returns true if the [`Editor`] has no contents. fn is_empty(&self) -> bool; /// Returns the current [`Cursor`] of the [`Editor`]. fn cursor(&self) -> Cursor; /// Returns the current [`Selection`] of the [`Editor`]. fn selection(&self) -> Selection; /// Returns the current selected text of the [`Editor`]. fn copy(&self) -> Option<String>; /// Returns the text of the given line in the [`Editor`], if it exists. fn line(&self, index: usize) -> Option<Line<'_>>; /// Returns the amount of lines in the [`Editor`]. fn line_count(&self) -> usize; /// Performs an [`Action`] on the [`Editor`]. fn perform(&mut self, action: Action); /// Moves the cursor to the given position. fn move_to(&mut self, cursor: Cursor); /// Returns the current boundaries of the [`Editor`]. fn bounds(&self) -> Size; /// Returns the minimum boundaries to fit the current contents of /// the [`Editor`]. fn min_bounds(&self) -> Size; /// Returns the hint factor of the [`Editor`]. fn hint_factor(&self) -> Option<f32>; /// Updates the [`Editor`] with some new attributes. fn update( &mut self, new_bounds: Size, new_font: Self::Font, new_size: Pixels, new_line_height: LineHeight, new_wrapping: Wrapping, new_hint_factor: Option<f32>, new_highlighter: &mut impl Highlighter, ); /// Runs a text [`Highlighter`] in the [`Editor`]. fn highlight<H: Highlighter>( &mut self, font: Self::Font, highlighter: &mut H, format_highlight: impl Fn(&H::Highlight) -> highlighter::Format<Self::Font>, ); } /// An interaction with an [`Editor`]. #[derive(Debug, Clone, PartialEq)] pub enum Action { /// Apply a [`Motion`]. Move(Motion), /// Select text with a given [`Motion`]. Select(Motion), /// Select the word at the current cursor. SelectWord, /// Select the line at the current cursor. SelectLine, /// Select the entire buffer. SelectAll, /// Perform an [`Edit`]. Edit(Edit), /// Click the [`Editor`] at the given [`Point`]. Click(Point), /// Drag the mouse on the [`Editor`] to the given [`Point`]. Drag(Point), /// Scroll the [`Editor`] a certain amount of lines. Scroll { /// The amount of lines to scroll. lines: i32, }, } impl Action { /// Returns whether the [`Action`] is an editing action. pub fn is_edit(&self) -> bool { matches!(self, Self::Edit(_)) } } /// An action that edits text. #[derive(Debug, Clone, PartialEq)] pub enum Edit { /// Insert the given character. Insert(char), /// Paste the given text. Paste(Arc<String>), /// Break the current line. Enter, /// Indent the current line. Indent, /// Unindent the current line. Unindent, /// Delete the previous character. Backspace, /// Delete the next character. Delete, } /// A cursor movement. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Motion { /// Move left. Left, /// Move right. Right, /// Move up. Up, /// Move down. Down, /// Move to the left boundary of a word. WordLeft, /// Move to the right boundary of a word. WordRight, /// Move to the start of the line. Home, /// Move to the end of the line. End, /// Move to the start of the previous window. PageUp, /// Move to the start of the next window. PageDown, /// Move to the start of the text. DocumentStart, /// Move to the end of the text. DocumentEnd, } impl Motion { /// Widens the [`Motion`], if possible. pub fn widen(self) -> Self { match self { Self::Left => Self::WordLeft, Self::Right => Self::WordRight, Self::Home => Self::DocumentStart, Self::End => Self::DocumentEnd, _ => self, } } /// Returns the [`Direction`] of the [`Motion`]. pub fn direction(&self) -> Direction { match self { Self::Left | Self::Up | Self::WordLeft | Self::Home | Self::PageUp | Self::DocumentStart => Direction::Left, Self::Right | Self::Down | Self::WordRight | Self::End | Self::PageDown | Self::DocumentEnd => Direction::Right, } } } /// A direction in some text. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Direction { /// <- Left, /// -> Right, } /// The cursor of an [`Editor`]. #[derive(Debug, Clone)] pub enum Selection { /// Cursor without a selection Caret(Point), /// Cursor selecting a range of text Range(Vec<Rectangle>), } /// The range of an [`Editor`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Cursor { /// The cursor position. pub position: Position, /// The selection position, if any. pub selection: Option<Position>, } /// A cursor position in an [`Editor`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Position { /// The line of text. pub line: usize, /// The column in the line. pub column: usize, } /// A line of an [`Editor`]. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Line<'a> { /// The raw text of the [`Line`]. pub text: Cow<'a, str>, /// The line ending of the [`Line`]. pub ending: LineEnding, } /// The line ending of a [`Line`]. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum LineEnding { /// Use `\n` for line ending (POSIX-style) #[default] Lf, /// Use `\r\n` for line ending (Windows-style) CrLf, /// Use `\r` for line ending (many legacy systems) Cr, /// Use `\n\r` for line ending (some legacy systems) LfCr, /// No line ending None, } impl LineEnding { /// Gets the string representation of the [`LineEnding`]. pub fn as_str(self) -> &'static str { match self { Self::Lf => "\n", Self::CrLf => "\r\n", Self::Cr => "\r", Self::LfCr => "\n\r", Self::None => "", } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/text/highlighter.rs
core/src/text/highlighter.rs
//! Highlight text. use crate::Color; use std::ops::Range; /// A type capable of highlighting text. /// /// A [`Highlighter`] highlights lines in sequence. When a line changes, /// it must be notified and the lines after the changed one must be fed /// again to the [`Highlighter`]. pub trait Highlighter: 'static { /// The settings to configure the [`Highlighter`]. type Settings: PartialEq + Clone; /// The output of the [`Highlighter`]. type Highlight; /// The highlight iterator type. type Iterator<'a>: Iterator<Item = (Range<usize>, Self::Highlight)> where Self: 'a; /// Creates a new [`Highlighter`] from its [`Self::Settings`]. fn new(settings: &Self::Settings) -> Self; /// Updates the [`Highlighter`] with some new [`Self::Settings`]. fn update(&mut self, new_settings: &Self::Settings); /// Notifies the [`Highlighter`] that the line at the given index has changed. fn change_line(&mut self, line: usize); /// Highlights the given line. /// /// If a line changed prior to this, the first line provided here will be the /// line that changed. fn highlight_line(&mut self, line: &str) -> Self::Iterator<'_>; /// Returns the current line of the [`Highlighter`]. /// /// If `change_line` has been called, this will normally be the least index /// that changed. fn current_line(&self) -> usize; } /// A highlighter that highlights nothing. #[derive(Debug, Clone, Copy)] pub struct PlainText; impl Highlighter for PlainText { type Settings = (); type Highlight = (); type Iterator<'a> = std::iter::Empty<(Range<usize>, Self::Highlight)>; fn new(_settings: &Self::Settings) -> Self { Self } fn update(&mut self, _new_settings: &Self::Settings) {} fn change_line(&mut self, _line: usize) {} fn highlight_line(&mut self, _line: &str) -> Self::Iterator<'_> { std::iter::empty() } fn current_line(&self) -> usize { usize::MAX } } /// The format of some text. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Format<Font> { /// The [`Color`] of the text. pub color: Option<Color>, /// The `Font` of the text. pub font: Option<Font>, } impl<Font> Default for Format<Font> { fn default() -> Self { Self { color: None, font: None, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/text/paragraph.rs
core/src/text/paragraph.rs
//! Draw paragraphs. use crate::alignment; use crate::text::{Alignment, Difference, Hit, LineHeight, Shaping, Span, Text, Wrapping}; use crate::{Pixels, Point, Rectangle, Size}; /// A text paragraph. pub trait Paragraph: Sized + Default { /// The font of this [`Paragraph`]. type Font: Copy + PartialEq; /// Creates a new [`Paragraph`] laid out with the given [`Text`]. fn with_text(text: Text<&str, Self::Font>) -> Self; /// Creates a new [`Paragraph`] laid out with the given [`Text`]. fn with_spans<Link>(text: Text<&[Span<'_, Link, Self::Font>], Self::Font>) -> Self; /// Lays out the [`Paragraph`] with some new boundaries. fn resize(&mut self, new_bounds: Size); /// Compares the [`Paragraph`] with some desired [`Text`] and returns the /// [`Difference`]. fn compare(&self, text: Text<(), Self::Font>) -> Difference; /// Returns the text size of the [`Paragraph`] in [`Pixels`]. fn size(&self) -> Pixels; /// Returns the hint factor of the [`Paragraph`]. fn hint_factor(&self) -> Option<f32>; /// Returns the font of the [`Paragraph`]. fn font(&self) -> Self::Font; /// Returns the [`LineHeight`] of the [`Paragraph`]. fn line_height(&self) -> LineHeight; /// Returns the horizontal alignment of the [`Paragraph`]. fn align_x(&self) -> Alignment; /// Returns the vertical alignment of the [`Paragraph`]. fn align_y(&self) -> alignment::Vertical; /// Returns the [`Wrapping`] strategy of the [`Paragraph`]> fn wrapping(&self) -> Wrapping; /// Returns the [`Shaping`] strategy of the [`Paragraph`]> fn shaping(&self) -> Shaping; /// Returns the available bounds used to layout the [`Paragraph`]. fn bounds(&self) -> Size; /// Returns the minimum boundaries that can fit the contents of the /// [`Paragraph`]. fn min_bounds(&self) -> Size; /// Tests whether the provided point is within the boundaries of the /// [`Paragraph`], returning information about the nearest character. fn hit_test(&self, point: Point) -> Option<Hit>; /// Tests whether the provided point is within the boundaries of a /// [`Span`] in the [`Paragraph`], returning the index of the [`Span`] /// that was hit. fn hit_span(&self, point: Point) -> Option<usize>; /// Returns all bounds for the provided [`Span`] index of the [`Paragraph`]. /// A [`Span`] can have multiple bounds for each line it's on. fn span_bounds(&self, index: usize) -> Vec<Rectangle>; /// Returns the distance to the given grapheme index in the [`Paragraph`]. fn grapheme_position(&self, line: usize, index: usize) -> Option<Point>; /// Returns the minimum width that can fit the contents of the [`Paragraph`]. fn min_width(&self) -> f32 { self.min_bounds().width } /// Returns the minimum height that can fit the contents of the [`Paragraph`]. fn min_height(&self) -> f32 { self.min_bounds().height } } /// A [`Paragraph`] of plain text. #[derive(Debug, Clone, Default)] pub struct Plain<P: Paragraph> { raw: P, content: String, } impl<P: Paragraph> Plain<P> { /// Creates a new [`Plain`] paragraph. pub fn new(text: Text<String, P::Font>) -> Self { Self { raw: P::with_text(text.as_ref()), content: text.content, } } /// Updates the plain [`Paragraph`] to match the given [`Text`], if needed. /// /// Returns true if the [`Paragraph`] changed. pub fn update(&mut self, text: Text<&str, P::Font>) -> bool { if self.content != text.content { text.content.clone_into(&mut self.content); self.raw = P::with_text(text); return true; } match self.raw.compare(text.with_content(())) { Difference::None => false, Difference::Bounds => { self.raw.resize(text.bounds); true } Difference::Shape => { self.raw = P::with_text(text); true } } } /// Returns the horizontal alignment of the [`Paragraph`]. pub fn align_x(&self) -> Alignment { self.raw.align_x() } /// Returns the vertical alignment of the [`Paragraph`]. pub fn align_y(&self) -> alignment::Vertical { self.raw.align_y() } /// Returns the minimum boundaries that can fit the contents of the /// [`Paragraph`]. pub fn min_bounds(&self) -> Size { self.raw.min_bounds() } /// Returns the minimum width that can fit the contents of the /// [`Paragraph`]. pub fn min_width(&self) -> f32 { self.raw.min_width() } /// Returns the minimum height that can fit the contents of the /// [`Paragraph`]. pub fn min_height(&self) -> f32 { self.raw.min_height() } /// Returns the cached [`Paragraph`]. pub fn raw(&self) -> &P { &self.raw } /// Returns the current content of the plain [`Paragraph`]. pub fn content(&self) -> &str { &self.content } /// Returns the [`Paragraph`] as a [`Text`] definition. pub fn as_text(&self) -> Text<&str, P::Font> { Text { content: &self.content, bounds: self.raw.bounds(), size: self.raw.size(), line_height: self.raw.line_height(), font: self.raw.font(), align_x: self.raw.align_x(), align_y: self.raw.align_y(), shaping: self.raw.shaping(), wrapping: self.raw.wrapping(), hint_factor: self.raw.hint_factor(), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/keyboard/event.rs
core/src/keyboard/event.rs
use crate::SmolStr; use crate::keyboard::key; use crate::keyboard::{Key, Location, Modifiers}; /// A keyboard event. /// /// _**Note:** This type is largely incomplete! If you need to track /// additional events, feel free to [open an issue] and share your use case!_ /// /// [open an issue]: https://github.com/iced-rs/iced/issues #[derive(Debug, Clone, PartialEq, Eq)] pub enum Event { /// A keyboard key was pressed. KeyPressed { /// The key pressed. key: Key, /// The key pressed with all keyboard modifiers applied, except Ctrl. modified_key: Key, /// The physical key pressed. physical_key: key::Physical, /// The location of the key. location: Location, /// The state of the modifier keys. modifiers: Modifiers, /// The text produced by the key press, if any. text: Option<SmolStr>, /// Whether the event was the result of key repeat. repeat: bool, }, /// A keyboard key was released. KeyReleased { /// The key released. key: Key, /// The key released with all keyboard modifiers applied, except Ctrl. modified_key: Key, /// The physical key released. physical_key: key::Physical, /// The location of the key. location: Location, /// The state of the modifier keys. modifiers: Modifiers, }, /// The keyboard modifiers have changed. ModifiersChanged(Modifiers), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/keyboard/key.rs
core/src/keyboard/key.rs
//! Identify keyboard keys. use crate::SmolStr; /// A key on the keyboard. /// /// This is mostly the `Key` type found in [`winit`]. /// /// [`winit`]: https://docs.rs/winit/0.30/winit/keyboard/enum.Key.html #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Key<C = SmolStr> { /// A key with an established name. Named(Named), /// A key string that corresponds to the character typed by the user, taking into account the /// user’s current locale setting, and any system-level keyboard mapping overrides that are in /// effect. Character(C), /// An unidentified key. Unidentified, } impl Key { /// Convert `Key::Character(SmolStr)` to `Key::Character(&str)` so you can more easily match on /// `Key`. All other variants remain unchanged. pub fn as_ref(&self) -> Key<&str> { match self { Self::Named(named) => Key::Named(*named), Self::Character(c) => Key::Character(c.as_ref()), Self::Unidentified => Key::Unidentified, } } /// Tries to convert this logical [`Key`] into its latin character, using the /// [`Physical`] key provided for translation if it isn't already in latin. /// /// Returns `None` if no latin variant could be found. /// /// ``` /// use iced_core::keyboard::key::{Key, Named, Physical, Code}; /// /// // Latin c /// assert_eq!( /// Key::Character("c".into()).to_latin(Physical::Code(Code::KeyC)), /// Some('c'), /// ); /// /// // Cyrillic с /// assert_eq!( /// Key::Character("с".into()).to_latin(Physical::Code(Code::KeyC)), /// Some('c'), /// ); /// /// // Arrow Left /// assert_eq!( /// Key::Named(Named::ArrowLeft).to_latin(Physical::Code(Code::ArrowLeft)), /// None, /// ); /// ``` pub fn to_latin(&self, physical_key: Physical) -> Option<char> { let Self::Character(s) = self else { return None; }; let mut chars = s.chars(); let c = chars.next()?; if chars.next().is_none() && c < '\u{370}' { return Some(c); } let Physical::Code(code) = physical_key else { return None; }; let latin = match code { Code::KeyA => 'a', Code::KeyB => 'b', Code::KeyC => 'c', Code::KeyD => 'd', Code::KeyE => 'e', Code::KeyF => 'f', Code::KeyG => 'g', Code::KeyH => 'h', Code::KeyI => 'i', Code::KeyJ => 'j', Code::KeyK => 'k', Code::KeyL => 'l', Code::KeyM => 'm', Code::KeyN => 'n', Code::KeyO => 'o', Code::KeyP => 'p', Code::KeyQ => 'q', Code::KeyR => 'r', Code::KeyS => 's', Code::KeyT => 't', Code::KeyU => 'u', Code::KeyV => 'v', Code::KeyW => 'w', Code::KeyX => 'x', Code::KeyY => 'y', Code::KeyZ => 'z', Code::Digit0 => '0', Code::Digit1 => '1', Code::Digit2 => '2', Code::Digit3 => '3', Code::Digit4 => '4', Code::Digit5 => '5', Code::Digit6 => '6', Code::Digit7 => '7', Code::Digit8 => '8', Code::Digit9 => '9', _ => return None, }; Some(latin) } } impl From<Named> for Key { fn from(named: Named) -> Self { Self::Named(named) } } /// A named key. /// /// This is mostly the `NamedKey` type found in [`winit`]. /// /// [`winit`]: https://docs.rs/winit/0.30/winit/keyboard/enum.Key.html #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub enum Named { /// The `Alt` (Alternative) key. /// /// This key enables the alternate modifier function for interpreting concurrent or subsequent /// keyboard input. This key value is also used for the Apple <kbd>Option</kbd> key. Alt, /// The Alternate Graphics (<kbd>AltGr</kbd> or <kbd>AltGraph</kbd>) key. /// /// This key is used enable the ISO Level 3 shift modifier (the standard `Shift` key is the /// level 2 modifier). AltGraph, /// The `Caps Lock` (Capital) key. /// /// Toggle capital character lock function for interpreting subsequent keyboard input event. CapsLock, /// The `Control` or `Ctrl` key. /// /// Used to enable control modifier function for interpreting concurrent or subsequent keyboard /// input. Control, /// The Function switch `Fn` key. Activating this key simultaneously with another key changes /// that key’s value to an alternate character or function. This key is often handled directly /// in the keyboard hardware and does not usually generate key events. Fn, /// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key switches the mode of the /// keyboard to changes some keys' values to an alternate character or function. This key is /// often handled directly in the keyboard hardware and does not usually generate key events. FnLock, /// The `NumLock` or Number Lock key. Used to toggle numpad mode function for interpreting /// subsequent keyboard input. NumLock, /// Toggle between scrolling and cursor movement modes. ScrollLock, /// Used to enable shift modifier function for interpreting concurrent or subsequent keyboard /// input. Shift, /// The Symbol modifier key (used on some virtual keyboards). Symbol, SymbolLock, // Legacy modifier key. Also called "Super" in certain places. Meta, // Legacy modifier key. Hyper, /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘` key. /// /// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key. Super, /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This key /// value is also used for the `Return` (Macintosh numpad) key. This key value is also used for /// the Android `KEYCODE_DPAD_CENTER`. Enter, /// The Horizontal Tabulation `Tab` key. Tab, /// Used in text to insert a space between words. Usually located below the character keys. Space, /// Navigate or traverse downward. (`KEYCODE_DPAD_DOWN`) ArrowDown, /// Navigate or traverse leftward. (`KEYCODE_DPAD_LEFT`) ArrowLeft, /// Navigate or traverse rightward. (`KEYCODE_DPAD_RIGHT`) ArrowRight, /// Navigate or traverse upward. (`KEYCODE_DPAD_UP`) ArrowUp, /// The End key, used with keyboard entry to go to the end of content (`KEYCODE_MOVE_END`). End, /// The Home key, used with keyboard entry, to go to start of content (`KEYCODE_MOVE_HOME`). /// For the mobile phone `Home` key (which goes to the phone’s main screen), use [`GoHome`]. /// /// [`GoHome`]: Self::GoHome Home, /// Scroll down or display next page of content. PageDown, /// Scroll up or display previous page of content. PageUp, /// Used to remove the character to the left of the cursor. This key value is also used for /// the key labeled `Delete` on MacOS keyboards. Backspace, /// Remove the currently selected input. Clear, /// Copy the current selection. (`APPCOMMAND_COPY`) Copy, /// The Cursor Select key. CrSel, /// Cut the current selection. (`APPCOMMAND_CUT`) Cut, /// Used to delete the character to the right of the cursor. This key value is also used for the /// key labeled `Delete` on MacOS keyboards when `Fn` is active. Delete, /// The Erase to End of Field key. This key deletes all characters from the current cursor /// position to the end of the current field. EraseEof, /// The Extend Selection (Exsel) key. ExSel, /// Toggle between text modes for insertion or overtyping. /// (`KEYCODE_INSERT`) Insert, /// The Paste key. (`APPCOMMAND_PASTE`) Paste, /// Redo the last action. (`APPCOMMAND_REDO`) Redo, /// Undo the last action. (`APPCOMMAND_UNDO`) Undo, /// The Accept (Commit, OK) key. Accept current option or input method sequence conversion. Accept, /// Redo or repeat an action. Again, /// The Attention (Attn) key. Attn, Cancel, /// Show the application’s context menu. /// This key is commonly found between the right `Super` key and the right `Control` key. ContextMenu, /// The `Esc` key. This key was originally used to initiate an escape sequence, but is /// now more generally used to exit or "escape" the current context, such as closing a dialog /// or exiting full screen mode. Escape, Execute, /// Open the Find dialog. (`APPCOMMAND_FIND`) Find, /// Open a help dialog or toggle display of help information. (`APPCOMMAND_HELP`, /// `KEYCODE_HELP`) Help, /// Pause the current state or application (as appropriate). /// /// Note: Do not use this value for the `Pause` button on media controllers. Use `"MediaPause"` /// instead. Pause, /// Play or resume the current state or application (as appropriate). /// /// Note: Do not use this value for the `Play` button on media controllers. Use `"MediaPlay"` /// instead. Play, /// The properties (Props) key. Props, Select, /// The ZoomIn key. (`KEYCODE_ZOOM_IN`) ZoomIn, /// The ZoomOut key. (`KEYCODE_ZOOM_OUT`) ZoomOut, /// The Brightness Down key. Typically controls the display brightness. /// (`KEYCODE_BRIGHTNESS_DOWN`) BrightnessDown, /// The Brightness Up key. Typically controls the display brightness. (`KEYCODE_BRIGHTNESS_UP`) BrightnessUp, /// Toggle removable media to eject (open) and insert (close) state. (`KEYCODE_MEDIA_EJECT`) Eject, LogOff, /// Toggle power state. (`KEYCODE_POWER`) /// Note: Note: Some devices might not expose this key to the operating environment. Power, /// The `PowerOff` key. Sometime called `PowerDown`. PowerOff, /// Initiate print-screen function. PrintScreen, /// The Hibernate key. This key saves the current state of the computer to disk so that it can /// be restored. The computer will then shutdown. Hibernate, /// The Standby key. This key turns off the display and places the computer into a low-power /// mode without completely shutting down. It is sometimes labelled `Suspend` or `Sleep` key. /// (`KEYCODE_SLEEP`) Standby, /// The WakeUp key. (`KEYCODE_WAKEUP`) WakeUp, /// Initiate the multi-candidate mode. AllCandidates, Alphanumeric, /// Initiate the Code Input mode to allow characters to be entered by /// their code points. CodeInput, /// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a /// manner similar to a dead key, triggering a mode where subsequent key presses are combined to /// produce a different character. Compose, /// Convert the current input method sequence. Convert, /// The Final Mode `Final` key used on some Asian keyboards, to enable the final mode for IMEs. FinalMode, /// Switch to the first character group. (ISO/IEC 9995) GroupFirst, /// Switch to the last character group. (ISO/IEC 9995) GroupLast, /// Switch to the next character group. (ISO/IEC 9995) GroupNext, /// Switch to the previous character group. (ISO/IEC 9995) GroupPrevious, /// Toggle between or cycle through input modes of IMEs. ModeChange, NextCandidate, /// Accept current input method sequence without /// conversion in IMEs. NonConvert, PreviousCandidate, Process, SingleCandidate, /// Toggle between Hangul and English modes. HangulMode, HanjaMode, JunjaMode, /// The Eisu key. This key may close the IME, but its purpose is defined by the current IME. /// (`KEYCODE_EISU`) Eisu, /// The (Half-Width) Characters key. Hankaku, /// The Hiragana (Japanese Kana characters) key. Hiragana, /// The Hiragana/Katakana toggle key. (`KEYCODE_KATAKANA_HIRAGANA`) HiraganaKatakana, /// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from /// romaji mode). KanaMode, /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key is /// typically used to switch to a hiragana keyboard for the purpose of converting input into /// kanji. (`KEYCODE_KANA`) KanjiMode, /// The Katakana (Japanese Kana characters) key. Katakana, /// The Roman characters function key. Romaji, /// The Zenkaku (Full-Width) Characters key. Zenkaku, /// The Zenkaku/Hankaku (full-width/half-width) toggle key. (`KEYCODE_ZENKAKU_HANKAKU`) ZenkakuHankaku, /// General purpose virtual function key, as index 1. Soft1, /// General purpose virtual function key, as index 2. Soft2, /// General purpose virtual function key, as index 3. Soft3, /// General purpose virtual function key, as index 4. Soft4, /// Select next (numerically or logically) lower channel. (`APPCOMMAND_MEDIA_CHANNEL_DOWN`, /// `KEYCODE_CHANNEL_DOWN`) ChannelDown, /// Select next (numerically or logically) higher channel. (`APPCOMMAND_MEDIA_CHANNEL_UP`, /// `KEYCODE_CHANNEL_UP`) ChannelUp, /// Close the current document or message (Note: This doesn’t close the application). /// (`APPCOMMAND_CLOSE`) Close, /// Open an editor to forward the current message. (`APPCOMMAND_FORWARD_MAIL`) MailForward, /// Open an editor to reply to the current message. (`APPCOMMAND_REPLY_TO_MAIL`) MailReply, /// Send the current message. (`APPCOMMAND_SEND_MAIL`) MailSend, /// Close the current media, for example to close a CD or DVD tray. (`KEYCODE_MEDIA_CLOSE`) MediaClose, /// Initiate or continue forward playback at faster than normal speed, or increase speed if /// already fast forwarding. (`APPCOMMAND_MEDIA_FAST_FORWARD`, `KEYCODE_MEDIA_FAST_FORWARD`) MediaFastForward, /// Pause the currently playing media. (`APPCOMMAND_MEDIA_PAUSE`, `KEYCODE_MEDIA_PAUSE`) /// /// Note: Media controller devices should use this value rather than `"Pause"` for their pause /// keys. MediaPause, /// Initiate or continue media playback at normal speed, if not currently playing at normal /// speed. (`APPCOMMAND_MEDIA_PLAY`, `KEYCODE_MEDIA_PLAY`) MediaPlay, /// Toggle media between play and pause states. (`APPCOMMAND_MEDIA_PLAY_PAUSE`, /// `KEYCODE_MEDIA_PLAY_PAUSE`) MediaPlayPause, /// Initiate or resume recording of currently selected media. (`APPCOMMAND_MEDIA_RECORD`, /// `KEYCODE_MEDIA_RECORD`) MediaRecord, /// Initiate or continue reverse playback at faster than normal speed, or increase speed if /// already rewinding. (`APPCOMMAND_MEDIA_REWIND`, `KEYCODE_MEDIA_REWIND`) MediaRewind, /// Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped. /// (`APPCOMMAND_MEDIA_STOP`, `KEYCODE_MEDIA_STOP`) MediaStop, /// Seek to next media or program track. (`APPCOMMAND_MEDIA_NEXTTRACK`, `KEYCODE_MEDIA_NEXT`) MediaTrackNext, /// Seek to previous media or program track. (`APPCOMMAND_MEDIA_PREVIOUSTRACK`, /// `KEYCODE_MEDIA_PREVIOUS`) MediaTrackPrevious, /// Open a new document or message. (`APPCOMMAND_NEW`) New, /// Open an existing document or message. (`APPCOMMAND_OPEN`) Open, /// Print the current document or message. (`APPCOMMAND_PRINT`) Print, /// Save the current document or message. (`APPCOMMAND_SAVE`) Save, /// Spellcheck the current document or selection. (`APPCOMMAND_SPELL_CHECK`) SpellCheck, /// The `11` key found on media numpads that /// have buttons from `1` ... `12`. Key11, /// The `12` key found on media numpads that /// have buttons from `1` ... `12`. Key12, /// Adjust audio balance leftward. (`VK_AUDIO_BALANCE_LEFT`) AudioBalanceLeft, /// Adjust audio balance rightward. (`VK_AUDIO_BALANCE_RIGHT`) AudioBalanceRight, /// Decrease audio bass boost or cycle down through bass boost states. (`APPCOMMAND_BASS_DOWN`, /// `VK_BASS_BOOST_DOWN`) AudioBassBoostDown, /// Toggle bass boost on/off. (`APPCOMMAND_BASS_BOOST`) AudioBassBoostToggle, /// Increase audio bass boost or cycle up through bass boost states. (`APPCOMMAND_BASS_UP`, /// `VK_BASS_BOOST_UP`) AudioBassBoostUp, /// Adjust audio fader towards front. (`VK_FADER_FRONT`) AudioFaderFront, /// Adjust audio fader towards rear. (`VK_FADER_REAR`) AudioFaderRear, /// Advance surround audio mode to next available mode. (`VK_SURROUND_MODE_NEXT`) AudioSurroundModeNext, /// Decrease treble. (`APPCOMMAND_TREBLE_DOWN`) AudioTrebleDown, /// Increase treble. (`APPCOMMAND_TREBLE_UP`) AudioTrebleUp, /// Decrease audio volume. (`APPCOMMAND_VOLUME_DOWN`, `KEYCODE_VOLUME_DOWN`) AudioVolumeDown, /// Increase audio volume. (`APPCOMMAND_VOLUME_UP`, `KEYCODE_VOLUME_UP`) AudioVolumeUp, /// Toggle between muted state and prior volume level. (`APPCOMMAND_VOLUME_MUTE`, /// `KEYCODE_VOLUME_MUTE`) AudioVolumeMute, /// Toggle the microphone on/off. (`APPCOMMAND_MIC_ON_OFF_TOGGLE`) MicrophoneToggle, /// Decrease microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_DOWN`) MicrophoneVolumeDown, /// Increase microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_UP`) MicrophoneVolumeUp, /// Mute the microphone. (`APPCOMMAND_MICROPHONE_VOLUME_MUTE`, `KEYCODE_MUTE`) MicrophoneVolumeMute, /// Show correction list when a word is incorrectly identified. (`APPCOMMAND_CORRECTION_LIST`) SpeechCorrectionList, /// Toggle between dictation mode and command/control mode. /// (`APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE`) SpeechInputToggle, /// The first generic "LaunchApplication" key. This is commonly associated with launching "My /// Computer", and may have a computer symbol on the key. (`APPCOMMAND_LAUNCH_APP1`) LaunchApplication1, /// The second generic "LaunchApplication" key. This is commonly associated with launching /// "Calculator", and may have a calculator symbol on the key. (`APPCOMMAND_LAUNCH_APP2`, /// `KEYCODE_CALCULATOR`) LaunchApplication2, /// The "Calendar" key. (`KEYCODE_CALENDAR`) LaunchCalendar, /// The "Contacts" key. (`KEYCODE_CONTACTS`) LaunchContacts, /// The "Mail" key. (`APPCOMMAND_LAUNCH_MAIL`) LaunchMail, /// The "Media Player" key. (`APPCOMMAND_LAUNCH_MEDIA_SELECT`) LaunchMediaPlayer, LaunchMusicPlayer, LaunchPhone, LaunchScreenSaver, LaunchSpreadsheet, LaunchWebBrowser, LaunchWebCam, LaunchWordProcessor, /// Navigate to previous content or page in current history. (`APPCOMMAND_BROWSER_BACKWARD`) BrowserBack, /// Open the list of browser favorites. (`APPCOMMAND_BROWSER_FAVORITES`) BrowserFavorites, /// Navigate to next content or page in current history. (`APPCOMMAND_BROWSER_FORWARD`) BrowserForward, /// Go to the user’s preferred home page. (`APPCOMMAND_BROWSER_HOME`) BrowserHome, /// Refresh the current page or content. (`APPCOMMAND_BROWSER_REFRESH`) BrowserRefresh, /// Call up the user’s preferred search page. (`APPCOMMAND_BROWSER_SEARCH`) BrowserSearch, /// Stop loading the current page or content. (`APPCOMMAND_BROWSER_STOP`) BrowserStop, /// The Application switch key, which provides a list of recent apps to switch between. /// (`KEYCODE_APP_SWITCH`) AppSwitch, /// The Call key. (`KEYCODE_CALL`) Call, /// The Camera key. (`KEYCODE_CAMERA`) Camera, /// The Camera focus key. (`KEYCODE_FOCUS`) CameraFocus, /// The End Call key. (`KEYCODE_ENDCALL`) EndCall, /// The Back key. (`KEYCODE_BACK`) GoBack, /// The Home key, which goes to the phone’s main screen. (`KEYCODE_HOME`) GoHome, /// The Headset Hook key. (`KEYCODE_HEADSETHOOK`) HeadsetHook, LastNumberRedial, /// The Notification key. (`KEYCODE_NOTIFICATION`) Notification, /// Toggle between manner mode state: silent, vibrate, ring, ... (`KEYCODE_MANNER_MODE`) MannerMode, VoiceDial, /// Switch to viewing TV. (`KEYCODE_TV`) TV, /// TV 3D Mode. (`KEYCODE_3D_MODE`) TV3DMode, /// Toggle between antenna and cable input. (`KEYCODE_TV_ANTENNA_CABLE`) TVAntennaCable, /// Audio description. (`KEYCODE_TV_AUDIO_DESCRIPTION`) TVAudioDescription, /// Audio description mixing volume down. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN`) TVAudioDescriptionMixDown, /// Audio description mixing volume up. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP`) TVAudioDescriptionMixUp, /// Contents menu. (`KEYCODE_TV_CONTENTS_MENU`) TVContentsMenu, /// Contents menu. (`KEYCODE_TV_DATA_SERVICE`) TVDataService, /// Switch the input mode on an external TV. (`KEYCODE_TV_INPUT`) TVInput, /// Switch to component input #1. (`KEYCODE_TV_INPUT_COMPONENT_1`) TVInputComponent1, /// Switch to component input #2. (`KEYCODE_TV_INPUT_COMPONENT_2`) TVInputComponent2, /// Switch to composite input #1. (`KEYCODE_TV_INPUT_COMPOSITE_1`) TVInputComposite1, /// Switch to composite input #2. (`KEYCODE_TV_INPUT_COMPOSITE_2`) TVInputComposite2, /// Switch to HDMI input #1. (`KEYCODE_TV_INPUT_HDMI_1`) TVInputHDMI1, /// Switch to HDMI input #2. (`KEYCODE_TV_INPUT_HDMI_2`) TVInputHDMI2, /// Switch to HDMI input #3. (`KEYCODE_TV_INPUT_HDMI_3`) TVInputHDMI3, /// Switch to HDMI input #4. (`KEYCODE_TV_INPUT_HDMI_4`) TVInputHDMI4, /// Switch to VGA input #1. (`KEYCODE_TV_INPUT_VGA_1`) TVInputVGA1, /// Media context menu. (`KEYCODE_TV_MEDIA_CONTEXT_MENU`) TVMediaContext, /// Toggle network. (`KEYCODE_TV_NETWORK`) TVNetwork, /// Number entry. (`KEYCODE_TV_NUMBER_ENTRY`) TVNumberEntry, /// Toggle the power on an external TV. (`KEYCODE_TV_POWER`) TVPower, /// Radio. (`KEYCODE_TV_RADIO_SERVICE`) TVRadioService, /// Satellite. (`KEYCODE_TV_SATELLITE`) TVSatellite, /// Broadcast Satellite. (`KEYCODE_TV_SATELLITE_BS`) TVSatelliteBS, /// Communication Satellite. (`KEYCODE_TV_SATELLITE_CS`) TVSatelliteCS, /// Toggle between available satellites. (`KEYCODE_TV_SATELLITE_SERVICE`) TVSatelliteToggle, /// Analog Terrestrial. (`KEYCODE_TV_TERRESTRIAL_ANALOG`) TVTerrestrialAnalog, /// Digital Terrestrial. (`KEYCODE_TV_TERRESTRIAL_DIGITAL`) TVTerrestrialDigital, /// Timer programming. (`KEYCODE_TV_TIMER_PROGRAMMING`) TVTimer, /// Switch the input mode on an external AVR (audio/video receiver). (`KEYCODE_AVR_INPUT`) AVRInput, /// Toggle the power on an external AVR (audio/video receiver). (`KEYCODE_AVR_POWER`) AVRPower, /// General purpose color-coded media function key, as index 0 (red). (`VK_COLORED_KEY_0`, /// `KEYCODE_PROG_RED`) ColorF0Red, /// General purpose color-coded media function key, as index 1 (green). (`VK_COLORED_KEY_1`, /// `KEYCODE_PROG_GREEN`) ColorF1Green, /// General purpose color-coded media function key, as index 2 (yellow). (`VK_COLORED_KEY_2`, /// `KEYCODE_PROG_YELLOW`) ColorF2Yellow, /// General purpose color-coded media function key, as index 3 (blue). (`VK_COLORED_KEY_3`, /// `KEYCODE_PROG_BLUE`) ColorF3Blue, /// General purpose color-coded media function key, as index 4 (grey). (`VK_COLORED_KEY_4`) ColorF4Grey, /// General purpose color-coded media function key, as index 5 (brown). (`VK_COLORED_KEY_5`) ColorF5Brown, /// Toggle the display of Closed Captions. (`VK_CC`, `KEYCODE_CAPTIONS`) ClosedCaptionToggle, /// Adjust brightness of device, by toggling between or cycling through states. (`VK_DIMMER`) Dimmer, /// Swap video sources. (`VK_DISPLAY_SWAP`) DisplaySwap, /// Select Digital Video Rrecorder. (`KEYCODE_DVR`) DVR, /// Exit the current application. (`VK_EXIT`) Exit, /// Clear program or content stored as favorite 0. (`VK_CLEAR_FAVORITE_0`) FavoriteClear0, /// Clear program or content stored as favorite 1. (`VK_CLEAR_FAVORITE_1`) FavoriteClear1, /// Clear program or content stored as favorite 2. (`VK_CLEAR_FAVORITE_2`) FavoriteClear2, /// Clear program or content stored as favorite 3. (`VK_CLEAR_FAVORITE_3`) FavoriteClear3, /// Select (recall) program or content stored as favorite 0. (`VK_RECALL_FAVORITE_0`) FavoriteRecall0, /// Select (recall) program or content stored as favorite 1. (`VK_RECALL_FAVORITE_1`) FavoriteRecall1, /// Select (recall) program or content stored as favorite 2. (`VK_RECALL_FAVORITE_2`) FavoriteRecall2, /// Select (recall) program or content stored as favorite 3. (`VK_RECALL_FAVORITE_3`) FavoriteRecall3, /// Store current program or content as favorite 0. (`VK_STORE_FAVORITE_0`) FavoriteStore0, /// Store current program or content as favorite 1. (`VK_STORE_FAVORITE_1`) FavoriteStore1, /// Store current program or content as favorite 2. (`VK_STORE_FAVORITE_2`) FavoriteStore2, /// Store current program or content as favorite 3. (`VK_STORE_FAVORITE_3`) FavoriteStore3, /// Toggle display of program or content guide. (`VK_GUIDE`, `KEYCODE_GUIDE`) Guide, /// If guide is active and displayed, then display next day’s content. (`VK_NEXT_DAY`) GuideNextDay, /// If guide is active and displayed, then display previous day’s content. (`VK_PREV_DAY`) GuidePreviousDay, /// Toggle display of information about currently selected context or media. (`VK_INFO`, /// `KEYCODE_INFO`) Info, /// Toggle instant replay. (`VK_INSTANT_REPLAY`) InstantReplay, /// Launch linked content, if available and appropriate. (`VK_LINK`) Link, /// List the current program. (`VK_LIST`) ListProgram, /// Toggle display listing of currently available live content or programs. (`VK_LIVE`) LiveContent, /// Lock or unlock current content or program. (`VK_LOCK`) Lock, /// Show a list of media applications: audio/video players and image viewers. (`VK_APPS`) /// /// Note: Do not confuse this key value with the Windows' `VK_APPS` / `VK_CONTEXT_MENU` key, /// which is encoded as `"ContextMenu"`. MediaApps, /// Audio track key. (`KEYCODE_MEDIA_AUDIO_TRACK`) MediaAudioTrack, /// Select previously selected channel or media. (`VK_LAST`, `KEYCODE_LAST_CHANNEL`) MediaLast, /// Skip backward to next content or program. (`KEYCODE_MEDIA_SKIP_BACKWARD`) MediaSkipBackward, /// Skip forward to next content or program. (`VK_SKIP`, `KEYCODE_MEDIA_SKIP_FORWARD`) MediaSkipForward, /// Step backward to next content or program. (`KEYCODE_MEDIA_STEP_BACKWARD`) MediaStepBackward, /// Step forward to next content or program. (`KEYCODE_MEDIA_STEP_FORWARD`) MediaStepForward, /// Media top menu. (`KEYCODE_MEDIA_TOP_MENU`) MediaTopMenu, /// Navigate in. (`KEYCODE_NAVIGATE_IN`) NavigateIn, /// Navigate to next key. (`KEYCODE_NAVIGATE_NEXT`) NavigateNext, /// Navigate out. (`KEYCODE_NAVIGATE_OUT`) NavigateOut, /// Navigate to previous key. (`KEYCODE_NAVIGATE_PREVIOUS`) NavigatePrevious, /// Cycle to next favorite channel (in favorites list). (`VK_NEXT_FAVORITE_CHANNEL`) NextFavoriteChannel, /// Cycle to next user profile (if there are multiple user profiles). (`VK_USER`) NextUserProfile, /// Access on-demand content or programs. (`VK_ON_DEMAND`) OnDemand, /// Pairing key to pair devices. (`KEYCODE_PAIRING`) Pairing, /// Move picture-in-picture window down. (`VK_PINP_DOWN`) PinPDown, /// Move picture-in-picture window. (`VK_PINP_MOVE`) PinPMove, /// Toggle display of picture-in-picture window. (`VK_PINP_TOGGLE`) PinPToggle, /// Move picture-in-picture window up. (`VK_PINP_UP`) PinPUp, /// Decrease media playback speed. (`VK_PLAY_SPEED_DOWN`) PlaySpeedDown, /// Reset playback to normal speed. (`VK_PLAY_SPEED_RESET`) PlaySpeedReset, /// Increase media playback speed. (`VK_PLAY_SPEED_UP`) PlaySpeedUp, /// Toggle random media or content shuffle mode. (`VK_RANDOM_TOGGLE`) RandomToggle, /// Not a physical key, but this key code is sent when the remote control battery is low. /// (`VK_RC_LOW_BATTERY`) RcLowBattery, /// Toggle or cycle between media recording speeds. (`VK_RECORD_SPEED_NEXT`) RecordSpeedNext, /// Toggle RF (radio frequency) input bypass mode (pass RF input directly to the RF output). /// (`VK_RF_BYPASS`) RfBypass, /// Toggle scan channels mode. (`VK_SCAN_CHANNELS_TOGGLE`) ScanChannelsToggle, /// Advance display screen mode to next available mode. (`VK_SCREEN_MODE_NEXT`) ScreenModeNext, /// Toggle display of device settings screen. (`VK_SETTINGS`, `KEYCODE_SETTINGS`) Settings, /// Toggle split screen mode. (`VK_SPLIT_SCREEN_TOGGLE`) SplitScreenToggle, /// Switch the input mode on an external STB (set top box). (`KEYCODE_STB_INPUT`) STBInput, /// Toggle the power on an external STB (set top box). (`KEYCODE_STB_POWER`) STBPower, /// Toggle display of subtitles, if available. (`VK_SUBTITLE`) Subtitle, /// Toggle display of teletext, if available (`VK_TELETEXT`, `KEYCODE_TV_TELETEXT`). Teletext, /// Advance video mode to next available mode. (`VK_VIDEO_MODE_NEXT`) VideoModeNext, /// Cause device to identify itself in some manner, e.g., audibly or visibly. (`VK_WINK`) Wink, /// Toggle between full-screen and scaled content, or alter magnification level. (`VK_ZOOM`, /// `KEYCODE_TV_ZOOM_MODE`) ZoomToggle, /// General-purpose function key. /// Usually found at the top of the keyboard. F1, /// General-purpose function key. /// Usually found at the top of the keyboard. F2, /// General-purpose function key. /// Usually found at the top of the keyboard. F3, /// General-purpose function key. /// Usually found at the top of the keyboard. F4, /// General-purpose function key. /// Usually found at the top of the keyboard. F5, /// General-purpose function key. /// Usually found at the top of the keyboard. F6, /// General-purpose function key. /// Usually found at the top of the keyboard. F7, /// General-purpose function key. /// Usually found at the top of the keyboard. F8, /// General-purpose function key. /// Usually found at the top of the keyboard. F9, /// General-purpose function key. /// Usually found at the top of the keyboard. F10, /// General-purpose function key. /// Usually found at the top of the keyboard. F11, /// General-purpose function key. /// Usually found at the top of the keyboard. F12, /// General-purpose function key. /// Usually found at the top of the keyboard. F13, /// General-purpose function key. /// Usually found at the top of the keyboard. F14, /// General-purpose function key. /// Usually found at the top of the keyboard. F15, /// General-purpose function key. /// Usually found at the top of the keyboard. F16, /// General-purpose function key. /// Usually found at the top of the keyboard. F17, /// General-purpose function key. /// Usually found at the top of the keyboard. F18, /// General-purpose function key. /// Usually found at the top of the keyboard. F19, /// General-purpose function key. /// Usually found at the top of the keyboard. F20, /// General-purpose function key. /// Usually found at the top of the keyboard. F21, /// General-purpose function key. /// Usually found at the top of the keyboard. F22, /// General-purpose function key. /// Usually found at the top of the keyboard. F23, /// General-purpose function key. /// Usually found at the top of the keyboard. F24, /// General-purpose function key. F25,
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/keyboard/modifiers.rs
core/src/keyboard/modifiers.rs
use bitflags::bitflags; bitflags! { /// The current state of the keyboard modifiers. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Modifiers: u32{ /// The "shift" key. const SHIFT = 0b100; // const LSHIFT = 0b010 << 0; // const RSHIFT = 0b001 << 0; // /// The "control" key. const CTRL = 0b100 << 3; // const LCTRL = 0b010 << 3; // const RCTRL = 0b001 << 3; // /// The "alt" key. const ALT = 0b100 << 6; // const LALT = 0b010 << 6; // const RALT = 0b001 << 6; // /// The "windows" key on Windows, "command" key on Mac, and /// "super" key on Linux. const LOGO = 0b100 << 9; // const LLOGO = 0b010 << 9; // const RLOGO = 0b001 << 9; /// No modifiers const NONE = 0; } } impl Modifiers { /// The "command" key. /// /// This is normally the main modifier to be used for hotkeys. /// /// On macOS, this is equivalent to `Self::LOGO`. /// Otherwise, this is equivalent to `Self::CTRL`. pub const COMMAND: Self = if cfg!(target_os = "macos") { Self::LOGO } else { Self::CTRL }; /// Returns true if the [`SHIFT`] key is pressed in the [`Modifiers`]. /// /// [`SHIFT`]: Self::SHIFT pub fn shift(self) -> bool { self.contains(Self::SHIFT) } /// Returns true if the [`CTRL`] key is pressed in the [`Modifiers`]. /// /// [`CTRL`]: Self::CTRL pub fn control(self) -> bool { self.contains(Self::CTRL) } /// Returns true if the [`ALT`] key is pressed in the [`Modifiers`]. /// /// [`ALT`]: Self::ALT pub fn alt(self) -> bool { self.contains(Self::ALT) } /// Returns true if the [`LOGO`] key is pressed in the [`Modifiers`]. /// /// [`LOGO`]: Self::LOGO pub fn logo(self) -> bool { self.contains(Self::LOGO) } /// Returns true if a "command key" is pressed in the [`Modifiers`]. /// /// The "command key" is the main modifier key used to issue commands in the /// current platform. Specifically: /// /// - It is the `logo` or command key (⌘) on macOS /// - It is the `control` key on other platforms pub fn command(self) -> bool { #[cfg(target_os = "macos")] let is_pressed = self.logo(); #[cfg(not(target_os = "macos"))] let is_pressed = self.control(); is_pressed } /// Returns true if the "jump key" is pressed in the [`Modifiers`]. /// /// The "jump key" is the modifier key used to widen text motions. It is the `Alt` /// key in macOS and the `Ctrl` key in other platforms. pub fn jump(self) -> bool { if cfg!(target_os = "macos") { self.alt() } else { self.control() } } /// Returns true if the "command key" is pressed on a macOS device. /// /// This is relevant for macOS-specific actions (e.g. `⌘ + ArrowLeft` moves the cursor /// to the beginning of the line). pub fn macos_command(self) -> bool { if cfg!(target_os = "macos") { self.logo() } else { false } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/keyboard/location.rs
core/src/keyboard/location.rs
/// The location of a key on the keyboard. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Location { /// The standard group of keys on the keyboard. Standard, /// The left side of the keyboard. Left, /// The right side of the keyboard. Right, /// The numpad of the keyboard. Numpad, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/id.rs
core/src/widget/id.rs
use std::borrow; use std::sync::atomic::{self, AtomicUsize}; static NEXT_ID: AtomicUsize = AtomicUsize::new(0); /// The identifier of a generic widget. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Id(Internal); impl Id { /// Creates a new [`Id`] from a static `str`. pub const fn new(id: &'static str) -> Self { Self(Internal::Custom(borrow::Cow::Borrowed(id))) } /// Creates a unique [`Id`]. /// /// This function produces a different [`Id`] every time it is called. pub fn unique() -> Self { let id = NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed); Self(Internal::Unique(id)) } } impl From<&'static str> for Id { fn from(value: &'static str) -> Self { Self::new(value) } } impl From<String> for Id { fn from(value: String) -> Self { Self(Internal::Custom(borrow::Cow::Owned(value))) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Internal { Unique(usize), Custom(borrow::Cow<'static, str>), } #[cfg(test)] mod tests { use super::Id; #[test] fn unique_generates_different_ids() { let a = Id::unique(); let b = Id::unique(); assert_ne!(a, b); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/tree.rs
core/src/widget/tree.rs
//! Store internal widget state in a state tree to ensure continuity. use crate::Widget; use std::any::{self, Any}; use std::borrow::Borrow; use std::fmt; /// A persistent state widget tree. /// /// A [`Tree`] is normally associated with a specific widget in the widget tree. #[derive(Debug)] pub struct Tree { /// The tag of the [`Tree`]. pub tag: Tag, /// The [`State`] of the [`Tree`]. pub state: State, /// The children of the root widget of the [`Tree`]. pub children: Vec<Tree>, } impl Tree { /// Creates an empty, stateless [`Tree`] with no children. pub fn empty() -> Self { Self { tag: Tag::stateless(), state: State::None, children: Vec::new(), } } /// Creates a new [`Tree`] for the provided [`Widget`]. pub fn new<'a, Message, Theme, Renderer>( widget: impl Borrow<dyn Widget<Message, Theme, Renderer> + 'a>, ) -> Self where Renderer: crate::Renderer, { let widget = widget.borrow(); Self { tag: widget.tag(), state: widget.state(), children: widget.children(), } } /// Reconciles the current tree with the provided [`Widget`]. /// /// If the tag of the [`Widget`] matches the tag of the [`Tree`], then the /// [`Widget`] proceeds with the reconciliation (i.e. [`Widget::diff`] is called). /// /// Otherwise, the whole [`Tree`] is recreated. /// /// [`Widget::diff`]: crate::Widget::diff pub fn diff<'a, Message, Theme, Renderer>( &mut self, new: impl Borrow<dyn Widget<Message, Theme, Renderer> + 'a>, ) where Renderer: crate::Renderer, { if self.tag == new.borrow().tag() { new.borrow().diff(self); } else { *self = Self::new(new); } } /// Reconciles the children of the tree with the provided list of widgets. pub fn diff_children<'a, Message, Theme, Renderer>( &mut self, new_children: &[impl Borrow<dyn Widget<Message, Theme, Renderer> + 'a>], ) where Renderer: crate::Renderer, { self.diff_children_custom( new_children, |tree, widget| tree.diff(widget.borrow()), |widget| Self::new(widget.borrow()), ); } /// Reconciles the children of the tree with the provided list of widgets using custom /// logic both for diffing and creating new widget state. pub fn diff_children_custom<T>( &mut self, new_children: &[T], diff: impl Fn(&mut Tree, &T), new_state: impl Fn(&T) -> Self, ) { if self.children.len() > new_children.len() { self.children.truncate(new_children.len()); } for (child_state, new) in self.children.iter_mut().zip(new_children.iter()) { diff(child_state, new); } if self.children.len() < new_children.len() { self.children .extend(new_children[self.children.len()..].iter().map(new_state)); } } } /// Reconciles the `current_children` with the provided list of widgets using /// custom logic both for diffing and creating new widget state. /// /// The algorithm will try to minimize the impact of diffing by querying the /// `maybe_changed` closure. pub fn diff_children_custom_with_search<T>( current_children: &mut Vec<Tree>, new_children: &[T], diff: impl Fn(&mut Tree, &T), maybe_changed: impl Fn(usize) -> bool, new_state: impl Fn(&T) -> Tree, ) { if new_children.is_empty() { current_children.clear(); return; } if current_children.is_empty() { current_children.extend(new_children.iter().map(new_state)); return; } let first_maybe_changed = maybe_changed(0); let last_maybe_changed = maybe_changed(current_children.len() - 1); if current_children.len() > new_children.len() { if !first_maybe_changed && last_maybe_changed { current_children.truncate(new_children.len()); } else { let difference_index = if first_maybe_changed { 0 } else { (1..current_children.len()) .find(|&i| maybe_changed(i)) .unwrap_or(0) }; let _ = current_children.splice( difference_index..difference_index + (current_children.len() - new_children.len()), std::iter::empty(), ); } } if current_children.len() < new_children.len() { let first_maybe_changed = maybe_changed(0); let last_maybe_changed = maybe_changed(current_children.len() - 1); if !first_maybe_changed && last_maybe_changed { current_children.extend(new_children[current_children.len()..].iter().map(new_state)); } else { let difference_index = if first_maybe_changed { 0 } else { (1..current_children.len()) .find(|&i| maybe_changed(i)) .unwrap_or(0) }; let _ = current_children.splice( difference_index..difference_index, new_children[difference_index ..difference_index + (new_children.len() - current_children.len())] .iter() .map(new_state), ); } } // TODO: Merge loop with extend logic (?) for (child_state, new) in current_children.iter_mut().zip(new_children.iter()) { diff(child_state, new); } } /// The identifier of some widget state. #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct Tag(any::TypeId); impl Tag { /// Creates a [`Tag`] for a state of type `T`. pub fn of<T>() -> Self where T: 'static, { Self(any::TypeId::of::<T>()) } /// Creates a [`Tag`] for a stateless widget. pub fn stateless() -> Self { Self::of::<()>() } } /// The internal [`State`] of a widget. pub enum State { /// No meaningful internal state. None, /// Some meaningful internal state. Some(Box<dyn Any>), } impl State { /// Creates a new [`State`]. pub fn new<T>(state: T) -> Self where T: 'static, { State::Some(Box::new(state)) } /// Downcasts the [`State`] to `T` and returns a reference to it. /// /// # Panics /// This method will panic if the downcast fails or the [`State`] is [`State::None`]. pub fn downcast_ref<T>(&self) -> &T where T: 'static, { match self { State::None => panic!("Downcast on stateless state"), State::Some(state) => state.downcast_ref().expect("Downcast widget state"), } } /// Downcasts the [`State`] to `T` and returns a mutable reference to it. /// /// # Panics /// This method will panic if the downcast fails or the [`State`] is [`State::None`]. pub fn downcast_mut<T>(&mut self) -> &mut T where T: 'static, { match self { State::None => panic!("Downcast on stateless state"), State::Some(state) => state.downcast_mut().expect("Downcast widget state"), } } } impl fmt::Debug for State { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None => write!(f, "State::None"), Self::Some(_) => write!(f, "State::Some"), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/text.rs
core/src/widget/text.rs
//! Text widgets display information through writing. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub fn text<T>(t: T) -> iced_core::widget::Text<'static, iced_core::Theme, ()> { unimplemented!() } } //! # pub use iced_core::color; } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_core::Element<'a, Message, iced_core::Theme, ()>; //! use iced::widget::text; //! use iced::color; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! text("Hello, this is iced!") //! .size(20) //! .color(color!(0x0000ff)) //! .into() //! } //! ``` use crate::alignment; use crate::layout; use crate::mouse; use crate::renderer; use crate::text; use crate::text::paragraph::{self, Paragraph}; use crate::widget::tree::{self, Tree}; use crate::{Color, Element, Layout, Length, Pixels, Rectangle, Size, Theme, Widget}; pub use text::{Alignment, LineHeight, Shaping, Wrapping}; /// A bunch of text. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub fn text<T>(t: T) -> iced_core::widget::Text<'static, iced_core::Theme, ()> { unimplemented!() } } /// # pub use iced_core::color; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_core::Element<'a, Message, iced_core::Theme, ()>; /// use iced::widget::text; /// use iced::color; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// text("Hello, this is iced!") /// .size(20) /// .color(color!(0x0000ff)) /// .into() /// } /// ``` pub struct Text<'a, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { fragment: text::Fragment<'a>, format: Format<Renderer::Font>, class: Theme::Class<'a>, } impl<'a, Theme, Renderer> Text<'a, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { /// Create a new fragment of [`Text`] with the given contents. pub fn new(fragment: impl text::IntoFragment<'a>) -> Self { Text { fragment: fragment.into_fragment(), format: Format::default(), class: Theme::default(), } } /// Sets the size of the [`Text`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.format.size = Some(size.into()); self } /// Sets the [`LineHeight`] of the [`Text`]. pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self { self.format.line_height = line_height.into(); self } /// Sets the [`Font`] of the [`Text`]. /// /// [`Font`]: crate::text::Renderer::Font pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.format.font = Some(font.into()); self } /// Sets the [`Font`] of the [`Text`], if `Some`. /// /// [`Font`]: crate::text::Renderer::Font pub fn font_maybe(mut self, font: Option<impl Into<Renderer::Font>>) -> Self { self.format.font = font.map(Into::into); self } /// Sets the width of the [`Text`] boundaries. pub fn width(mut self, width: impl Into<Length>) -> Self { self.format.width = width.into(); self } /// Sets the height of the [`Text`] boundaries. pub fn height(mut self, height: impl Into<Length>) -> Self { self.format.height = height.into(); self } /// Centers the [`Text`], both horizontally and vertically. pub fn center(self) -> Self { self.align_x(alignment::Horizontal::Center) .align_y(alignment::Vertical::Center) } /// Sets the [`alignment::Horizontal`] of the [`Text`]. pub fn align_x(mut self, alignment: impl Into<text::Alignment>) -> Self { self.format.align_x = alignment.into(); self } /// Sets the [`alignment::Vertical`] of the [`Text`]. pub fn align_y(mut self, alignment: impl Into<alignment::Vertical>) -> Self { self.format.align_y = alignment.into(); self } /// Sets the [`Shaping`] strategy of the [`Text`]. pub fn shaping(mut self, shaping: Shaping) -> Self { self.format.shaping = shaping; self } /// Sets the [`Wrapping`] strategy of the [`Text`]. pub fn wrapping(mut self, wrapping: Wrapping) -> Self { self.format.wrapping = wrapping; self } /// Sets the style of the [`Text`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the [`Color`] of the [`Text`]. pub fn color(self, color: impl Into<Color>) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.color_maybe(Some(color)) } /// Sets the [`Color`] of the [`Text`], if `Some`. pub fn color_maybe(self, color: Option<impl Into<Color>>) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { let color = color.map(Into::into); self.style(move |_theme| Style { color }) } /// Sets the style class of the [`Text`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } /// The internal state of a [`Text`] widget. pub type State<P> = paragraph::Plain<P>; impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Text<'_, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(paragraph::Plain::<Renderer::Paragraph>::default()) } fn size(&self) -> Size<Length> { Size { width: self.format.width, height: self.format.height, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { layout( tree.state.downcast_mut::<State<Renderer::Paragraph>>(), renderer, limits, &self.fragment, self.format, ) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, _cursor_position: mouse::Cursor, viewport: &Rectangle, ) { let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>(); let style = theme.style(&self.class); draw( renderer, defaults, layout.bounds(), state.raw(), style, viewport, ); } fn operate( &mut self, _tree: &mut Tree, layout: Layout<'_>, _renderer: &Renderer, operation: &mut dyn super::Operation, ) { operation.text(None, layout.bounds(), &self.fragment); } } /// The format of some [`Text`]. /// /// Check out the methods of the [`Text`] widget /// to learn more about each field. #[derive(Debug, Clone, Copy)] #[allow(missing_docs)] pub struct Format<Font> { pub width: Length, pub height: Length, pub size: Option<Pixels>, pub font: Option<Font>, pub line_height: LineHeight, pub align_x: text::Alignment, pub align_y: alignment::Vertical, pub shaping: Shaping, pub wrapping: Wrapping, } impl<Font> Default for Format<Font> { fn default() -> Self { Self { size: None, line_height: LineHeight::default(), font: None, width: Length::Shrink, height: Length::Shrink, align_x: text::Alignment::Default, align_y: alignment::Vertical::Top, shaping: Shaping::default(), wrapping: Wrapping::default(), } } } /// Produces the [`layout::Node`] of a [`Text`] widget. pub fn layout<Renderer>( paragraph: &mut paragraph::Plain<Renderer::Paragraph>, renderer: &Renderer, limits: &layout::Limits, content: &str, format: Format<Renderer::Font>, ) -> layout::Node where Renderer: text::Renderer, { layout::sized(limits, format.width, format.height, |limits| { let bounds = limits.max(); let size = format.size.unwrap_or_else(|| renderer.default_size()); let font = format.font.unwrap_or_else(|| renderer.default_font()); let _ = paragraph.update(text::Text { content, bounds, size, line_height: format.line_height, font, align_x: format.align_x, align_y: format.align_y, shaping: format.shaping, wrapping: format.wrapping, hint_factor: renderer.scale_factor(), }); paragraph.min_bounds() }) } /// Draws text using the same logic as the [`Text`] widget. pub fn draw<Renderer>( renderer: &mut Renderer, style: &renderer::Style, bounds: Rectangle, paragraph: &Renderer::Paragraph, appearance: Style, viewport: &Rectangle, ) where Renderer: text::Renderer, { let anchor = bounds.anchor( paragraph.min_bounds(), paragraph.align_x(), paragraph.align_y(), ); renderer.fill_paragraph( paragraph, anchor, appearance.color.unwrap_or(style.text_color), *viewport, ); } impl<'a, Message, Theme, Renderer> From<Text<'a, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn from(text: Text<'a, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> { Element::new(text) } } impl<'a, Theme, Renderer> From<&'a str> for Text<'a, Theme, Renderer> where Theme: Catalog + 'a, Renderer: text::Renderer, { fn from(content: &'a str) -> Self { Self::new(content) } } impl<'a, Message, Theme, Renderer> From<&'a str> for Element<'a, Message, Theme, Renderer> where Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn from(content: &'a str) -> Self { Text::from(content).into() } } /// The appearance of some text. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Style { /// The [`Color`] of the text. /// /// The default, `None`, means using the inherited color. pub color: Option<Color>, } /// The theme catalog of a [`Text`]. pub trait Catalog: Sized { /// The item class of this [`Catalog`]. type Class<'a>; /// The default class produced by this [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, item: &Self::Class<'_>) -> Style; } /// A styling function for a [`Text`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(|_theme| Style::default()) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The default text styling; color is inherited. pub fn default(_theme: &Theme) -> Style { Style { color: None } } /// Text with the default base color. pub fn base(theme: &Theme) -> Style { Style { color: Some(theme.palette().text), } } /// Text conveying some important information, like an action. pub fn primary(theme: &Theme) -> Style { Style { color: Some(theme.palette().primary), } } /// Text conveying some secondary information, like a footnote. pub fn secondary(theme: &Theme) -> Style { Style { color: Some(theme.extended_palette().secondary.base.color), } } /// Text conveying some positive information, like a successful event. pub fn success(theme: &Theme) -> Style { Style { color: Some(theme.palette().success), } } /// Text conveying some mildly negative information, like a warning. pub fn warning(theme: &Theme) -> Style { Style { color: Some(theme.palette().warning), } } /// Text conveying some negative information, like an error. pub fn danger(theme: &Theme) -> Style { Style { color: Some(theme.palette().danger), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/operation.rs
core/src/widget/operation.rs
//! Query or update internal widget state. pub mod focusable; pub mod scrollable; pub mod text_input; pub use focusable::Focusable; pub use scrollable::Scrollable; pub use text_input::TextInput; use crate::widget::Id; use crate::{Rectangle, Vector}; use std::any::Any; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; /// A piece of logic that can traverse the widget tree of an application in /// order to query or update some widget state. pub trait Operation<T = ()>: Send { /// Requests further traversal of the widget tree to keep operating. /// /// The provided `operate` closure may be called by an [`Operation`] /// to return control to the widget tree and keep traversing it. If /// the closure is not called, the children of the widget asking for /// traversal will be skipped. fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)); /// Operates on a widget that contains other widgets. fn container(&mut self, _id: Option<&Id>, _bounds: Rectangle) {} /// Operates on a widget that can be scrolled. fn scrollable( &mut self, _id: Option<&Id>, _bounds: Rectangle, _content_bounds: Rectangle, _translation: Vector, _state: &mut dyn Scrollable, ) { } /// Operates on a widget that can be focused. fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn Focusable) {} /// Operates on a widget that has text input. fn text_input(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn TextInput) {} /// Operates on a widget that contains some text. fn text(&mut self, _id: Option<&Id>, _bounds: Rectangle, _text: &str) {} /// Operates on a custom widget with some state. fn custom(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn Any) {} /// Finishes the [`Operation`] and returns its [`Outcome`]. fn finish(&self) -> Outcome<T> { Outcome::None } } impl<T, O> Operation<O> for Box<T> where T: Operation<O> + ?Sized, { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<O>)) { self.as_mut().traverse(operate); } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { self.as_mut().container(id, bounds); } fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.as_mut().focusable(id, bounds, state); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: Vector, state: &mut dyn Scrollable, ) { self.as_mut() .scrollable(id, bounds, content_bounds, translation, state); } fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.as_mut().text_input(id, bounds, state); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.as_mut().text(id, bounds, text); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.as_mut().custom(id, bounds, state); } fn finish(&self) -> Outcome<O> { self.as_ref().finish() } } /// The result of an [`Operation`]. pub enum Outcome<T> { /// The [`Operation`] produced no result. None, /// The [`Operation`] produced some result. Some(T), /// The [`Operation`] needs to be followed by another [`Operation`]. Chain(Box<dyn Operation<T>>), } impl<T> fmt::Debug for Outcome<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None => write!(f, "Outcome::None"), Self::Some(output) => write!(f, "Outcome::Some({output:?})"), Self::Chain(_) => write!(f, "Outcome::Chain(...)"), } } } /// Wraps the [`Operation`] in a black box, erasing its returning type. pub fn black_box<'a, T, O>(operation: &'a mut dyn Operation<T>) -> impl Operation<O> + 'a where T: 'a, { struct BlackBox<'a, T> { operation: &'a mut dyn Operation<T>, } impl<T, O> Operation<O> for BlackBox<'_, T> { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<O>)) where Self: Sized, { self.operation.traverse(&mut |operation| { operate(&mut BlackBox { operation }); }); } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { self.operation.container(id, bounds); } fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: Vector, state: &mut dyn Scrollable, ) { self.operation .scrollable(id, bounds, content_bounds, translation, state); } fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.operation.text(id, bounds, text); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } fn finish(&self) -> Outcome<O> { Outcome::None } } BlackBox { operation } } /// Maps the output of an [`Operation`] using the given function. pub fn map<A, B>( operation: impl Operation<A>, f: impl Fn(A) -> B + Send + Sync + 'static, ) -> impl Operation<B> where A: 'static, B: 'static, { struct Map<O, A, B> { operation: O, f: Arc<dyn Fn(A) -> B + Send + Sync>, } impl<O, A, B> Operation<B> for Map<O, A, B> where O: Operation<A>, A: 'static, B: 'static, { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<B>)) { struct MapRef<'a, A> { operation: &'a mut dyn Operation<A>, } impl<A, B> Operation<B> for MapRef<'_, A> { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<B>)) { self.operation.traverse(&mut |operation| { operate(&mut MapRef { operation }); }); } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { let Self { operation, .. } = self; operation.container(id, bounds); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: Vector, state: &mut dyn Scrollable, ) { self.operation .scrollable(id, bounds, content_bounds, translation, state); } fn focusable( &mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable, ) { self.operation.focusable(id, bounds, state); } fn text_input( &mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput, ) { self.operation.text_input(id, bounds, state); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.operation.text(id, bounds, text); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } } self.operation.traverse(&mut |operation| { operate(&mut MapRef { operation }); }); } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { self.operation.container(id, bounds); } fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: Vector, state: &mut dyn Scrollable, ) { self.operation .scrollable(id, bounds, content_bounds, translation, state); } fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.operation.text(id, bounds, text); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } fn finish(&self) -> Outcome<B> { match self.operation.finish() { Outcome::None => Outcome::None, Outcome::Some(output) => Outcome::Some((self.f)(output)), Outcome::Chain(next) => Outcome::Chain(Box::new(Map { operation: next, f: self.f.clone(), })), } } } Map { operation, f: Arc::new(f), } } /// Chains the output of an [`Operation`] with the provided function to /// build a new [`Operation`]. pub fn then<A, B, O>(operation: impl Operation<A> + 'static, f: fn(A) -> O) -> impl Operation<B> where A: 'static, B: Send + 'static, O: Operation<B> + 'static, { struct Chain<T, O, A, B> where T: Operation<A>, O: Operation<B>, { operation: T, next: fn(A) -> O, _result: PhantomData<B>, } impl<T, O, A, B> Operation<B> for Chain<T, O, A, B> where T: Operation<A> + 'static, O: Operation<B> + 'static, A: 'static, B: Send + 'static, { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<B>)) { self.operation.traverse(&mut |operation| { operate(&mut black_box(operation)); }); } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { self.operation.container(id, bounds); } fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: crate::Vector, state: &mut dyn Scrollable, ) { self.operation .scrollable(id, bounds, content_bounds, translation, state); } fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.operation.text(id, bounds, text); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } fn finish(&self) -> Outcome<B> { match self.operation.finish() { Outcome::None => Outcome::None, Outcome::Some(value) => Outcome::Chain(Box::new((self.next)(value))), Outcome::Chain(operation) => Outcome::Chain(Box::new(then(operation, self.next))), } } } Chain { operation, next: f, _result: PhantomData, } } /// Produces an [`Operation`] that applies the given [`Operation`] to the /// children of a container with the given [`Id`]. pub fn scope<T: 'static>(target: Id, operation: impl Operation<T> + 'static) -> impl Operation<T> { struct ScopedOperation<Message> { target: Id, current: Option<Id>, operation: Box<dyn Operation<Message>>, } impl<Message: 'static> Operation<Message> for ScopedOperation<Message> { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<Message>)) { if self.current.as_ref() == Some(&self.target) { self.operation.as_mut().traverse(operate); } else { operate(self); } self.current = None; } fn container(&mut self, id: Option<&Id>, _bounds: Rectangle) { self.current = id.cloned(); } fn finish(&self) -> Outcome<Message> { match self.operation.finish() { Outcome::Chain(next) => Outcome::Chain(Box::new(ScopedOperation { target: self.target.clone(), current: None, operation: next, })), outcome => outcome, } } } ScopedOperation { target, current: None, operation: Box::new(operation), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/operation/scrollable.rs
core/src/widget/operation/scrollable.rs
//! Operate on widgets that can be scrolled. use crate::widget::{Id, Operation}; use crate::{Rectangle, Vector}; /// The internal state of a widget that can be scrolled. pub trait Scrollable { /// Snaps the scroll of the widget to the given `percentage` along the horizontal & vertical axis. fn snap_to(&mut self, offset: RelativeOffset<Option<f32>>); /// Scroll the widget to the given [`AbsoluteOffset`] along the horizontal & vertical axis. fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>); /// Scroll the widget by the given [`AbsoluteOffset`] along the horizontal & vertical axis. fn scroll_by(&mut self, offset: AbsoluteOffset, bounds: Rectangle, content_bounds: Rectangle); } /// Produces an [`Operation`] that snaps the widget with the given [`Id`] to /// the provided `percentage`. pub fn snap_to<T>(target: Id, offset: RelativeOffset<Option<f32>>) -> impl Operation<T> { struct SnapTo { target: Id, offset: RelativeOffset<Option<f32>>, } impl<T> Operation<T> for SnapTo { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } fn scrollable( &mut self, id: Option<&Id>, _bounds: Rectangle, _content_bounds: Rectangle, _translation: Vector, state: &mut dyn Scrollable, ) { if Some(&self.target) == id { state.snap_to(self.offset); } } } SnapTo { target, offset } } /// Produces an [`Operation`] that scrolls the widget with the given [`Id`] to /// the provided [`AbsoluteOffset`]. pub fn scroll_to<T>(target: Id, offset: AbsoluteOffset<Option<f32>>) -> impl Operation<T> { struct ScrollTo { target: Id, offset: AbsoluteOffset<Option<f32>>, } impl<T> Operation<T> for ScrollTo { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } fn scrollable( &mut self, id: Option<&Id>, _bounds: Rectangle, _content_bounds: Rectangle, _translation: Vector, state: &mut dyn Scrollable, ) { if Some(&self.target) == id { state.scroll_to(self.offset); } } } ScrollTo { target, offset } } /// Produces an [`Operation`] that scrolls the widget with the given [`Id`] by /// the provided [`AbsoluteOffset`]. pub fn scroll_by<T>(target: Id, offset: AbsoluteOffset) -> impl Operation<T> { struct ScrollBy { target: Id, offset: AbsoluteOffset, } impl<T> Operation<T> for ScrollBy { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, _translation: Vector, state: &mut dyn Scrollable, ) { if Some(&self.target) == id { state.scroll_by(self.offset, bounds, content_bounds); } } } ScrollBy { target, offset } } /// The amount of absolute offset in each direction of a [`Scrollable`]. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct AbsoluteOffset<T = f32> { /// The amount of horizontal offset pub x: T, /// The amount of vertical offset pub y: T, } impl From<AbsoluteOffset> for AbsoluteOffset<Option<f32>> { fn from(offset: AbsoluteOffset) -> Self { Self { x: Some(offset.x), y: Some(offset.y), } } } /// The amount of relative offset in each direction of a [`Scrollable`]. /// /// A value of `0.0` means start, while `1.0` means end. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct RelativeOffset<T = f32> { /// The amount of horizontal offset pub x: T, /// The amount of vertical offset pub y: T, } impl RelativeOffset { /// A relative offset that points to the top-left of a [`Scrollable`]. pub const START: Self = Self { x: 0.0, y: 0.0 }; /// A relative offset that points to the bottom-right of a [`Scrollable`]. pub const END: Self = Self { x: 1.0, y: 1.0 }; } impl From<RelativeOffset> for RelativeOffset<Option<f32>> { fn from(offset: RelativeOffset) -> Self { Self { x: Some(offset.x), y: Some(offset.y), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/operation/focusable.rs
core/src/widget/operation/focusable.rs
//! Operate on widgets that can be focused. use crate::Rectangle; use crate::widget::Id; use crate::widget::operation::{self, Operation, Outcome}; /// The internal state of a widget that can be focused. pub trait Focusable { /// Returns whether the widget is focused or not. fn is_focused(&self) -> bool; /// Focuses the widget. fn focus(&mut self); /// Unfocuses the widget. fn unfocus(&mut self); } /// A summary of the focusable widgets present on a widget tree. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Count { /// The index of the current focused widget, if any. pub focused: Option<usize>, /// The total amount of focusable widgets. pub total: usize, } /// Produces an [`Operation`] that focuses the widget with the given [`Id`]. pub fn focus<T>(target: Id) -> impl Operation<T> { struct Focus { target: Id, } impl<T> Operation<T> for Focus { fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { match id { Some(id) if id == &self.target => { state.focus(); } _ => { state.unfocus(); } } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } Focus { target } } /// Produces an [`Operation`] that unfocuses the focused widget. pub fn unfocus<T>() -> impl Operation<T> { struct Unfocus; impl<T> Operation<T> for Unfocus { fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { state.unfocus(); } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } Unfocus } /// Produces an [`Operation`] that generates a [`Count`] and chains it with the /// provided function to build a new [`Operation`]. pub fn count() -> impl Operation<Count> { struct CountFocusable { count: Count, } impl Operation<Count> for CountFocusable { fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if state.is_focused() { self.count.focused = Some(self.count.total); } self.count.total += 1; } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<Count>)) { operate(self); } fn finish(&self) -> Outcome<Count> { Outcome::Some(self.count) } } CountFocusable { count: Count::default(), } } /// Produces an [`Operation`] that searches for the current focused widget, and /// - if found, focuses the previous focusable widget. /// - if not found, focuses the last focusable widget. pub fn focus_previous<T>() -> impl Operation<T> where T: Send + 'static, { struct FocusPrevious { count: Count, current: usize, } impl<T> Operation<T> for FocusPrevious { fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if self.count.total == 0 { return; } match self.count.focused { None if self.current == self.count.total - 1 => state.focus(), Some(0) if self.current == 0 => state.unfocus(), Some(0) => {} Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused - 1 == self.current => state.focus(), _ => {} } self.current += 1; } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } operation::then(count(), |count| FocusPrevious { count, current: 0 }) } /// Produces an [`Operation`] that searches for the current focused widget, and /// - if found, focuses the next focusable widget. /// - if not found, focuses the first focusable widget. pub fn focus_next<T>() -> impl Operation<T> where T: Send + 'static, { struct FocusNext { count: Count, current: usize, } impl<T> Operation<T> for FocusNext { fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { match self.count.focused { None if self.current == 0 => state.focus(), Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused + 1 == self.current => state.focus(), _ => {} } self.current += 1; } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } operation::then(count(), |count| FocusNext { count, current: 0 }) } /// Produces an [`Operation`] that searches for the current focused widget /// and stores its ID. This ignores widgets that do not have an ID. pub fn find_focused() -> impl Operation<Id> { struct FindFocused { focused: Option<Id>, } impl Operation<Id> for FindFocused { fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if state.is_focused() && id.is_some() { self.focused = id.cloned(); } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<Id>)) { operate(self); } fn finish(&self) -> Outcome<Id> { if let Some(id) = &self.focused { Outcome::Some(id.clone()) } else { Outcome::None } } } FindFocused { focused: None } } /// Produces an [`Operation`] that searches for the focusable widget /// and stores whether it is focused or not. This ignores widgets that /// do not have an ID. pub fn is_focused(target: Id) -> impl Operation<bool> { struct IsFocused { target: Id, is_focused: Option<bool>, } impl Operation<bool> for IsFocused { fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if id.is_some_and(|id| *id == self.target) { self.is_focused = Some(state.is_focused()); } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<bool>)) { if self.is_focused.is_some() { return; } operate(self); } fn finish(&self) -> Outcome<bool> { self.is_focused.map_or(Outcome::None, Outcome::Some) } } IsFocused { target, is_focused: None, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/core/src/widget/operation/text_input.rs
core/src/widget/operation/text_input.rs
//! Operate on widgets that have text input. use crate::Rectangle; use crate::widget::Id; use crate::widget::operation::Operation; /// The internal state of a widget that has text input. pub trait TextInput { /// Returns the current _visible_ text of the text input /// /// Normally, this is either its value or its placeholder. fn text(&self) -> &str; /// Moves the cursor of the text input to the front of the input text. fn move_cursor_to_front(&mut self); /// Moves the cursor of the text input to the end of the input text. fn move_cursor_to_end(&mut self); /// Moves the cursor of the text input to an arbitrary location. fn move_cursor_to(&mut self, position: usize); /// Selects all the content of the text input. fn select_all(&mut self); /// Selects the given content range of the text input. fn select_range(&mut self, start: usize, end: usize); } /// Produces an [`Operation`] that moves the cursor of the widget with the given [`Id`] to the /// front. pub fn move_cursor_to_front<T>(target: Id) -> impl Operation<T> { struct MoveCursor { target: Id, } impl<T> Operation<T> for MoveCursor { fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to_front(); } _ => {} } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } MoveCursor { target } } /// Produces an [`Operation`] that moves the cursor of the widget with the given [`Id`] to the /// end. pub fn move_cursor_to_end<T>(target: Id) -> impl Operation<T> { struct MoveCursor { target: Id, } impl<T> Operation<T> for MoveCursor { fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to_end(); } _ => {} } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } MoveCursor { target } } /// Produces an [`Operation`] that moves the cursor of the widget with the given [`Id`] to the /// provided position. pub fn move_cursor_to<T>(target: Id, position: usize) -> impl Operation<T> { struct MoveCursor { target: Id, position: usize, } impl<T> Operation<T> for MoveCursor { fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to(self.position); } _ => {} } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } MoveCursor { target, position } } /// Produces an [`Operation`] that selects all the content of the widget with the given [`Id`]. pub fn select_all<T>(target: Id) -> impl Operation<T> { struct MoveCursor { target: Id, } impl<T> Operation<T> for MoveCursor { fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.select_all(); } _ => {} } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } MoveCursor { target } } /// Produces an [`Operation`] that selects the given content range of the widget with the given [`Id`]. pub fn select_range<T>(target: Id, start: usize, end: usize) -> impl Operation<T> { struct SelectRange { target: Id, start: usize, end: usize, } impl<T> Operation<T> for SelectRange { fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.select_range(self.start, self.end); } _ => {} } } fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) { operate(self); } } SelectRange { target, start, end } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tester/src/icon.rs
tester/src/icon.rs
#![allow(unused)] use crate::core::Font; use crate::program; use crate::widget::{Text, text}; pub const FONT: &[u8] = include_bytes!("../fonts/iced_tester-icons.ttf"); pub fn cancel<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{2715}") } pub fn check<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{2713}") } pub fn floppy<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{1F4BE}") } pub fn folder<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{1F4C1}") } pub fn keyboard<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{2328}") } pub fn lightbulb<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{F0EB}") } pub fn mouse_pointer<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{F245}") } pub fn pause<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{2389}") } pub fn pencil<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{270E}") } pub fn play<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{25B6}") } pub fn record<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{26AB}") } pub fn stop<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{25A0}") } pub fn tape<'a, Theme, Renderer>() -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { icon("\u{2707}") } fn icon<'a, Theme, Renderer>(codepoint: &'a str) -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: program::Renderer, { text(codepoint).font(Font::with_name("iced_devtools-icons")) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false