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/src/application/timed.rs
src/application/timed.rs
//! An [`Application`] that receives an [`Instant`] in update logic. use crate::application::{Application, BootFn, ViewFn}; use crate::program; use crate::theme; use crate::time::Instant; use crate::window; use crate::{Element, Program, Settings, Subscription, Task}; use iced_debug as debug; /// Creates an [`Application`] with an `update` function that also /// takes the [`Instant`] of each `Message`. /// /// This constructor is useful to create animated applications that /// are _pure_ (e.g. without relying on side-effect calls like [`Instant::now`]). /// /// Purity is needed when you want your application to end up in the /// same exact state given the same history of messages. This property /// enables proper time traveling debugging with [`comet`]. /// /// [`comet`]: https://github.com/iced-rs/comet pub fn timed<State, Message, Theme, Renderer>( boot: impl BootFn<State, Message>, update: impl UpdateFn<State, Message>, subscription: impl Fn(&State) -> Subscription<Message>, view: impl for<'a> ViewFn<'a, State, Message, Theme, Renderer>, ) -> Application<impl Program<State = State, Message = (Message, Instant), Theme = Theme>> where State: 'static, Message: Send + 'static, Theme: theme::Base + 'static, Renderer: program::Renderer + 'static, { use std::marker::PhantomData; struct Instance<State, Message, Theme, Renderer, Boot, Update, Subscription, View> { boot: Boot, update: Update, subscription: Subscription, view: View, _state: PhantomData<State>, _message: PhantomData<Message>, _theme: PhantomData<Theme>, _renderer: PhantomData<Renderer>, } impl<State, Message, Theme, Renderer, Boot, Update, Subscription, View> Program for Instance<State, Message, Theme, Renderer, Boot, Update, Subscription, View> where Message: Send + 'static, Theme: theme::Base + 'static, Renderer: program::Renderer + 'static, Boot: self::BootFn<State, Message>, Update: self::UpdateFn<State, Message>, Subscription: Fn(&State) -> self::Subscription<Message>, View: for<'a> self::ViewFn<'a, State, Message, Theme, Renderer>, { type State = State; type Message = (Message, Instant); type Theme = Theme; type Renderer = Renderer; type Executor = iced_futures::backend::default::Executor; fn name() -> &'static str { let name = std::any::type_name::<State>(); name.split("::").next().unwrap_or("a_cool_application") } fn settings(&self) -> Settings { Settings::default() } fn window(&self) -> Option<iced_core::window::Settings> { Some(window::Settings::default()) } fn boot(&self) -> (State, Task<Self::Message>) { let (state, task) = self.boot.boot(); (state, task.map(|message| (message, Instant::now()))) } fn update( &self, state: &mut Self::State, (message, now): Self::Message, ) -> Task<Self::Message> { debug::hot(move || { self.update .update(state, message, now) .into() .map(|message| (message, Instant::now())) }) } fn view<'a>( &self, state: &'a Self::State, _window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { debug::hot(|| { self.view .view(state) .map(|message| (message, Instant::now())) }) } fn subscription(&self, state: &Self::State) -> self::Subscription<Self::Message> { debug::hot(|| (self.subscription)(state).map(|message| (message, Instant::now()))) } } Application { raw: Instance { boot, update, subscription, view, _state: PhantomData, _message: PhantomData, _theme: PhantomData, _renderer: PhantomData, }, settings: Settings::default(), window: window::Settings::default(), presets: Vec::new(), } } /// The update logic of some timed [`Application`]. /// /// This is like [`application::UpdateFn`](super::UpdateFn), /// but it also takes an [`Instant`]. pub trait UpdateFn<State, Message> { /// Processes the message and updates the state of the [`Application`]. fn update(&self, state: &mut State, message: Message, now: Instant) -> impl Into<Task<Message>>; } impl<State, Message> UpdateFn<State, Message> for () { fn update( &self, _state: &mut State, _message: Message, _now: Instant, ) -> impl Into<Task<Message>> { } } impl<T, State, Message, C> UpdateFn<State, Message> for T where T: Fn(&mut State, Message, Instant) -> C, C: Into<Task<Message>>, { fn update( &self, state: &mut State, message: Message, now: Instant, ) -> impl Into<Task<Message>> { self(state, message, now) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/benches/wgpu.rs
benches/wgpu.rs
#![allow(missing_docs)] use criterion::{Bencher, Criterion, criterion_group, criterion_main}; use iced::alignment; use iced::mouse; use iced::widget::{canvas, scrollable, stack, text}; use iced::{Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Theme}; use iced_wgpu::Renderer; use iced_wgpu::wgpu; criterion_main!(benches); criterion_group!(benches, wgpu_benchmark); #[allow(unused_results)] pub fn wgpu_benchmark(c: &mut Criterion) { use iced_futures::futures::executor; use iced_wgpu::wgpu; let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { backends: wgpu::Backends::all(), ..Default::default() }); let adapter = executor::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: None, force_fallback_adapter: false, })) .expect("request adapter"); let (device, queue) = executor::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::default(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, experimental_features: wgpu::ExperimentalFeatures::disabled(), })) .expect("request device"); c.bench_function("wgpu — canvas (light)", |b| { benchmark(b, &adapter, &device, &queue, |_| scene(10)); }); c.bench_function("wgpu — canvas (heavy)", |b| { benchmark(b, &adapter, &device, &queue, |_| scene(1_000)); }); c.bench_function("wgpu - layered text (light)", |b| { benchmark(b, &adapter, &device, &queue, |_| layered_text(10)); }); c.bench_function("wgpu - layered text (heavy)", |b| { benchmark(b, &adapter, &device, &queue, |_| layered_text(1_000)); }); c.bench_function("wgpu - dynamic text (light)", |b| { benchmark(b, &adapter, &device, &queue, |i| dynamic_text(1_000, i)); }); c.bench_function("wgpu - dynamic text (heavy)", |b| { benchmark(b, &adapter, &device, &queue, |i| dynamic_text(100_000, i)); }); c.bench_function("wgpu - advanced shaping (light)", |b| { benchmark(b, &adapter, &device, &queue, |i| advanced_shaping(1_000, i)); }); c.bench_function("wgpu - advanced shaping (heavy)", |b| { benchmark(b, &adapter, &device, &queue, |i| { advanced_shaping(100_000, i) }); }); } fn benchmark<'a>( bencher: &mut Bencher<'_>, adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, view: impl Fn(usize) -> Element<'a, (), Theme, Renderer>, ) { use iced_wgpu::graphics; use iced_wgpu::graphics::{Antialiasing, Shell}; use iced_wgpu::wgpu; use iced_winit::core; use iced_winit::runtime; let format = wgpu::TextureFormat::Bgra8UnormSrgb; let engine = iced_wgpu::Engine::new( adapter, device.clone(), queue.clone(), format, Some(Antialiasing::MSAAx4), Shell::headless(), ); let mut renderer = Renderer::new(engine, Font::DEFAULT, Pixels::from(16)); let viewport = graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, size: wgpu::Extent3d { width: 3840, height: 2160, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[], }); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let mut i = 0; let mut cache = Some(runtime::user_interface::Cache::default()); bencher.iter(|| { let mut user_interface = runtime::UserInterface::build( view(i), viewport.logical_size(), cache.take().unwrap(), &mut renderer, ); user_interface.draw( &mut renderer, &Theme::Dark, &core::renderer::Style { text_color: Color::WHITE, }, mouse::Cursor::Unavailable, ); cache = Some(user_interface.into_cache()); let submission = renderer.present(Some(Color::BLACK), format, &texture_view, &viewport); let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None, }); i += 1; }); } fn scene<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> { struct Scene { n: usize, } impl<Message, Theme> canvas::Program<Message, Theme, Renderer> for Scene { type State = canvas::Cache<Renderer>; fn draw( &self, cache: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<canvas::Geometry<Renderer>> { vec![cache.draw(renderer, bounds.size(), |frame| { for i in 0..self.n { frame.fill_rectangle( Point::new(0.0, i as f32), Size::new(10.0, 10.0), Color::WHITE, ); } for i in 0..self.n { frame.fill_text(canvas::Text { content: i.to_string(), position: Point::new(0.0, i as f32), color: Color::BLACK, size: Pixels::from(16), line_height: text::LineHeight::default(), font: Font::DEFAULT, align_x: text::Alignment::Left, align_y: alignment::Vertical::Top, shaping: text::Shaping::Basic, max_width: f32::INFINITY, }); } })] } } canvas(Scene { n }) .width(Length::Fill) .height(Length::Fill) .into() } fn layered_text<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> { stack((0..n).map(|i| text!("I am paragraph {i}!").into())) .width(Length::Fill) .height(Length::Fill) .into() } fn dynamic_text<'a, Message: 'a>(n: usize, i: usize) -> Element<'a, Message, Theme, Renderer> { const LOREM_IPSUM: &str = include_str!("ipsum.txt"); scrollable( text!( "{}... Iteration {i}", std::iter::repeat(LOREM_IPSUM.chars()) .flatten() .take(n) .collect::<String>(), ) .size(10), ) .into() } fn advanced_shaping<'a, Message: 'a>(n: usize, i: usize) -> Element<'a, Message, Theme, Renderer> { const LOREM_IPSUM: &str = include_str!("ipsum.txt"); scrollable( text!( "{}... Iteration {i} 😎", std::iter::repeat(LOREM_IPSUM.chars()) .flatten() .take(n) .collect::<String>(), ) .shaping(text::Shaping::Advanced) .size(10), ) .into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/lib.rs
test/src/lib.rs
//! Test your `iced` applications in headless mode. //! //! # Basic Usage //! Let's assume we want to test [the classical counter interface]. //! //! First, we will want to create a [`Simulator`] of our interface: //! //! ```rust,no_run //! # struct Counter { value: i64 } //! # impl Counter { //! # pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() } //! # } //! use iced_test::simulator; //! //! let mut counter = Counter { value: 0 }; //! let mut ui = simulator(counter.view()); //! ``` //! //! Now we can simulate a user interacting with our interface. Let's use [`Simulator::click`] to click //! the counter buttons: //! //! ```rust,no_run //! # struct Counter { value: i64 } //! # impl Counter { //! # pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() } //! # } //! # use iced_test::simulator; //! # //! # let mut counter = Counter { value: 0 }; //! # let mut ui = simulator(counter.view()); //! # //! let _ = ui.click("+"); //! let _ = ui.click("+"); //! let _ = ui.click("-"); //! ``` //! //! [`Simulator::click`] takes a type implementing the [`Selector`] trait. A [`Selector`] describes a way to query the widgets of an interface. //! In this case, we leverage the [`Selector`] implementation of `&str`, which selects a widget by the text it contains. //! //! We can now process any messages produced by these interactions and then assert that the final value of our counter is //! indeed `1`! //! //! ```rust,no_run //! # struct Counter { value: i64 } //! # impl Counter { //! # pub fn update(&mut self, message: ()) {} //! # pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() } //! # } //! # use iced_test::simulator; //! # //! # let mut counter = Counter { value: 0 }; //! # let mut ui = simulator(counter.view()); //! # //! # let _ = ui.click("+"); //! # let _ = ui.click("+"); //! # let _ = ui.click("-"); //! # //! for message in ui.into_messages() { //! counter.update(message); //! } //! //! assert_eq!(counter.value, 1); //! ``` //! //! We can even rebuild the interface to make sure the counter _displays_ the proper value with [`Simulator::find`]: //! //! ```rust,no_run //! # struct Counter { value: i64 } //! # impl Counter { //! # pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() } //! # } //! # use iced_test::simulator; //! # //! # let mut counter = Counter { value: 0 }; //! let mut ui = simulator(counter.view()); //! //! assert!(ui.find("1").is_ok(), "Counter should display 1!"); //! ``` //! //! And that's it! That's the gist of testing `iced` applications! //! //! [`Simulator`] contains additional operations you can use to simulate more interactions—like [`tap_key`](Simulator::tap_key) or //! [`typewrite`](Simulator::typewrite)—and even perform [_snapshot testing_](Simulator::snapshot)! //! //! [the classical counter interface]: https://book.iced.rs/architecture.html#dissecting-an-interface pub use iced_futures as futures; pub use iced_program as program; pub use iced_renderer as renderer; pub use iced_runtime as runtime; pub use iced_runtime::core; pub use iced_selector as selector; pub mod emulator; pub mod ice; pub mod instruction; pub mod simulator; mod error; pub use emulator::Emulator; pub use error::Error; pub use ice::Ice; pub use instruction::Instruction; pub use selector::Selector; pub use simulator::{Simulator, simulator}; use crate::core::Size; use crate::core::time::{Duration, Instant}; use crate::core::window; use std::path::Path; /// Runs an [`Ice`] test suite for the given [`Program`](program::Program). /// /// Any `.ice` tests will be parsed from the given directory and executed in /// an [`Emulator`] of the given [`Program`](program::Program). /// /// Remember that an [`Emulator`] executes the real thing! Side effects _will_ /// take place. It is up to you to ensure your tests have reproducible environments /// by leveraging [`Preset`][program::Preset]. pub fn run( program: impl program::Program + 'static, tests_dir: impl AsRef<Path>, ) -> Result<(), Error> { use crate::futures::futures::StreamExt; use crate::futures::futures::channel::mpsc; use crate::futures::futures::executor; use std::ffi::OsStr; use std::fs; let files = fs::read_dir(tests_dir)?; let mut tests = Vec::new(); for file in files { let file = file?; if file.path().extension().and_then(OsStr::to_str) != Some("ice") { continue; } let content = fs::read_to_string(file.path())?; match Ice::parse(&content) { Ok(ice) => { let preset = if let Some(preset) = &ice.preset { let Some(preset) = program .presets() .iter() .find(|candidate| candidate.name() == preset) else { return Err(Error::PresetNotFound { name: preset.to_owned(), available: program .presets() .iter() .map(program::Preset::name) .map(str::to_owned) .collect(), }); }; Some(preset) } else { None }; tests.push((file, ice, preset)); } Err(error) => { return Err(Error::IceParsingFailed { file: file.path().to_path_buf(), error, }); } } } // TODO: Concurrent runtimes for (file, ice, preset) in tests { let (sender, mut receiver) = mpsc::channel(1); let mut emulator = Emulator::with_preset(sender, &program, ice.mode, ice.viewport, preset); let mut instructions = ice.instructions.into_iter(); loop { let event = executor::block_on(receiver.next()) .expect("emulator runtime should never stop on its own"); match event { emulator::Event::Action(action) => { emulator.perform(&program, action); } emulator::Event::Failed(instruction) => { return Err(Error::IceTestingFailed { file: file.path().to_path_buf(), instruction, }); } emulator::Event::Ready => { let Some(instruction) = instructions.next() else { break; }; emulator.run(&program, instruction); } } } } Ok(()) } /// Takes a screenshot of the given [`Program`](program::Program) with the given theme, viewport, /// and scale factor after running it for the given [`Duration`]. pub fn screenshot<P: program::Program + 'static>( program: &P, theme: &P::Theme, viewport: impl Into<Size>, scale_factor: f32, duration: Duration, ) -> window::Screenshot { use crate::runtime::futures::futures::channel::mpsc; let (sender, mut receiver) = mpsc::channel(100); let mut emulator = Emulator::new(sender, program, emulator::Mode::Immediate, viewport.into()); let start = Instant::now(); loop { if let Some(event) = receiver.try_next().ok().flatten() { match event { emulator::Event::Action(action) => { emulator.perform(program, action); } emulator::Event::Failed(_) => { unreachable!("no instructions should be executed during a screenshot"); } emulator::Event::Ready => {} } } if start.elapsed() >= duration { break; } std::thread::sleep(Duration::from_millis(1)); } emulator.screenshot(program, theme, scale_factor) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/instruction.rs
test/src/instruction.rs
//! A step in an end-to-end test. use crate::core::keyboard; use crate::core::mouse; use crate::core::{Event, Point}; use crate::simulator; use std::fmt; /// A step in an end-to-end test. /// /// An [`Instruction`] can be run by an [`Emulator`](crate::Emulator). #[derive(Debug, Clone, PartialEq)] pub enum Instruction { /// A user [`Interaction`]. Interact(Interaction), /// A testing [`Expectation`]. Expect(Expectation), } impl Instruction { /// Parses an [`Instruction`] from its textual representation. pub fn parse(line: &str) -> Result<Self, ParseError> { parser::run(line) } } impl fmt::Display for Instruction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Instruction::Interact(interaction) => interaction.fmt(f), Instruction::Expect(expectation) => expectation.fmt(f), } } } /// A user interaction. #[derive(Debug, Clone, PartialEq)] pub enum Interaction { /// A mouse interaction. Mouse(Mouse), /// A keyboard interaction. Keyboard(Keyboard), } impl Interaction { /// Creates an [`Interaction`] from a runtime [`Event`]. /// /// This can be useful for recording tests during real usage. pub fn from_event(event: &Event) -> Option<Self> { Some(match event { Event::Mouse(mouse) => Self::Mouse(match mouse { mouse::Event::CursorMoved { position } => Mouse::Move(Target::Point(*position)), mouse::Event::ButtonPressed(button) => Mouse::Press { button: *button, target: None, }, mouse::Event::ButtonReleased(button) => Mouse::Release { button: *button, target: None, }, _ => None?, }), Event::Keyboard(keyboard) => Self::Keyboard(match keyboard { keyboard::Event::KeyPressed { key, text, .. } => match key { keyboard::Key::Named(keyboard::key::Named::Enter) => { Keyboard::Press(Key::Enter) } keyboard::Key::Named(keyboard::key::Named::Escape) => { Keyboard::Press(Key::Escape) } keyboard::Key::Named(keyboard::key::Named::Tab) => Keyboard::Press(Key::Tab), keyboard::Key::Named(keyboard::key::Named::Backspace) => { Keyboard::Press(Key::Backspace) } _ => Keyboard::Typewrite(text.as_ref()?.to_string()), }, keyboard::Event::KeyReleased { key, .. } => match key { keyboard::Key::Named(keyboard::key::Named::Enter) => { Keyboard::Release(Key::Enter) } keyboard::Key::Named(keyboard::key::Named::Escape) => { Keyboard::Release(Key::Escape) } keyboard::Key::Named(keyboard::key::Named::Tab) => Keyboard::Release(Key::Tab), keyboard::Key::Named(keyboard::key::Named::Backspace) => { Keyboard::Release(Key::Backspace) } _ => None?, }, keyboard::Event::ModifiersChanged(_) => None?, }), _ => None?, }) } /// Merges two interactions together, if possible. /// /// This method can turn certain sequences of interactions into a single one. /// For instance, a mouse movement, left button press, and left button release /// can all be merged into a single click interaction. /// /// Merging is lossy and, therefore, it is not always desirable if you are recording /// a test and want full reproducibility. /// /// If the interactions cannot be merged, the `next` interaction will be /// returned as the second element of the tuple. pub fn merge(self, next: Self) -> (Self, Option<Self>) { match (self, next) { (Self::Mouse(current), Self::Mouse(next)) => match (current, next) { (Mouse::Move(_), Mouse::Move(to)) => (Self::Mouse(Mouse::Move(to)), None), ( Mouse::Move(to), Mouse::Press { button, target: None, }, ) => ( Self::Mouse(Mouse::Press { button, target: Some(to), }), None, ), ( Mouse::Move(to), Mouse::Release { button, target: None, }, ) => ( Self::Mouse(Mouse::Release { button, target: Some(to), }), None, ), ( Mouse::Press { button: press, target: press_at, }, Mouse::Release { button: release, target: release_at, }, ) if press == release && release_at .as_ref() .is_none_or(|release_at| Some(release_at) == press_at.as_ref()) => { ( Self::Mouse(Mouse::Click { button: press, target: press_at, }), None, ) } ( Mouse::Press { button, target: Some(press_at), }, Mouse::Move(move_at), ) if press_at == move_at => ( Self::Mouse(Mouse::Press { button, target: Some(press_at), }), None, ), ( Mouse::Click { button, target: Some(click_at), }, Mouse::Move(move_at), ) if click_at == move_at => ( Self::Mouse(Mouse::Click { button, target: Some(click_at), }), None, ), (current, next) => (Self::Mouse(current), Some(Self::Mouse(next))), }, (Self::Keyboard(current), Self::Keyboard(next)) => match (current, next) { (Keyboard::Typewrite(current), Keyboard::Typewrite(next)) => ( Self::Keyboard(Keyboard::Typewrite(format!("{current}{next}"))), None, ), (Keyboard::Press(current), Keyboard::Release(next)) if current == next => { (Self::Keyboard(Keyboard::Type(current)), None) } (current, next) => (Self::Keyboard(current), Some(Self::Keyboard(next))), }, (current, next) => (current, Some(next)), } } /// Returns a list of runtime events representing the [`Interaction`]. /// /// The `find_target` closure must convert a [`Target`] into its screen /// coordinates. pub fn events(&self, find_target: impl FnOnce(&Target) -> Option<Point>) -> Option<Vec<Event>> { let mouse_move_ = |to| Event::Mouse(mouse::Event::CursorMoved { position: to }); let mouse_press = |button| Event::Mouse(mouse::Event::ButtonPressed(button)); let mouse_release = |button| Event::Mouse(mouse::Event::ButtonReleased(button)); let key_press = |key| simulator::press_key(key, None); let key_release = |key| simulator::release_key(key); Some(match self { Interaction::Mouse(mouse) => match mouse { Mouse::Move(to) => vec![mouse_move_(find_target(to)?)], Mouse::Press { button, target: Some(at), } => vec![mouse_move_(find_target(at)?), mouse_press(*button)], Mouse::Press { button, target: None, } => { vec![mouse_press(*button)] } Mouse::Release { button, target: Some(at), } => { vec![mouse_move_(find_target(at)?), mouse_release(*button)] } Mouse::Release { button, target: None, } => { vec![mouse_release(*button)] } Mouse::Click { button, target: Some(at), } => { vec![ mouse_move_(find_target(at)?), mouse_press(*button), mouse_release(*button), ] } Mouse::Click { button, target: None, } => { vec![mouse_press(*button), mouse_release(*button)] } }, Interaction::Keyboard(keyboard) => match keyboard { Keyboard::Press(key) => vec![key_press(*key)], Keyboard::Release(key) => vec![key_release(*key)], Keyboard::Type(key) => vec![key_press(*key), key_release(*key)], Keyboard::Typewrite(text) => simulator::typewrite(text).collect(), }, }) } } impl fmt::Display for Interaction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Interaction::Mouse(mouse) => mouse.fmt(f), Interaction::Keyboard(keyboard) => keyboard.fmt(f), } } } /// A mouse interaction. #[derive(Debug, Clone, PartialEq)] pub enum Mouse { /// The mouse was moved. Move(Target), /// A button was pressed. Press { /// The button. button: mouse::Button, /// The location of the press. target: Option<Target>, }, /// A button was released. Release { /// The button. button: mouse::Button, /// The location of the release. target: Option<Target>, }, /// A button was clicked. Click { /// The button. button: mouse::Button, /// The location of the click. target: Option<Target>, }, } impl fmt::Display for Mouse { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Mouse::Move(target) => { write!(f, "move {}", target) } Mouse::Press { button, target } => { write!(f, "press {}", format::button_at(*button, target.as_ref())) } Mouse::Release { button, target } => { write!(f, "release {}", format::button_at(*button, target.as_ref())) } Mouse::Click { button, target } => { write!(f, "click {}", format::button_at(*button, target.as_ref())) } } } } /// The target of an interaction. #[derive(Debug, Clone, PartialEq)] pub enum Target { /// A specific point of the viewport. Point(Point), /// A UI element containing the given text. Text(String), } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Point(point) => f.write_str(&format::point(*point)), Self::Text(text) => f.write_str(&format::string(text)), } } } /// A keyboard interaction. #[derive(Debug, Clone, PartialEq)] pub enum Keyboard { /// A key was pressed. Press(Key), /// A key was released. Release(Key), /// A key was "typed" (press and released). Type(Key), /// A bunch of text was typed. Typewrite(String), } impl fmt::Display for Keyboard { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Keyboard::Press(key) => { write!(f, "press {}", format::key(*key)) } Keyboard::Release(key) => { write!(f, "release {}", format::key(*key)) } Keyboard::Type(key) => { write!(f, "type {}", format::key(*key)) } Keyboard::Typewrite(text) => { write!(f, "type \"{text}\"") } } } } /// A keyboard key. /// /// Only a small subset of keys is supported currently! #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[allow(missing_docs)] pub enum Key { Enter, Escape, Tab, Backspace, } impl From<Key> for keyboard::Key { fn from(key: Key) -> Self { match key { Key::Enter => Self::Named(keyboard::key::Named::Enter), Key::Escape => Self::Named(keyboard::key::Named::Escape), Key::Tab => Self::Named(keyboard::key::Named::Tab), Key::Backspace => Self::Named(keyboard::key::Named::Backspace), } } } mod format { use super::*; pub fn button_at(button: mouse::Button, at: Option<&Target>) -> String { let button = self::button(button); if let Some(at) = at { if button.is_empty() { at.to_string() } else { format!("{} {}", button, at) } } else { button.to_owned() } } pub fn button(button: mouse::Button) -> &'static str { match button { mouse::Button::Left => "", mouse::Button::Right => "right", mouse::Button::Middle => "middle", mouse::Button::Back => "back", mouse::Button::Forward => "forward", mouse::Button::Other(_) => "other", } } pub fn point(point: Point) -> String { format!("({:.2}, {:.2})", point.x, point.y) } pub fn key(key: Key) -> &'static str { match key { Key::Enter => "enter", Key::Escape => "escape", Key::Tab => "tab", Key::Backspace => "backspace", } } pub fn string(text: &str) -> String { format!("\"{}\"", text.escape_default()) } } /// A testing assertion. /// /// Expectations are instructions that verify the current state of /// the user interface of an application. #[derive(Debug, Clone, PartialEq)] pub enum Expectation { /// Expect some element to contain some text. Text(String), } impl fmt::Display for Expectation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Expectation::Text(text) => { write!(f, "expect {}", format::string(text)) } } } } pub use parser::Error as ParseError; mod parser { use super::*; use nom::branch::alt; use nom::bytes::complete::tag; use nom::bytes::{is_not, take_while_m_n}; use nom::character::complete::{char, multispace0, multispace1}; use nom::combinator::{map, map_opt, map_res, opt, success, value, verify}; use nom::error::ParseError; use nom::multi::fold; use nom::number::float; use nom::sequence::{delimited, preceded, separated_pair}; use nom::{Finish, IResult, Parser}; /// A parsing error. #[derive(Debug, Clone, thiserror::Error)] #[error("parse error: {0}")] pub struct Error(nom::error::Error<String>); pub fn run(input: &str) -> Result<Instruction, Error> { match instruction.parse_complete(input).finish() { Ok((_rest, instruction)) => Ok(instruction), Err(error) => Err(Error(error.cloned())), } } fn instruction(input: &str) -> IResult<&str, Instruction> { alt(( map(interaction, Instruction::Interact), map(expectation, Instruction::Expect), )) .parse(input) } fn interaction(input: &str) -> IResult<&str, Interaction> { alt(( map(mouse, Interaction::Mouse), map(keyboard, Interaction::Keyboard), )) .parse(input) } fn mouse(input: &str) -> IResult<&str, Mouse> { let mouse_move = preceded(tag("move "), target).map(Mouse::Move); alt((mouse_move, mouse_click, mouse_press, mouse_release)).parse(input) } fn mouse_click(input: &str) -> IResult<&str, Mouse> { let (input, _) = tag("click ")(input)?; let (input, (button, target)) = mouse_button_at(input)?; Ok((input, Mouse::Click { button, target })) } fn mouse_press(input: &str) -> IResult<&str, Mouse> { let (input, _) = tag("press ")(input)?; let (input, (button, target)) = mouse_button_at(input)?; Ok((input, Mouse::Press { button, target })) } fn mouse_release(input: &str) -> IResult<&str, Mouse> { let (input, _) = tag("release ")(input)?; let (input, (button, target)) = mouse_button_at(input)?; Ok((input, Mouse::Release { button, target })) } fn mouse_button_at(input: &str) -> IResult<&str, (mouse::Button, Option<Target>)> { let (input, button) = mouse_button(input)?; let (input, at) = opt(target).parse(input)?; Ok((input, (button, at))) } fn target(input: &str) -> IResult<&str, Target> { alt((string.map(Target::Text), point.map(Target::Point))).parse(input) } fn mouse_button(input: &str) -> IResult<&str, mouse::Button> { alt(( tag("right").map(|_| mouse::Button::Right), success(mouse::Button::Left), )) .parse(input) } fn keyboard(input: &str) -> IResult<&str, Keyboard> { alt(( map(preceded(tag("type "), string), Keyboard::Typewrite), map(preceded(tag("type "), key), Keyboard::Type), )) .parse(input) } fn expectation(input: &str) -> IResult<&str, Expectation> { map(preceded(tag("expect "), string), |text| { Expectation::Text(text) }) .parse(input) } fn key(input: &str) -> IResult<&str, Key> { alt(( map(tag("enter"), |_| Key::Enter), map(tag("escape"), |_| Key::Escape), map(tag("tab"), |_| Key::Tab), map(tag("backspace"), |_| Key::Backspace), )) .parse(input) } fn point(input: &str) -> IResult<&str, Point> { let comma = whitespace(char(',')); map( delimited( char('('), separated_pair(float(), comma, float()), char(')'), ), |(x, y)| Point { x, y }, ) .parse(input) } pub fn whitespace<'a, O, E: ParseError<&'a str>, F>( inner: F, ) -> impl Parser<&'a str, Output = O, Error = E> where F: Parser<&'a str, Output = O, Error = E>, { delimited(multispace0, inner, multispace0) } // Taken from https://github.com/rust-bakery/nom/blob/51c3c4e44fa78a8a09b413419372b97b2cc2a787/examples/string.rs // // Copyright (c) 2014-2019 Geoffroy Couprie // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fn string(input: &str) -> IResult<&str, String> { #[derive(Debug, Clone, Copy)] enum Fragment<'a> { Literal(&'a str), EscapedChar(char), EscapedWS, } fn fragment(input: &str) -> IResult<&str, Fragment<'_>> { alt(( map(string_literal, Fragment::Literal), map(escaped_char, Fragment::EscapedChar), value(Fragment::EscapedWS, escaped_whitespace), )) .parse(input) } fn string_literal<'a, E: ParseError<&'a str>>( input: &'a str, ) -> IResult<&'a str, &'a str, E> { let not_quote_slash = is_not("\"\\"); verify(not_quote_slash, |s: &str| !s.is_empty()).parse(input) } fn unicode(input: &str) -> IResult<&str, char> { let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit()); let parse_delimited_hex = preceded(char('u'), delimited(char('{'), parse_hex, char('}'))); let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16)); map_opt(parse_u32, std::char::from_u32).parse(input) } fn escaped_char(input: &str) -> IResult<&str, char> { preceded( char('\\'), alt(( unicode, value('\n', char('n')), value('\r', char('r')), value('\t', char('t')), value('\u{08}', char('b')), value('\u{0C}', char('f')), value('\\', char('\\')), value('/', char('/')), value('"', char('"')), )), ) .parse(input) } fn escaped_whitespace(input: &str) -> IResult<&str, &str> { preceded(char('\\'), multispace1).parse(input) } let build_string = fold(0.., fragment, String::new, |mut string, fragment| { match fragment { Fragment::Literal(s) => string.push_str(s), Fragment::EscapedChar(c) => string.push(c), Fragment::EscapedWS => {} } string }); delimited(char('"'), build_string, char('"')).parse(input) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/error.rs
test/src/error.rs
use crate::Instruction; use crate::ice; use std::io; use std::path::PathBuf; use std::sync::Arc; /// A test error. #[derive(Debug, Clone, thiserror::Error)] pub enum Error { /// No matching widget was found for the [`Selector`](crate::Selector). #[error("no matching widget was found for the selector: {selector}")] SelectorNotFound { /// A description of the selector. selector: String, }, /// A target matched, but is not visible. #[error("the matching target is not visible: {target:?}")] TargetNotVisible { /// The target target: Arc<dyn std::fmt::Debug + Send + Sync>, }, /// An IO operation failed. #[error("an IO operation failed: {0}")] IOFailed(Arc<io::Error>), /// The decoding of some PNG image failed. #[error("the decoding of some PNG image failed: {0}")] PngDecodingFailed(Arc<png::DecodingError>), /// The encoding of some PNG image failed. #[error("the encoding of some PNG image failed: {0}")] PngEncodingFailed(Arc<png::EncodingError>), /// The parsing of an [`Ice`](crate::Ice) test failed. #[error("the ice test ({file}) is invalid: {error}")] IceParsingFailed { /// The path of the test. file: PathBuf, /// The parse error. error: ice::ParseError, }, /// The execution of an [`Ice`](crate::Ice) test failed. #[error("the ice test ({file}) failed")] IceTestingFailed { /// The path of the test. file: PathBuf, /// The [`Instruction`] that failed. instruction: Instruction, }, /// The [`Preset`](crate::program::Preset) of a program could not be found. #[error("the preset \"{name}\" does not exist (available presets: {available:?})")] PresetNotFound { /// The name of the [`Preset`](crate::program::Preset). name: String, /// The available set of presets. available: Vec<String>, }, } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Self::IOFailed(Arc::new(error)) } } impl From<png::DecodingError> for Error { fn from(error: png::DecodingError) -> Self { Self::PngDecodingFailed(Arc::new(error)) } } impl From<png::EncodingError> for Error { fn from(error: png::EncodingError) -> Self { Self::PngEncodingFailed(Arc::new(error)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/simulator.rs
test/src/simulator.rs
//! Run a simulation of your application without side effects. use crate::core; use crate::core::clipboard; use crate::core::event; use crate::core::keyboard; use crate::core::mouse; use crate::core::theme; use crate::core::time; use crate::core::widget; use crate::core::window; use crate::core::{Element, Event, Font, Point, Settings, Size, SmolStr}; use crate::renderer; use crate::runtime::UserInterface; use crate::runtime::user_interface; use crate::selector::Bounded; use crate::{Error, Selector}; use std::borrow::Cow; use std::env; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; /// A user interface that can be interacted with and inspected programmatically. pub struct Simulator<'a, Message, Theme = core::Theme, Renderer = renderer::Renderer> { raw: UserInterface<'a, Message, Theme, Renderer>, renderer: Renderer, size: Size, cursor: mouse::Cursor, messages: Vec<Message>, } impl<'a, Message, Theme, Renderer> Simulator<'a, Message, Theme, Renderer> where Theme: theme::Base, Renderer: core::Renderer + core::renderer::Headless, { /// Creates a new [`Simulator`] with default [`Settings`] and a default size (1024x768). pub fn new(element: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self::with_settings(Settings::default(), element) } /// Creates a new [`Simulator`] with the given [`Settings`] and a default size (1024x768). pub fn with_settings( settings: Settings, element: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Self { Self::with_size(settings, window::Settings::default().size, element) } /// Creates a new [`Simulator`] with the given [`Settings`] and size. pub fn with_size( settings: Settings, size: impl Into<Size>, element: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Self { let size = size.into(); let default_font = match settings.default_font { Font::DEFAULT => Font::with_name("Fira Sans"), _ => settings.default_font, }; for font in settings.fonts { load_font(font).expect("Font must be valid"); } let mut renderer = { let backend = env::var("ICED_TEST_BACKEND").ok(); crate::futures::futures::executor::block_on(Renderer::new( default_font, settings.default_text_size, backend.as_deref(), )) .expect("Create new headless renderer") }; let raw = UserInterface::build( element, size, user_interface::Cache::default(), &mut renderer, ); Simulator { raw, renderer, size, cursor: mouse::Cursor::Unavailable, messages: Vec::new(), } } /// Finds the target of the given widget [`Selector`] in the [`Simulator`]. pub fn find<S>(&mut self, selector: S) -> Result<S::Output, Error> where S: Selector + Send, S::Output: Clone + Send, { use widget::Operation; let description = selector.description(); let mut operation = selector.find(); self.raw.operate( &self.renderer, &mut widget::operation::black_box(&mut operation), ); match operation.finish() { widget::operation::Outcome::Some(output) => output.ok_or(Error::SelectorNotFound { selector: description, }), _ => Err(Error::SelectorNotFound { selector: description, }), } } /// Points the mouse cursor at the given position in the [`Simulator`]. /// /// This does _not_ produce mouse movement events! pub fn point_at(&mut self, position: impl Into<Point>) { self.cursor = mouse::Cursor::Available(position.into()); } /// Clicks the [`Bounded`] target found by the given [`Selector`], if any. /// /// This consists in: /// - Pointing the mouse cursor at the center of the [`Bounded`] target. /// - Simulating a [`click`]. pub fn click<S>(&mut self, selector: S) -> Result<S::Output, Error> where S: Selector + Send, S::Output: Bounded + Clone + Send + Sync + 'static, { let target = self.find(selector)?; let Some(visible_bounds) = target.visible_bounds() else { return Err(Error::TargetNotVisible { target: Arc::new(target), }); }; self.point_at(visible_bounds.center()); let _ = self.simulate(click()); Ok(target) } /// Simulates a key press, followed by a release, in the [`Simulator`]. pub fn tap_key(&mut self, key: impl Into<keyboard::Key>) -> event::Status { self.simulate(tap_key(key, None)) .first() .copied() .unwrap_or(event::Status::Ignored) } /// Simulates a user typing in the keyboard the given text in the [`Simulator`]. pub fn typewrite(&mut self, text: &str) -> event::Status { let statuses = self.simulate(typewrite(text)); statuses .into_iter() .fold(event::Status::Ignored, event::Status::merge) } /// Simulates the given raw sequence of events in the [`Simulator`]. pub fn simulate(&mut self, events: impl IntoIterator<Item = Event>) -> Vec<event::Status> { let events: Vec<Event> = events.into_iter().collect(); let (_state, statuses) = self.raw.update( &events, self.cursor, &mut self.renderer, &mut clipboard::Null, &mut self.messages, ); statuses } /// Draws and takes a [`Snapshot`] of the interface in the [`Simulator`]. pub fn snapshot(&mut self, theme: &Theme) -> Result<Snapshot, Error> { let base = theme.base(); let _ = self.raw.update( &[Event::Window(window::Event::RedrawRequested( time::Instant::now(), ))], self.cursor, &mut self.renderer, &mut clipboard::Null, &mut self.messages, ); self.raw.draw( &mut self.renderer, theme, &core::renderer::Style { text_color: base.text_color, }, self.cursor, ); let scale_factor = 2.0; let physical_size = Size::new( (self.size.width * scale_factor).round() as u32, (self.size.height * scale_factor).round() as u32, ); let rgba = self .renderer .screenshot(physical_size, scale_factor, base.background_color); Ok(Snapshot { screenshot: window::Screenshot::new(rgba, physical_size, scale_factor), renderer: self.renderer.name(), }) } /// Turns the [`Simulator`] into the sequence of messages produced by any interactions. pub fn into_messages(self) -> impl Iterator<Item = Message> + use<Message, Theme, Renderer> { self.messages.into_iter() } } /// A frame of a user interface rendered by a [`Simulator`]. #[derive(Debug, Clone)] pub struct Snapshot { screenshot: window::Screenshot, renderer: String, } impl Snapshot { /// Compares the [`Snapshot`] with the PNG image found in the given path, returning /// `true` if they are identical. /// /// If the PNG image does not exist, it will be created by the [`Snapshot`] for future /// testing and `true` will be returned. pub fn matches_image(&self, path: impl AsRef<Path>) -> Result<bool, Error> { let path = self.path(path, "png"); if path.exists() { let file = fs::File::open(&path)?; let decoder = png::Decoder::new(io::BufReader::new(file)); let mut reader = decoder.read_info()?; let n = reader .output_buffer_size() .expect("snapshot should fit in memory"); let mut bytes = vec![0; n]; let info = reader.next_frame(&mut bytes)?; Ok(self.screenshot.rgba == bytes[..info.buffer_size()]) } else { if let Some(directory) = path.parent() { fs::create_dir_all(directory)?; } let file = fs::File::create(path)?; let mut encoder = png::Encoder::new( file, self.screenshot.size.width, self.screenshot.size.height, ); encoder.set_color(png::ColorType::Rgba); let mut writer = encoder.write_header()?; writer.write_image_data(&self.screenshot.rgba)?; writer.finish()?; Ok(true) } } /// Compares the [`Snapshot`] with the SHA-256 hash file found in the given path, returning /// `true` if they are identical. /// /// If the hash file does not exist, it will be created by the [`Snapshot`] for future /// testing and `true` will be returned. pub fn matches_hash(&self, path: impl AsRef<Path>) -> Result<bool, Error> { use sha2::{Digest, Sha256}; let path = self.path(path, "sha256"); let hash = { let mut hasher = Sha256::new(); hasher.update(&self.screenshot.rgba); format!("{:x}", hasher.finalize()) }; if path.exists() { let saved_hash = fs::read_to_string(&path)?; Ok(hash == saved_hash) } else { if let Some(directory) = path.parent() { fs::create_dir_all(directory)?; } fs::write(path, hash)?; Ok(true) } } fn path(&self, path: impl AsRef<Path>, extension: &str) -> PathBuf { let path = path.as_ref(); path.with_file_name(format!( "{name}-{renderer}", name = path .file_stem() .map(std::ffi::OsStr::to_string_lossy) .unwrap_or_default(), renderer = self.renderer )) .with_extension(extension) } } /// Creates a new [`Simulator`]. /// /// This is just a function version of [`Simulator::new`]. pub fn simulator<'a, Message, Theme, Renderer>( element: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Simulator<'a, Message, Theme, Renderer> where Theme: theme::Base, Renderer: core::Renderer + core::renderer::Headless, { Simulator::new(element) } /// Returns the sequence of events of a click. pub fn click() -> impl Iterator<Item = Event> { [ Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)), Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)), ] .into_iter() } /// Returns the sequence of events of a key press. pub fn press_key(key: impl Into<keyboard::Key>, text: Option<SmolStr>) -> Event { let key = key.into(); Event::Keyboard(keyboard::Event::KeyPressed { key: key.clone(), modified_key: key, physical_key: keyboard::key::Physical::Unidentified( keyboard::key::NativeCode::Unidentified, ), location: keyboard::Location::Standard, modifiers: keyboard::Modifiers::default(), repeat: false, text, }) } /// Returns the sequence of events of a key release. pub fn release_key(key: impl Into<keyboard::Key>) -> Event { let key = key.into(); Event::Keyboard(keyboard::Event::KeyReleased { key: key.clone(), modified_key: key, physical_key: keyboard::key::Physical::Unidentified( keyboard::key::NativeCode::Unidentified, ), location: keyboard::Location::Standard, modifiers: keyboard::Modifiers::default(), }) } /// Returns the sequence of events of a "key tap" (i.e. pressing and releasing a key). pub fn tap_key( key: impl Into<keyboard::Key>, text: Option<SmolStr>, ) -> impl Iterator<Item = Event> { let key = key.into(); [press_key(key.clone(), text), release_key(key)].into_iter() } /// Returns the sequence of events of typewriting the given text in a keyboard. pub fn typewrite(text: &str) -> impl Iterator<Item = Event> + '_ { text.chars() .map(|c| SmolStr::new_inline(&c.to_string())) .flat_map(|c| tap_key(keyboard::Key::Character(c.clone()), Some(c))) } fn load_font(font: impl Into<Cow<'static, [u8]>>) -> Result<(), Error> { renderer::graphics::text::font_system() .write() .expect("Write to font system") .load_font(font.into()); Ok(()) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/emulator.rs
test/src/emulator.rs
//! Run your application in a headless runtime. use crate::core; use crate::core::mouse; use crate::core::renderer; use crate::core::time::Instant; use crate::core::widget; use crate::core::window; use crate::core::{Bytes, Element, Point, Size}; use crate::instruction; use crate::program; use crate::program::Program; use crate::runtime; use crate::runtime::futures::futures::StreamExt; use crate::runtime::futures::futures::channel::mpsc; use crate::runtime::futures::futures::stream; use crate::runtime::futures::subscription; use crate::runtime::futures::{Executor, Runtime}; use crate::runtime::task; use crate::runtime::user_interface; use crate::runtime::{Task, UserInterface}; use crate::{Instruction, Selector}; use std::fmt; /// A headless runtime that can run iced applications and execute /// [instructions](crate::Instruction). /// /// An [`Emulator`] runs its program as faithfully as possible to the real thing. /// It will run subscriptions and tasks with the [`Executor`](Program::Executor) of /// the [`Program`]. /// /// If you want to run a simulation without side effects, use a [`Simulator`](crate::Simulator) /// instead. pub struct Emulator<P: Program> { state: P::State, runtime: Runtime<P::Executor, mpsc::Sender<Event<P>>, Event<P>>, renderer: P::Renderer, mode: Mode, size: Size, window: core::window::Id, cursor: mouse::Cursor, clipboard: Clipboard, cache: Option<user_interface::Cache>, pending_tasks: usize, } /// An emulation event. pub enum Event<P: Program> { /// An action that must be [performed](Emulator::perform) by the [`Emulator`]. Action(Action<P>), /// An [`Instruction`] failed to be executed. Failed(Instruction), /// The [`Emulator`] is ready. Ready, } /// An action that must be [performed](Emulator::perform) by the [`Emulator`]. pub struct Action<P: Program>(Action_<P>); enum Action_<P: Program> { Runtime(runtime::Action<P::Message>), CountDown, } impl<P: Program + 'static> Emulator<P> { /// Creates a new [`Emulator`] of the [`Program`] with the given [`Mode`] and [`Size`]. /// /// The [`Emulator`] will send [`Event`] notifications through the provided [`mpsc::Sender`]. /// /// When the [`Emulator`] has finished booting, an [`Event::Ready`] will be produced. pub fn new(sender: mpsc::Sender<Event<P>>, program: &P, mode: Mode, size: Size) -> Emulator<P> { Self::with_preset(sender, program, mode, size, None) } /// Creates a new [`Emulator`] analogously to [`new`](Self::new), but it also takes a /// [`program::Preset`] that will be used as the initial state. /// /// When the [`Emulator`] has finished booting, an [`Event::Ready`] will be produced. pub fn with_preset( sender: mpsc::Sender<Event<P>>, program: &P, mode: Mode, size: Size, preset: Option<&program::Preset<P::State, P::Message>>, ) -> Emulator<P> { use renderer::Headless; let settings = program.settings(); // TODO: Error handling let executor = P::Executor::new().expect("Create emulator executor"); let renderer = executor .block_on(P::Renderer::new( settings.default_font, settings.default_text_size, None, )) .expect("Create emulator renderer"); let runtime = Runtime::new(executor, sender); let (state, task) = runtime.enter(|| { if let Some(preset) = preset { preset.boot() } else { program.boot() } }); let mut emulator = Self { state, runtime, renderer, mode, size, clipboard: Clipboard { content: None }, cursor: mouse::Cursor::Unavailable, window: core::window::Id::unique(), cache: Some(user_interface::Cache::default()), pending_tasks: 0, }; emulator.resubscribe(program); emulator.wait_for(task); emulator } /// Updates the state of the [`Emulator`] program. /// /// This is equivalent to calling the [`Program::update`] function, /// resubscribing to any subscriptions, and running the resulting tasks /// concurrently. pub fn update(&mut self, program: &P, message: P::Message) { let task = self .runtime .enter(|| program.update(&mut self.state, message)); self.resubscribe(program); match self.mode { Mode::Zen if self.pending_tasks > 0 => self.wait_for(task), _ => { if let Some(stream) = task::into_stream(task) { self.runtime.run( stream .map(Action_::Runtime) .map(Action) .map(Event::Action) .boxed(), ); } } } } /// Performs an [`Action`]. /// /// Whenever an [`Emulator`] sends an [`Event::Action`], this /// method must be called to proceed with the execution. pub fn perform(&mut self, program: &P, action: Action<P>) { match action.0 { Action_::CountDown => { if self.pending_tasks > 0 { self.pending_tasks -= 1; if self.pending_tasks == 0 { self.runtime.send(Event::Ready); } } } Action_::Runtime(action) => match action { runtime::Action::Output(message) => { self.update(program, message); } runtime::Action::LoadFont { .. } => { // TODO } runtime::Action::Widget(operation) => { let mut user_interface = UserInterface::build( program.view(&self.state, self.window), self.size, self.cache.take().unwrap(), &mut self.renderer, ); let mut operation = Some(operation); while let Some(mut current) = operation.take() { user_interface.operate(&self.renderer, &mut current); match current.finish() { widget::operation::Outcome::None => {} widget::operation::Outcome::Some(()) => {} widget::operation::Outcome::Chain(next) => { operation = Some(next); } } } self.cache = Some(user_interface.into_cache()); } runtime::Action::Clipboard(action) => { // TODO dbg!(action); } runtime::Action::Window(action) => { use crate::runtime::window; match action { window::Action::Open(id, _settings, sender) => { self.window = id; let _ = sender.send(self.window); } window::Action::GetOldest(sender) | window::Action::GetLatest(sender) => { let _ = sender.send(Some(self.window)); } window::Action::GetSize(id, sender) => { if id == self.window { let _ = sender.send(self.size); } } window::Action::GetMaximized(id, sender) => { if id == self.window { let _ = sender.send(false); } } window::Action::GetMinimized(id, sender) => { if id == self.window { let _ = sender.send(None); } } window::Action::GetPosition(id, sender) => { if id == self.window { let _ = sender.send(Some(Point::ORIGIN)); } } window::Action::GetScaleFactor(id, sender) => { if id == self.window { let _ = sender.send(1.0); } } window::Action::GetMode(id, sender) => { if id == self.window { let _ = sender.send(core::window::Mode::Windowed); } } _ => { // Ignored } } } runtime::Action::System(action) => { // TODO dbg!(action); } iced_runtime::Action::Image(action) => { // TODO dbg!(action); } iced_runtime::Action::Tick => { // TODO } runtime::Action::Exit => { // TODO } runtime::Action::Reload => { // TODO } }, } } /// Runs an [`Instruction`]. /// /// If the [`Instruction`] executes successfully, an [`Event::Ready`] will be /// produced by the [`Emulator`]. /// /// Otherwise, an [`Event::Failed`] will be triggered. pub fn run(&mut self, program: &P, instruction: Instruction) { let mut user_interface = UserInterface::build( program.view(&self.state, self.window), self.size, self.cache.take().unwrap(), &mut self.renderer, ); let mut messages = Vec::new(); match &instruction { Instruction::Interact(interaction) => { let Some(events) = interaction.events(|target| match target { instruction::Target::Point(position) => Some(*position), instruction::Target::Text(text) => { use widget::Operation; let mut operation = Selector::find(text.as_str()); user_interface.operate( &self.renderer, &mut widget::operation::black_box(&mut operation), ); match operation.finish() { widget::operation::Outcome::Some(text) => { Some(text?.visible_bounds()?.center()) } _ => None, } } }) else { self.runtime.send(Event::Failed(instruction)); self.cache = Some(user_interface.into_cache()); return; }; for event in &events { if let core::Event::Mouse(mouse::Event::CursorMoved { position }) = event { self.cursor = mouse::Cursor::Available(*position); } } let (_state, _status) = user_interface.update( &events, self.cursor, &mut self.renderer, &mut self.clipboard, &mut messages, ); self.cache = Some(user_interface.into_cache()); let task = self.runtime.enter(|| { Task::batch( messages .into_iter() .map(|message| program.update(&mut self.state, message)), ) }); self.resubscribe(program); self.wait_for(task); } Instruction::Expect(expectation) => match expectation { instruction::Expectation::Text(text) => { use widget::Operation; let mut operation = Selector::find(text.as_str()); user_interface.operate( &self.renderer, &mut widget::operation::black_box(&mut operation), ); match operation.finish() { widget::operation::Outcome::Some(Some(_text)) => { self.runtime.send(Event::Ready); } _ => { self.runtime.send(Event::Failed(instruction)); } } self.cache = Some(user_interface.into_cache()); } }, } } fn wait_for(&mut self, task: Task<P::Message>) { if let Some(stream) = task::into_stream(task) { match self.mode { Mode::Zen => { self.pending_tasks += 1; self.runtime.run( stream .map(Action_::Runtime) .map(Action) .map(Event::Action) .chain(stream::once(async { Event::Action(Action(Action_::CountDown)) })) .boxed(), ); } Mode::Patient => { self.runtime.run( stream .map(Action_::Runtime) .map(Action) .map(Event::Action) .chain(stream::once(async { Event::Ready })) .boxed(), ); } Mode::Immediate => { self.runtime.run( stream .map(Action_::Runtime) .map(Action) .map(Event::Action) .boxed(), ); self.runtime.send(Event::Ready); } } } else if self.pending_tasks == 0 { self.runtime.send(Event::Ready); } } fn resubscribe(&mut self, program: &P) { self.runtime .track(subscription::into_recipes(self.runtime.enter(|| { program.subscription(&self.state).map(|message| { Event::Action(Action(Action_::Runtime(runtime::Action::Output(message)))) }) }))); } /// Returns the current view of the [`Emulator`]. pub fn view(&self, program: &P) -> Element<'_, P::Message, P::Theme, P::Renderer> { program.view(&self.state, self.window) } /// Returns the current theme of the [`Emulator`]. pub fn theme(&self, program: &P) -> Option<P::Theme> { program.theme(&self.state, self.window) } /// Takes a [`window::Screenshot`] of the current state of the [`Emulator`]. pub fn screenshot( &mut self, program: &P, theme: &P::Theme, scale_factor: f32, ) -> window::Screenshot { use core::renderer::Headless; let style = program.style(&self.state, theme); let mut user_interface = UserInterface::build( program.view(&self.state, self.window), self.size, self.cache.take().unwrap(), &mut self.renderer, ); // TODO: Nested redraws! let _ = user_interface.update( &[core::Event::Window(window::Event::RedrawRequested( Instant::now(), ))], mouse::Cursor::Unavailable, &mut self.renderer, &mut self.clipboard, &mut Vec::new(), ); user_interface.draw( &mut self.renderer, theme, &renderer::Style { text_color: style.text_color, }, mouse::Cursor::Unavailable, ); let physical_size = Size::new( (self.size.width * scale_factor).round() as u32, (self.size.height * scale_factor).round() as u32, ); let rgba = self .renderer .screenshot(physical_size, scale_factor, style.background_color); window::Screenshot { rgba: Bytes::from(rgba), size: physical_size, scale_factor, } } /// Turns the [`Emulator`] into its internal state. pub fn into_state(self) -> (P::State, core::window::Id) { (self.state, self.window) } } /// The strategy used by an [`Emulator`] when waiting for tasks to finish. /// /// A [`Mode`] can be used to make an [`Emulator`] wait for side effects to finish before /// continuing execution. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Mode { /// Waits for all tasks spawned by an [`Instruction`], as well as all tasks indirectly /// spawned by the the results of those tasks. /// /// This is the default. #[default] Zen, /// Waits only for the tasks directly spawned by an [`Instruction`]. Patient, /// Never waits for any tasks to finish. Immediate, } impl Mode { /// A list of all the available modes. pub const ALL: &[Self] = &[Self::Zen, Self::Patient, Self::Immediate]; } impl fmt::Display for Mode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::Zen => "Zen", Self::Patient => "Patient", Self::Immediate => "Immediate", }) } } struct Clipboard { content: Option<String>, } impl core::Clipboard for Clipboard { fn read(&self, _kind: core::clipboard::Kind) -> Option<String> { self.content.clone() } fn write(&mut self, _kind: core::clipboard::Kind, contents: String) { self.content = Some(contents); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/test/src/ice.rs
test/src/ice.rs
//! A shareable, simple format of end-to-end tests. use crate::Instruction; use crate::core::Size; use crate::emulator; use crate::instruction; /// An end-to-end test for iced applications. /// /// Ice tests encode a certain configuration together with a sequence of instructions. /// An ice test passes if all the instructions can be executed successfully. /// /// Normally, ice tests are run by an [`Emulator`](crate::Emulator) in continuous /// integration pipelines. /// /// Ice tests can be easily run by saving them as `.ice` files in a folder and simply /// calling [`run`](crate::run). These test files can be recorded by enabling the `tester` /// feature flag in the root crate. #[derive(Debug, Clone, PartialEq)] pub struct Ice { /// The viewport [`Size`] that must be used for the test. pub viewport: Size, /// The [`emulator::Mode`] that must be used for the test. pub mode: emulator::Mode, /// The name of the [`Preset`](crate::program::Preset) that must be used for the test. pub preset: Option<String>, /// The sequence of instructions of the test. pub instructions: Vec<Instruction>, } impl Ice { /// Parses an [`Ice`] test from its textual representation. /// /// Here is an example of the [`Ice`] test syntax: /// /// ```text /// viewport: 500x800 /// mode: Immediate /// preset: Empty /// ----- /// click "What needs to be done?" /// type "Create the universe" /// type enter /// type "Make an apple pie" /// type enter /// expect "2 tasks left" /// click "Create the universe" /// expect "1 task left" /// click "Make an apple pie" /// expect "0 tasks left" /// ``` /// /// This syntax is _very_ experimental and extremely likely to change often. /// For this reason, it is reserved for advanced users that want to early test it. /// /// Currently, in order to use it, you will need to earn the right and prove you understand /// its experimental nature by reading the code! pub fn parse(content: &str) -> Result<Self, ParseError> { let Some((metadata, rest)) = content.split_once("-") else { return Err(ParseError::NoMetadata); }; let mut viewport = None; let mut mode = None; let mut preset = None; for (i, line) in metadata.lines().enumerate() { if line.trim().is_empty() { continue; } let Some((field, value)) = line.split_once(':') else { return Err(ParseError::InvalidMetadata { line: i, content: line.to_owned(), }); }; match field.trim() { "viewport" => { viewport = Some( if let Some((width, height)) = value.trim().split_once('x') && let Ok(width) = width.parse() && let Ok(height) = height.parse() { Size::new(width, height) } else { return Err(ParseError::InvalidViewport { line: i, value: value.to_owned(), }); }, ); } "mode" => { mode = Some(match value.trim().to_lowercase().as_str() { "zen" => emulator::Mode::Zen, "patient" => emulator::Mode::Patient, "immediate" => emulator::Mode::Immediate, _ => { return Err(ParseError::InvalidMode { line: i, value: value.to_owned(), }); } }); } "preset" => { preset = Some(value.trim().to_owned()); } field => { return Err(ParseError::UnknownField { line: i, field: field.to_owned(), }); } } } let Some(viewport) = viewport else { return Err(ParseError::MissingViewport); }; let Some(mode) = mode else { return Err(ParseError::MissingMode); }; let instructions = rest .lines() .skip(1) .enumerate() .map(|(i, line)| { Instruction::parse(line).map_err(|error| ParseError::InvalidInstruction { line: metadata.lines().count() + 1 + i, error, }) }) .collect::<Result<Vec<_>, _>>()?; Ok(Self { viewport, mode, preset, instructions, }) } } impl std::fmt::Display for Ice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "viewport: {width}x{height}", width = self.viewport.width as u32, // TODO height = self.viewport.height as u32, // TODO )?; writeln!(f, "mode: {}", self.mode)?; if let Some(preset) = &self.preset { writeln!(f, "preset: {preset}")?; } f.write_str("-----\n")?; for instruction in &self.instructions { instruction.fmt(f)?; f.write_str("\n")?; } Ok(()) } } /// An error produced during [`Ice::parse`]. #[derive(Debug, Clone, thiserror::Error)] pub enum ParseError { /// No metadata is present. #[error("the ice test has no metadata")] NoMetadata, /// The metadata is invalid. #[error("invalid metadata in line {line}: \"{content}\"")] InvalidMetadata { /// The number of the invalid line. line: usize, /// The content of the invalid line. content: String, }, /// The viewport is invalid. #[error("invalid viewport in line {line}: \"{value}\"")] InvalidViewport { /// The number of the invalid line. line: usize, /// The invalid value. value: String, }, /// The [`emulator::Mode`] is invalid. #[error("invalid mode in line {line}: \"{value}\"")] InvalidMode { /// The number of the invalid line. line: usize, /// The invalid value. value: String, }, /// A metadata field is unknown. #[error("unknown metadata field in line {line}: \"{field}\"")] UnknownField { /// The number of the invalid line. line: usize, /// The name of the unknown field. field: String, }, /// Viewport metadata is missing. #[error("metadata is missing the viewport field")] MissingViewport, /// [`emulator::Mode`] metadata is missing. #[error("metadata is missing the mode field")] MissingMode, /// An [`Instruction`] failed to parse. #[error("invalid instruction in line {line}: {error}")] InvalidInstruction { /// The number of the invalid line. line: usize, /// The parse error. error: instruction::ParseError, }, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/lib.rs
runtime/src/lib.rs
//! A renderer-agnostic native GUI runtime. //! //! ![The native path of the Iced ecosystem](https://github.com/iced-rs/iced/blob/master/docs/graphs/native.png?raw=true) //! //! `iced_runtime` takes [`iced_core`] and builds a native runtime on top of it. //! //! [`iced_core`]: https://github.com/iced-rs/iced/tree/master/core #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] pub mod clipboard; pub mod font; pub mod image; pub mod keyboard; pub mod system; pub mod task; pub mod user_interface; pub mod widget; pub mod window; pub use iced_core as core; pub use iced_futures as futures; pub use task::Task; pub use user_interface::UserInterface; pub use window::Window; use crate::futures::futures::channel::oneshot; use std::borrow::Cow; use std::fmt; /// An action that the iced runtime can perform. pub enum Action<T> { /// Output some value. Output(T), /// Load a font from its bytes. LoadFont { /// The bytes of the font to load. bytes: Cow<'static, [u8]>, /// The channel to send back the load result. channel: oneshot::Sender<Result<(), font::Error>>, }, /// Run a widget operation. Widget(Box<dyn core::widget::Operation>), /// Run a clipboard action. Clipboard(clipboard::Action), /// Run a window action. Window(window::Action), /// Run a system action. System(system::Action), /// Run an image action. Image(image::Action), /// Poll any resources that may have pending computations. Tick, /// Recreate all user interfaces and redraw all windows. Reload, /// Exits the runtime. /// /// This will normally close any application windows and /// terminate the runtime loop. Exit, } impl<T> Action<T> { /// Creates a new [`Action::Widget`] with the given [`widget::Operation`](core::widget::Operation). pub fn widget(operation: impl core::widget::Operation + 'static) -> Self { Self::Widget(Box::new(operation)) } fn output<O>(self) -> Result<T, Action<O>> { match self { Action::Output(output) => Ok(output), Action::LoadFont { bytes, channel } => Err(Action::LoadFont { bytes, channel }), Action::Widget(operation) => Err(Action::Widget(operation)), Action::Clipboard(action) => Err(Action::Clipboard(action)), Action::Window(action) => Err(Action::Window(action)), Action::System(action) => Err(Action::System(action)), Action::Image(action) => Err(Action::Image(action)), Action::Tick => Err(Action::Tick), Action::Reload => Err(Action::Reload), Action::Exit => Err(Action::Exit), } } } impl<T> fmt::Debug for Action<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Action::Output(output) => write!(f, "Action::Output({output:?})"), Action::LoadFont { .. } => { write!(f, "Action::LoadFont") } Action::Widget { .. } => { write!(f, "Action::Widget") } Action::Clipboard(action) => { write!(f, "Action::Clipboard({action:?})") } Action::Window(_) => write!(f, "Action::Window"), Action::System(action) => write!(f, "Action::System({action:?})"), Action::Image(_) => write!(f, "Action::Image"), Action::Tick => write!(f, "Action::Tick"), Action::Reload => write!(f, "Action::Reload"), Action::Exit => write!(f, "Action::Exit"), } } } /// Creates a [`Task`] that exits the iced runtime. /// /// This will normally close any application windows and /// terminate the runtime loop. pub fn exit<T>() -> Task<T> { task::effect(Action::Exit) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/widget.rs
runtime/src/widget.rs
//! Operate on widgets and query them at runtime. pub mod operation; #[cfg(feature = "selector")] pub mod selector;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/image.rs
runtime/src/image.rs
//! Allocate images explicitly to control presentation. use crate::core::image::Handle; use crate::futures::futures::channel::oneshot; use crate::task::{self, Task}; pub use crate::core::image::{Allocation, Error}; /// An image action. #[derive(Debug)] pub enum Action { /// Allocates the given [`Handle`]. Allocate(Handle, oneshot::Sender<Result<Allocation, Error>>), } /// Allocates an image [`Handle`]. /// /// When you obtain an [`Allocation`] explicitly, you get the guarantee /// that using a [`Handle`] will draw the corresponding image immediately /// in the next frame. pub fn allocate(handle: impl Into<Handle>) -> Task<Result<Allocation, Error>> { task::oneshot(|sender| crate::Action::Image(Action::Allocate(handle.into(), sender))) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/clipboard.rs
runtime/src/clipboard.rs
//! Access the clipboard. use crate::core::clipboard::Kind; use crate::futures::futures::channel::oneshot; use crate::task::{self, Task}; /// A clipboard action to be performed by some [`Task`]. /// /// [`Task`]: crate::Task #[derive(Debug)] pub enum Action { /// Read the clipboard and produce `T` with the result. Read { /// The clipboard target. target: Kind, /// The channel to send the read contents. channel: oneshot::Sender<Option<String>>, }, /// Write the given contents to the clipboard. Write { /// The clipboard target. target: Kind, /// The contents to be written. contents: String, }, } /// Read the current contents of the clipboard. pub fn read() -> Task<Option<String>> { task::oneshot(|channel| { crate::Action::Clipboard(Action::Read { target: Kind::Standard, channel, }) }) } /// Read the current contents of the primary clipboard. pub fn read_primary() -> Task<Option<String>> { task::oneshot(|channel| { crate::Action::Clipboard(Action::Read { target: Kind::Primary, channel, }) }) } /// Write the given contents to the clipboard. pub fn write<T>(contents: String) -> Task<T> { task::effect(crate::Action::Clipboard(Action::Write { target: Kind::Standard, contents, })) } /// Write the given contents to the primary clipboard. pub fn write_primary<Message>(contents: String) -> Task<Message> { task::effect(crate::Action::Clipboard(Action::Write { target: Kind::Primary, contents, })) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/font.rs
runtime/src/font.rs
//! Load and use fonts. use crate::Action; use crate::task::{self, Task}; use std::borrow::Cow; /// An error while loading a font. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Error {} /// Load a font from its bytes. pub fn load(bytes: impl Into<Cow<'static, [u8]>>) -> Task<Result<(), Error>> { task::oneshot(|channel| Action::LoadFont { bytes: bytes.into(), channel, }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/user_interface.rs
runtime/src/user_interface.rs
//! Implement your own event loop to drive a user interface. use crate::core::event::{self, Event}; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::window; use crate::core::{Clipboard, Element, InputMethod, Layout, Rectangle, Shell, Size, Vector}; /// A set of interactive graphical elements with a specific [`Layout`]. /// /// It can be updated and drawn. /// /// Iced tries to avoid dictating how to write your event loop. You are in /// charge of using this type in your system in any way you want. /// /// # Example /// The [`integration`] example uses a [`UserInterface`] to integrate Iced in an /// existing graphical application. /// /// [`integration`]: https://github.com/iced-rs/iced/tree/master/examples/integration pub struct UserInterface<'a, Message, Theme, Renderer> { root: Element<'a, Message, Theme, Renderer>, base: layout::Node, state: widget::Tree, overlay: Option<Overlay>, bounds: Size, } struct Overlay { layout: layout::Node, interaction: mouse::Interaction, } impl<'a, Message, Theme, Renderer> UserInterface<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Builds a user interface for an [`Element`]. /// /// It is able to avoid expensive computations when using a [`Cache`] /// obtained from a previous instance of a [`UserInterface`]. /// /// # Example /// Imagine we want to build a [`UserInterface`] for /// [the counter example that we previously wrote](index.html#usage). Here /// is naive way to set up our application loop: /// /// ```no_run /// # mod iced_wgpu { /// # pub type Renderer = (); /// # } /// # /// # pub struct Counter; /// # /// # impl Counter { /// # pub fn new() -> Self { Counter } /// # pub fn view(&self) -> iced_core::Element<(), (), Renderer> { unimplemented!() } /// # pub fn update(&mut self, _: ()) {} /// # } /// use iced_runtime::core::Size; /// use iced_runtime::user_interface::{self, UserInterface}; /// use iced_wgpu::Renderer; /// /// // Initialization /// let mut counter = Counter::new(); /// let mut cache = user_interface::Cache::new(); /// let mut renderer = Renderer::default(); /// let mut window_size = Size::new(1024.0, 768.0); /// /// // Application loop /// loop { /// // Process system events here... /// /// // Build the user interface /// let user_interface = UserInterface::build( /// counter.view(), /// window_size, /// cache, /// &mut renderer, /// ); /// /// // Update and draw the user interface here... /// // ... /// /// // Obtain the cache for the next iteration /// cache = user_interface.into_cache(); /// } /// ``` pub fn build<E: Into<Element<'a, Message, Theme, Renderer>>>( root: E, bounds: Size, cache: Cache, renderer: &mut Renderer, ) -> Self { let mut root = root.into(); let Cache { mut state } = cache; state.diff(root.as_widget()); let base = root.as_widget_mut().layout( &mut state, renderer, &layout::Limits::new(Size::ZERO, bounds), ); UserInterface { root, base, state, overlay: None, bounds, } } /// Updates the [`UserInterface`] by processing each provided [`Event`]. /// /// It returns __messages__ that may have been produced as a result of user /// interactions. You should feed these to your __update logic__. /// /// # Example /// Let's allow our [counter](index.html#usage) to change state by /// completing [the previous example](#example): /// /// ```no_run /// # mod iced_wgpu { /// # pub type Renderer = (); /// # } /// # /// # pub struct Counter; /// # /// # impl Counter { /// # pub fn new() -> Self { Counter } /// # pub fn view(&self) -> iced_core::Element<(), (), Renderer> { unimplemented!() } /// # pub fn update(&mut self, _: ()) {} /// # } /// use iced_runtime::core::clipboard; /// use iced_runtime::core::mouse; /// use iced_runtime::core::Size; /// use iced_runtime::user_interface::{self, UserInterface}; /// use iced_wgpu::Renderer; /// /// let mut counter = Counter::new(); /// let mut cache = user_interface::Cache::new(); /// let mut renderer = Renderer::default(); /// let mut window_size = Size::new(1024.0, 768.0); /// let mut cursor = mouse::Cursor::default(); /// let mut clipboard = clipboard::Null; /// /// // Initialize our event storage /// let mut events = Vec::new(); /// let mut messages = Vec::new(); /// /// loop { /// // Obtain system events... /// /// let mut user_interface = UserInterface::build( /// counter.view(), /// window_size, /// cache, /// &mut renderer, /// ); /// /// // Update the user interface /// let (state, event_statuses) = user_interface.update( /// &events, /// cursor, /// &mut renderer, /// &mut clipboard, /// &mut messages /// ); /// /// cache = user_interface.into_cache(); /// /// // Process the produced messages /// for message in messages.drain(..) { /// counter.update(message); /// } /// } /// ``` pub fn update( &mut self, events: &[Event], cursor: mouse::Cursor, renderer: &mut Renderer, clipboard: &mut dyn Clipboard, messages: &mut Vec<Message>, ) -> (State, Vec<event::Status>) { let mut outdated = false; let mut redraw_request = window::RedrawRequest::Wait; let mut input_method = InputMethod::Disabled; let mut has_layout_changed = false; let viewport = Rectangle::with_size(self.bounds); let mut maybe_overlay = self .root .as_widget_mut() .overlay( &mut self.state, Layout::new(&self.base), renderer, &viewport, Vector::ZERO, ) .map(overlay::Nested::new); let (base_cursor, overlay_statuses, overlay_interaction) = if maybe_overlay.is_some() { let bounds = self.bounds; let mut overlay = maybe_overlay.as_mut().unwrap(); let mut layout = overlay.layout(renderer, bounds); let mut event_statuses = Vec::new(); for event in events { let mut shell = Shell::new(messages); overlay.update( event, Layout::new(&layout), cursor, renderer, clipboard, &mut shell, ); event_statuses.push(shell.event_status()); redraw_request = redraw_request.min(shell.redraw_request()); input_method.merge(shell.input_method()); if shell.is_layout_invalid() { drop(maybe_overlay); self.base = self.root.as_widget_mut().layout( &mut self.state, renderer, &layout::Limits::new(Size::ZERO, self.bounds), ); maybe_overlay = self .root .as_widget_mut() .overlay( &mut self.state, Layout::new(&self.base), renderer, &viewport, Vector::ZERO, ) .map(overlay::Nested::new); if maybe_overlay.is_none() { break; } overlay = maybe_overlay.as_mut().unwrap(); shell.revalidate_layout(|| { layout = overlay.layout(renderer, bounds); has_layout_changed = true; }); } if shell.are_widgets_invalid() { outdated = true; } } let (base_cursor, interaction) = if let Some(overlay) = maybe_overlay.as_mut() { let interaction = cursor .position() .map(|cursor_position| { overlay.mouse_interaction( Layout::new(&layout), mouse::Cursor::Available(cursor_position), renderer, ) }) .unwrap_or_default(); if interaction == mouse::Interaction::None { (cursor, mouse::Interaction::None) } else { (mouse::Cursor::Unavailable, interaction) } } else { (cursor, mouse::Interaction::None) }; self.overlay = Some(Overlay { layout, interaction, }); (base_cursor, event_statuses, interaction) } else { ( cursor, vec![event::Status::Ignored; events.len()], mouse::Interaction::None, ) }; drop(maybe_overlay); let event_statuses = events .iter() .zip(overlay_statuses) .map(|(event, overlay_status)| { if matches!(overlay_status, event::Status::Captured) { return overlay_status; } let mut shell = Shell::new(messages); self.root.as_widget_mut().update( &mut self.state, event, Layout::new(&self.base), base_cursor, renderer, clipboard, &mut shell, &viewport, ); if shell.event_status() == event::Status::Captured { self.overlay = None; } redraw_request = redraw_request.min(shell.redraw_request()); input_method.merge(shell.input_method()); shell.revalidate_layout(|| { has_layout_changed = true; self.base = self.root.as_widget_mut().layout( &mut self.state, renderer, &layout::Limits::new(Size::ZERO, self.bounds), ); if let Some(mut overlay) = self .root .as_widget_mut() .overlay( &mut self.state, Layout::new(&self.base), renderer, &viewport, Vector::ZERO, ) .map(overlay::Nested::new) { let layout = overlay.layout(renderer, self.bounds); let interaction = overlay.mouse_interaction(Layout::new(&layout), cursor, renderer); self.overlay = Some(Overlay { layout, interaction, }); } }); if shell.are_widgets_invalid() { outdated = true; } shell.event_status().merge(overlay_status) }) .collect(); let mouse_interaction = if overlay_interaction == mouse::Interaction::None { self.root.as_widget().mouse_interaction( &self.state, Layout::new(&self.base), base_cursor, &viewport, renderer, ) } else { overlay_interaction }; ( if outdated { State::Outdated } else { State::Updated { mouse_interaction, redraw_request, input_method, has_layout_changed, } }, event_statuses, ) } /// Draws the [`UserInterface`] with the provided [`Renderer`]. /// /// It returns the current [`mouse::Interaction`]. You should update the /// icon of the mouse cursor accordingly in your system. /// /// [`Renderer`]: crate::core::Renderer /// /// # Example /// We can finally draw our [counter](index.html#usage) by /// [completing the last example](#example-1): /// /// ```no_run /// # mod iced_wgpu { /// # pub type Renderer = (); /// # pub type Theme = (); /// # } /// # /// # pub struct Counter; /// # /// # impl Counter { /// # pub fn new() -> Self { Counter } /// # pub fn view(&self) -> Element<(), (), Renderer> { unimplemented!() } /// # pub fn update(&mut self, _: ()) {} /// # } /// use iced_runtime::core::clipboard; /// use iced_runtime::core::mouse; /// use iced_runtime::core::renderer; /// use iced_runtime::core::{Element, Size}; /// use iced_runtime::user_interface::{self, UserInterface}; /// use iced_wgpu::{Renderer, Theme}; /// /// let mut counter = Counter::new(); /// let mut cache = user_interface::Cache::new(); /// let mut renderer = Renderer::default(); /// let mut window_size = Size::new(1024.0, 768.0); /// let mut cursor = mouse::Cursor::default(); /// let mut clipboard = clipboard::Null; /// let mut events = Vec::new(); /// let mut messages = Vec::new(); /// let mut theme = Theme::default(); /// /// loop { /// // Obtain system events... /// /// let mut user_interface = UserInterface::build( /// counter.view(), /// window_size, /// cache, /// &mut renderer, /// ); /// /// // Update the user interface /// let event_statuses = user_interface.update( /// &events, /// cursor, /// &mut renderer, /// &mut clipboard, /// &mut messages /// ); /// /// // Draw the user interface /// let mouse_interaction = user_interface.draw(&mut renderer, &theme, &renderer::Style::default(), cursor); /// /// cache = user_interface.into_cache(); /// /// for message in messages.drain(..) { /// counter.update(message); /// } /// /// // Update mouse cursor icon... /// // Flush rendering operations... /// } /// ``` pub fn draw( &mut self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, cursor: mouse::Cursor, ) { let viewport = Rectangle::with_size(self.bounds); renderer.reset(viewport); let base_cursor = match &self.overlay { None | Some(Overlay { interaction: mouse::Interaction::None, .. }) => cursor, _ => mouse::Cursor::Unavailable, }; self.root.as_widget().draw( &self.state, renderer, theme, style, Layout::new(&self.base), base_cursor, &viewport, ); let Self { overlay, root, base, .. } = self; let Some(Overlay { layout, .. }) = overlay.as_ref() else { return; }; let overlay = root .as_widget_mut() .overlay( &mut self.state, Layout::new(base), renderer, &viewport, Vector::ZERO, ) .map(overlay::Nested::new); if let Some(mut overlay) = overlay { overlay.draw(renderer, theme, style, Layout::new(layout), cursor); } } /// Applies a [`widget::Operation`] to the [`UserInterface`]. pub fn operate(&mut self, renderer: &Renderer, operation: &mut dyn widget::Operation) { let viewport = Rectangle::with_size(self.bounds); self.root.as_widget_mut().operate( &mut self.state, Layout::new(&self.base), renderer, operation, ); if let Some(mut overlay) = self .root .as_widget_mut() .overlay( &mut self.state, Layout::new(&self.base), renderer, &viewport, Vector::ZERO, ) .map(overlay::Nested::new) { if self.overlay.is_none() { self.overlay = Some(Overlay { layout: overlay.layout(renderer, self.bounds), interaction: mouse::Interaction::None, }); } overlay.operate( Layout::new(&self.overlay.as_ref().unwrap().layout), renderer, operation, ); } } /// Relayouts and returns a new [`UserInterface`] using the provided /// bounds. pub fn relayout(self, bounds: Size, renderer: &mut Renderer) -> Self { Self::build(self.root, bounds, Cache { state: self.state }, renderer) } /// Extract the [`Cache`] of the [`UserInterface`], consuming it in the /// process. pub fn into_cache(self) -> Cache { Cache { state: self.state } } } /// Reusable data of a specific [`UserInterface`]. #[derive(Debug)] pub struct Cache { state: widget::Tree, } impl Cache { /// Creates an empty [`Cache`]. /// /// You should use this to initialize a [`Cache`] before building your first /// [`UserInterface`]. pub fn new() -> Cache { Cache { state: widget::Tree::empty(), } } } impl Default for Cache { fn default() -> Cache { Cache::new() } } /// The resulting state after updating a [`UserInterface`]. #[derive(Debug, Clone)] pub enum State { /// The [`UserInterface`] is outdated and needs to be rebuilt. Outdated, /// The [`UserInterface`] is up-to-date and can be reused without /// rebuilding. Updated { /// The current [`mouse::Interaction`] of the user interface. mouse_interaction: mouse::Interaction, /// The [`window::RedrawRequest`] describing when a redraw should be performed. redraw_request: window::RedrawRequest, /// The current [`InputMethod`] strategy of the user interface. input_method: InputMethod, /// Whether the layout of the [`UserInterface`] has changed. has_layout_changed: bool, }, } impl State { /// Returns whether the layout of the [`UserInterface`] has changed. pub fn has_layout_changed(&self) -> bool { match self { State::Outdated => true, State::Updated { has_layout_changed, .. } => *has_layout_changed, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/system.rs
runtime/src/system.rs
//! Access the native system. use crate::core::theme; use crate::futures::futures::channel::oneshot; use crate::futures::subscription::{self, Subscription}; use crate::task::{self, Task}; /// An operation to be performed on the system. #[derive(Debug)] pub enum Action { /// Send available system information. GetInformation(oneshot::Sender<Information>), /// Send the current system theme mode. GetTheme(oneshot::Sender<theme::Mode>), /// Notify to the runtime that the system theme has changed. NotifyTheme(theme::Mode), } /// Contains information about the system (e.g. system name, processor, memory, graphics adapter). #[derive(Clone, Debug)] pub struct Information { /// The operating system name pub system_name: Option<String>, /// Operating system kernel version pub system_kernel: Option<String>, /// Long operating system version /// /// Examples: /// - MacOS 10.15 Catalina /// - Windows 10 Pro /// - Ubuntu 20.04 LTS (Focal Fossa) pub system_version: Option<String>, /// Short operating system version number pub system_short_version: Option<String>, /// Detailed processor model information pub cpu_brand: String, /// The number of physical cores on the processor pub cpu_cores: Option<usize>, /// Total RAM size, in bytes pub memory_total: u64, /// Memory used by this process, in bytes pub memory_used: Option<u64>, /// Underlying graphics backend for rendering pub graphics_backend: String, /// Model information for the active graphics adapter pub graphics_adapter: String, } /// Returns available system information. pub fn information() -> Task<Information> { task::oneshot(|channel| crate::Action::System(Action::GetInformation(channel))) } /// Returns the current system theme. pub fn theme() -> Task<theme::Mode> { task::oneshot(|sender| crate::Action::System(Action::GetTheme(sender))) } /// Subscribes to system theme changes. pub fn theme_changes() -> Subscription<theme::Mode> { #[derive(Hash)] struct ThemeChanges; subscription::filter_map(ThemeChanges, |event| { let subscription::Event::SystemThemeChanged(mode) = event else { return None; }; Some(mode) }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/window.rs
runtime/src/window.rs
//! Build window-based GUI applications. use crate::core::time::Instant; use crate::core::window::{ Direction, Event, Icon, Id, Level, Mode, Screenshot, Settings, UserAttention, }; use crate::core::{Point, Size}; use crate::futures::Subscription; use crate::futures::event; use crate::futures::futures::channel::oneshot; use crate::task::{self, Task}; pub use raw_window_handle; use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; /// An operation to be performed on some window. pub enum Action { /// Open a new window with some [`Settings`]. Open(Id, Settings, oneshot::Sender<Id>), /// Close the window and exits the application. Close(Id), /// Gets the [`Id`] of the oldest window. GetOldest(oneshot::Sender<Option<Id>>), /// Gets the [`Id`] of the latest window. GetLatest(oneshot::Sender<Option<Id>>), /// Move the window with the left mouse button until the button is /// released. /// /// There's no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. Drag(Id), /// Resize the window with the left mouse button until the button is /// released. /// /// There's no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. DragResize(Id, Direction), /// Resize the window to the given logical dimensions. Resize(Id, Size), /// Get the current logical dimensions of the window. GetSize(Id, oneshot::Sender<Size>), /// Get if the current window is maximized or not. GetMaximized(Id, oneshot::Sender<bool>), /// Set the window to maximized or back Maximize(Id, bool), /// Get if the current window is minimized or not. /// /// ## Platform-specific /// - **Wayland:** Always `None`. GetMinimized(Id, oneshot::Sender<Option<bool>>), /// Set the window to minimized or back Minimize(Id, bool), /// Get the current logical coordinates of the window. GetPosition(Id, oneshot::Sender<Option<Point>>), /// Get the current scale factor (DPI) of the window. GetScaleFactor(Id, oneshot::Sender<f32>), /// Move the window to the given logical coordinates. /// /// Unsupported on Wayland. Move(Id, Point), /// Change the [`Mode`] of the window. SetMode(Id, Mode), /// Get the current [`Mode`] of the window. GetMode(Id, oneshot::Sender<Mode>), /// Toggle the window to maximized or back ToggleMaximize(Id), /// Toggle whether window has decorations. /// /// ## Platform-specific /// - **X11:** Not implemented. /// - **Web:** Unsupported. ToggleDecorations(Id), /// Request user attention to the window, this has no effect if the application /// is already focused. How requesting for user attention manifests is platform dependent, /// see [`UserAttention`] for details. /// /// Providing `None` will unset the request for user attention. Unsetting the request for /// user attention might not be done automatically by the WM when the window receives input. /// /// ## Platform-specific /// /// - **iOS / Android / Web:** Unsupported. /// - **macOS:** `None` has no effect. /// - **X11:** Requests for user attention must be manually cleared. /// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect. RequestUserAttention(Id, Option<UserAttention>), /// Bring the window to the front and sets input focus. Has no effect if the window is /// already in focus, minimized, or not visible. /// /// This method steals input focus from other applications. Do not use this method unless /// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive /// user experience. /// /// ## Platform-specific /// /// - **Web / Wayland:** Unsupported. GainFocus(Id), /// Change the window [`Level`]. SetLevel(Id, Level), /// Show the system menu at cursor position. /// /// ## Platform-specific /// Android / iOS / macOS / Orbital / Web / X11: Unsupported. ShowSystemMenu(Id), /// Get the raw identifier unique to the window. GetRawId(Id, oneshot::Sender<u64>), /// Change the window [`Icon`]. /// /// On Windows and X11, this is typically the small icon in the top-left /// corner of the titlebar. /// /// ## Platform-specific /// /// - **Web / Wayland / macOS:** Unsupported. /// /// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. /// /// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. That /// said, it's usually in the same ballpark as on Windows. SetIcon(Id, Icon), /// Runs the closure with a reference to the [`Window`] with the given [`Id`]. Run(Id, Box<dyn FnOnce(&dyn Window) + Send>), /// Screenshot the viewport of the window. Screenshot(Id, oneshot::Sender<Screenshot>), /// Enable mouse passthrough for the given window. /// /// This disables mouse events for the window and passes mouse events /// through to whatever window is underneath. EnableMousePassthrough(Id), /// Disable mouse passthrough for the given window. /// /// This enables mouse events for the window and stops mouse events /// from being passed to whatever is underneath. DisableMousePassthrough(Id), /// Set the minimum inner window size. SetMinSize(Id, Option<Size>), /// Set the maximum inner window size. SetMaxSize(Id, Option<Size>), /// Set the window to be resizable or not. SetResizable(Id, bool), /// Set the window size increment. SetResizeIncrements(Id, Option<Size>), /// Get the logical dimensions of the monitor containing the window with the given [`Id`]. GetMonitorSize(Id, oneshot::Sender<Option<Size>>), /// Set whether the system can automatically organize windows into tabs. /// /// See <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing> SetAllowAutomaticTabbing(bool), /// Redraw all the windows. RedrawAll, /// Recompute the layouts of all the windows. RelayoutAll, } /// A window managed by iced. /// /// It implements both [`HasWindowHandle`] and [`HasDisplayHandle`]. pub trait Window: HasWindowHandle + HasDisplayHandle {} impl<T> Window for T where T: HasWindowHandle + HasDisplayHandle {} /// Subscribes to the frames of the window of the running application. /// /// The resulting [`Subscription`] will produce items at a rate equal to the /// refresh rate of the first application window. Note that this rate may be variable, as it is /// normally managed by the graphics driver and/or the OS. /// /// In any case, this [`Subscription`] is useful to smoothly draw application-driven /// animations without missing any frames. pub fn frames() -> Subscription<Instant> { event::listen_raw(|event, _status, _window| match event { crate::core::Event::Window(Event::RedrawRequested(at)) => Some(at), _ => None, }) } /// Subscribes to all window events of the running application. pub fn events() -> Subscription<(Id, Event)> { event::listen_with(|event, _status, id| { if let crate::core::Event::Window(event) = event { Some((id, event)) } else { None } }) } /// Subscribes to all [`Event::Opened`] occurrences in the running application. pub fn open_events() -> Subscription<Id> { event::listen_with(|event, _status, id| { if let crate::core::Event::Window(Event::Opened { .. }) = event { Some(id) } else { None } }) } /// Subscribes to all [`Event::Closed`] occurrences in the running application. pub fn close_events() -> Subscription<Id> { event::listen_with(|event, _status, id| { if let crate::core::Event::Window(Event::Closed) = event { Some(id) } else { None } }) } /// Subscribes to all [`Event::Resized`] occurrences in the running application. pub fn resize_events() -> Subscription<(Id, Size)> { event::listen_with(|event, _status, id| { if let crate::core::Event::Window(Event::Resized(size)) = event { Some((id, size)) } else { None } }) } /// Subscribes to all [`Event::CloseRequested`] occurrences in the running application. pub fn close_requests() -> Subscription<Id> { event::listen_with(|event, _status, id| { if let crate::core::Event::Window(Event::CloseRequested) = event { Some(id) } else { None } }) } /// Opens a new window with the given [`Settings`]; producing the [`Id`] /// of the new window on completion. pub fn open(settings: Settings) -> (Id, Task<Id>) { let id = Id::unique(); ( id, task::oneshot(|channel| crate::Action::Window(Action::Open(id, settings, channel))), ) } /// Closes the window with `id`. pub fn close<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::Close(id))) } /// Gets the window [`Id`] of the oldest window. pub fn oldest() -> Task<Option<Id>> { task::oneshot(|channel| crate::Action::Window(Action::GetOldest(channel))) } /// Gets the window [`Id`] of the latest window. pub fn latest() -> Task<Option<Id>> { task::oneshot(|channel| crate::Action::Window(Action::GetLatest(channel))) } /// Begins dragging the window while the left mouse button is held. pub fn drag<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::Drag(id))) } /// Begins resizing the window while the left mouse button is held. pub fn drag_resize<T>(id: Id, direction: Direction) -> Task<T> { task::effect(crate::Action::Window(Action::DragResize(id, direction))) } /// Resizes the window to the given logical dimensions. pub fn resize<T>(id: Id, new_size: Size) -> Task<T> { task::effect(crate::Action::Window(Action::Resize(id, new_size))) } /// Set the window to be resizable or not. pub fn set_resizable<T>(id: Id, resizable: bool) -> Task<T> { task::effect(crate::Action::Window(Action::SetResizable(id, resizable))) } /// Set the inner maximum size of the window. pub fn set_max_size<T>(id: Id, size: Option<Size>) -> Task<T> { task::effect(crate::Action::Window(Action::SetMaxSize(id, size))) } /// Set the inner minimum size of the window. pub fn set_min_size<T>(id: Id, size: Option<Size>) -> Task<T> { task::effect(crate::Action::Window(Action::SetMinSize(id, size))) } /// Set the window size increment. /// /// This is usually used by apps such as terminal emulators that need "blocky" resizing. pub fn set_resize_increments<T>(id: Id, increments: Option<Size>) -> Task<T> { task::effect(crate::Action::Window(Action::SetResizeIncrements( id, increments, ))) } /// Gets the window size in logical dimensions. pub fn size(id: Id) -> Task<Size> { task::oneshot(move |channel| crate::Action::Window(Action::GetSize(id, channel))) } /// Gets the maximized state of the window with the given [`Id`]. pub fn is_maximized(id: Id) -> Task<bool> { task::oneshot(move |channel| crate::Action::Window(Action::GetMaximized(id, channel))) } /// Maximizes the window. pub fn maximize<T>(id: Id, maximized: bool) -> Task<T> { task::effect(crate::Action::Window(Action::Maximize(id, maximized))) } /// Gets the minimized state of the window with the given [`Id`]. pub fn is_minimized(id: Id) -> Task<Option<bool>> { task::oneshot(move |channel| crate::Action::Window(Action::GetMinimized(id, channel))) } /// Minimizes the window. pub fn minimize<T>(id: Id, minimized: bool) -> Task<T> { task::effect(crate::Action::Window(Action::Minimize(id, minimized))) } /// Gets the position in logical coordinates of the window with the given [`Id`]. pub fn position(id: Id) -> Task<Option<Point>> { task::oneshot(move |channel| crate::Action::Window(Action::GetPosition(id, channel))) } /// Gets the scale factor of the window with the given [`Id`]. pub fn scale_factor(id: Id) -> Task<f32> { task::oneshot(move |channel| crate::Action::Window(Action::GetScaleFactor(id, channel))) } /// Moves the window to the given logical coordinates. pub fn move_to<T>(id: Id, position: Point) -> Task<T> { task::effect(crate::Action::Window(Action::Move(id, position))) } /// Gets the current [`Mode`] of the window. pub fn mode(id: Id) -> Task<Mode> { task::oneshot(move |channel| crate::Action::Window(Action::GetMode(id, channel))) } /// Changes the [`Mode`] of the window. pub fn set_mode<T>(id: Id, mode: Mode) -> Task<T> { task::effect(crate::Action::Window(Action::SetMode(id, mode))) } /// Toggles the window to maximized or back. pub fn toggle_maximize<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::ToggleMaximize(id))) } /// Toggles the window decorations. pub fn toggle_decorations<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::ToggleDecorations(id))) } /// Requests user attention to the window. This has no effect if the application /// is already focused. How requesting for user attention manifests is platform dependent, /// see [`UserAttention`] for details. /// /// Providing `None` will unset the request for user attention. Unsetting the request for /// user attention might not be done automatically by the WM when the window receives input. pub fn request_user_attention<T>(id: Id, user_attention: Option<UserAttention>) -> Task<T> { task::effect(crate::Action::Window(Action::RequestUserAttention( id, user_attention, ))) } /// Brings the window to the front and sets input focus. Has no effect if the window is /// already in focus, minimized, or not visible. /// /// This [`Task`] steals input focus from other applications. Do not use this method unless /// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive /// user experience. pub fn gain_focus<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::GainFocus(id))) } /// Changes the window [`Level`]. pub fn set_level<T>(id: Id, level: Level) -> Task<T> { task::effect(crate::Action::Window(Action::SetLevel(id, level))) } /// Shows the [system menu] at cursor position. /// /// [system menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu pub fn show_system_menu<T>(id: Id) -> Task<T> { task::effect(crate::Action::Window(Action::ShowSystemMenu(id))) } /// Gets an identifier unique to the window, provided by the underlying windowing system. This is /// not to be confused with [`Id`]. pub fn raw_id<Message>(id: Id) -> Task<u64> { task::oneshot(|channel| crate::Action::Window(Action::GetRawId(id, channel))) } /// Changes the [`Icon`] of the window. pub fn set_icon<T>(id: Id, icon: Icon) -> Task<T> { task::effect(crate::Action::Window(Action::SetIcon(id, icon))) } /// Runs the given callback with a reference to the [`Window`] with the given [`Id`]. /// /// Note that if the window closes before this call is processed the callback will not be run. pub fn run<T>(id: Id, f: impl FnOnce(&dyn Window) -> T + Send + 'static) -> Task<T> where T: Send + 'static, { task::oneshot(move |channel| { crate::Action::Window(Action::Run( id, Box::new(move |handle| { let _ = channel.send(f(handle)); }), )) }) } /// Captures a [`Screenshot`] from the window. pub fn screenshot(id: Id) -> Task<Screenshot> { task::oneshot(move |channel| crate::Action::Window(Action::Screenshot(id, channel))) } /// Enables mouse passthrough for the given window. /// /// This disables mouse events for the window and passes mouse events /// through to whatever window is underneath. pub fn enable_mouse_passthrough<Message>(id: Id) -> Task<Message> { task::effect(crate::Action::Window(Action::EnableMousePassthrough(id))) } /// Disables mouse passthrough for the given window. /// /// This enables mouse events for the window and stops mouse events /// from being passed to whatever is underneath. pub fn disable_mouse_passthrough<Message>(id: Id) -> Task<Message> { task::effect(crate::Action::Window(Action::DisableMousePassthrough(id))) } /// Gets the logical dimensions of the monitor containing the window with the given [`Id`]. pub fn monitor_size(id: Id) -> Task<Option<Size>> { task::oneshot(move |channel| crate::Action::Window(Action::GetMonitorSize(id, channel))) } /// Sets whether the system can automatically organize windows into tabs. /// /// See <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing> pub fn allow_automatic_tabbing<T>(enabled: bool) -> Task<T> { task::effect(crate::Action::Window(Action::SetAllowAutomaticTabbing( enabled, ))) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/task.rs
runtime/src/task.rs
//! Create runtime tasks. use crate::Action; use crate::core::widget; use crate::futures::futures::channel::mpsc; use crate::futures::futures::channel::oneshot; use crate::futures::futures::future::{self, FutureExt}; use crate::futures::futures::stream::{self, Stream, StreamExt}; use crate::futures::{BoxStream, MaybeSend, boxed_stream}; use std::convert::Infallible; use std::pin::Pin; use std::sync::Arc; use std::task; use std::thread; #[cfg(feature = "sipper")] #[doc(no_inline)] pub use sipper::{Never, Sender, Sipper, Straw, sipper, stream}; /// A set of concurrent actions to be performed by the iced runtime. /// /// A [`Task`] _may_ produce a bunch of values of type `T`. #[must_use = "`Task` must be returned to the runtime to take effect; normally in your `update` or `new` functions."] pub struct Task<T> { stream: Option<BoxStream<Action<T>>>, units: usize, } impl<T> Task<T> { /// Creates a [`Task`] that does nothing. pub fn none() -> Self { Self { stream: None, units: 0, } } /// Creates a new [`Task`] that instantly produces the given value. pub fn done(value: T) -> Self where T: MaybeSend + 'static, { Self::future(future::ready(value)) } /// Creates a [`Task`] that runs the given [`Future`] to completion and maps its /// output with the given closure. pub fn perform<A>( future: impl Future<Output = A> + MaybeSend + 'static, f: impl FnOnce(A) -> T + MaybeSend + 'static, ) -> Self where T: MaybeSend + 'static, A: MaybeSend + 'static, { Self::future(future.map(f)) } /// Creates a [`Task`] that runs the given [`Stream`] to completion and maps each /// item with the given closure. pub fn run<A>( stream: impl Stream<Item = A> + MaybeSend + 'static, f: impl Fn(A) -> T + MaybeSend + 'static, ) -> Self where T: 'static, { Self::stream(stream.map(f)) } /// Creates a [`Task`] that runs the given [`Sipper`] to completion, mapping /// progress with the first closure and the output with the second one. #[cfg(feature = "sipper")] pub fn sip<S>( sipper: S, on_progress: impl FnMut(S::Progress) -> T + MaybeSend + 'static, on_output: impl FnOnce(<S as Future>::Output) -> T + MaybeSend + 'static, ) -> Self where S: sipper::Core + MaybeSend + 'static, T: MaybeSend + 'static, { Self::stream(stream(sipper::sipper(move |sender| async move { on_output(sipper.with(on_progress).run(sender).await) }))) } /// Combines the given tasks and produces a single [`Task`] that will run all of them /// in parallel. pub fn batch(tasks: impl IntoIterator<Item = Self>) -> Self where T: 'static, { let mut select_all = stream::SelectAll::new(); let mut units = 0; for task in tasks.into_iter() { if let Some(stream) = task.stream { select_all.push(stream); } units += task.units; } Self { stream: Some(boxed_stream(select_all)), units, } } /// Maps the output of a [`Task`] with the given closure. pub fn map<O>(self, mut f: impl FnMut(T) -> O + MaybeSend + 'static) -> Task<O> where T: MaybeSend + 'static, O: MaybeSend + 'static, { self.then(move |output| Task::done(f(output))) } /// Performs a new [`Task`] for every output of the current [`Task`] using the /// given closure. /// /// This is the monadic interface of [`Task`]—analogous to [`Future`] and /// [`Stream`]. pub fn then<O>(self, mut f: impl FnMut(T) -> Task<O> + MaybeSend + 'static) -> Task<O> where T: MaybeSend + 'static, O: MaybeSend + 'static, { Task { stream: match self.stream { None => None, Some(stream) => Some(boxed_stream(stream.flat_map(move |action| { match action.output() { Ok(output) => f(output) .stream .unwrap_or_else(|| boxed_stream(stream::empty())), Err(action) => boxed_stream(stream::once(async move { action })), } }))), }, units: self.units, } } /// Chains a new [`Task`] to be performed once the current one finishes completely. pub fn chain(self, task: Self) -> Self where T: 'static, { match self.stream { None => task, Some(first) => match task.stream { None => Self { stream: Some(first), units: self.units, }, Some(second) => Self { stream: Some(boxed_stream(first.chain(second))), units: self.units + task.units, }, }, } } /// Creates a new [`Task`] that collects all the output of the current one into a [`Vec`]. pub fn collect(self) -> Task<Vec<T>> where T: MaybeSend + 'static, { match self.stream { None => Task::done(Vec::new()), Some(stream) => Task { stream: Some(boxed_stream( stream::unfold( (stream, Some(Vec::new())), move |(mut stream, outputs)| async move { let mut outputs = outputs?; let Some(action) = stream.next().await else { return Some((Some(Action::Output(outputs)), (stream, None))); }; match action.output() { Ok(output) => { outputs.push(output); Some((None, (stream, Some(outputs)))) } Err(action) => Some((Some(action), (stream, Some(outputs)))), } }, ) .filter_map(future::ready), )), units: self.units, }, } } /// Creates a new [`Task`] that discards the result of the current one. /// /// Useful if you only care about the side effects of a [`Task`]. pub fn discard<O>(self) -> Task<O> where T: MaybeSend + 'static, O: MaybeSend + 'static, { self.then(|_| Task::none()) } /// Creates a new [`Task`] that can be aborted with the returned [`Handle`]. pub fn abortable(self) -> (Self, Handle) where T: 'static, { let (stream, handle) = match self.stream { Some(stream) => { let (stream, handle) = stream::abortable(stream); (Some(boxed_stream(stream)), InternalHandle::Manual(handle)) } None => ( None, InternalHandle::Manual(stream::AbortHandle::new_pair().0), ), }; ( Self { stream, units: self.units, }, Handle { internal: handle }, ) } /// Creates a new [`Task`] that runs the given [`Future`] and produces /// its output. pub fn future(future: impl Future<Output = T> + MaybeSend + 'static) -> Self where T: 'static, { Self::stream(stream::once(future)) } /// Creates a new [`Task`] that runs the given [`Stream`] and produces /// each of its items. pub fn stream(stream: impl Stream<Item = T> + MaybeSend + 'static) -> Self where T: 'static, { Self { stream: Some(boxed_stream( stream::once(yield_now()) .filter_map(|_| async { None }) .chain(stream.map(Action::Output)), )), units: 1, } } /// Returns the amount of work "units" of the [`Task`]. pub fn units(&self) -> usize { self.units } } impl<T> std::fmt::Debug for Task<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct(&format!("Task<{}>", std::any::type_name::<T>())) .field("units", &self.units) .finish() } } /// A handle to a [`Task`] that can be used for aborting it. #[derive(Debug, Clone)] pub struct Handle { internal: InternalHandle, } #[derive(Debug, Clone)] enum InternalHandle { Manual(stream::AbortHandle), AbortOnDrop(Arc<stream::AbortHandle>), } impl InternalHandle { pub fn as_ref(&self) -> &stream::AbortHandle { match self { InternalHandle::Manual(handle) => handle, InternalHandle::AbortOnDrop(handle) => handle.as_ref(), } } } impl Handle { /// Aborts the [`Task`] of this [`Handle`]. pub fn abort(&self) { self.internal.as_ref().abort(); } /// Returns a new [`Handle`] that will call [`Handle::abort`] whenever /// all of its instances are dropped. /// /// If a [`Handle`] is cloned, [`Handle::abort`] will only be called /// once all of the clones are dropped. /// /// This can be really useful if you do not want to worry about calling /// [`Handle::abort`] yourself. pub fn abort_on_drop(self) -> Self { match &self.internal { InternalHandle::Manual(handle) => Self { internal: InternalHandle::AbortOnDrop(Arc::new(handle.clone())), }, InternalHandle::AbortOnDrop(_) => self, } } /// Returns `true` if the [`Task`] of this [`Handle`] has been aborted. pub fn is_aborted(&self) -> bool { self.internal.as_ref().is_aborted() } } impl Drop for Handle { fn drop(&mut self) { if let InternalHandle::AbortOnDrop(handle) = &mut self.internal { let handle = std::mem::replace(handle, Arc::new(stream::AbortHandle::new_pair().0)); if let Some(handle) = Arc::into_inner(handle) { handle.abort(); } } } } impl<T> Task<Option<T>> { /// Executes a new [`Task`] after this one, only when it produces `Some` value. /// /// The value is provided to the closure to create the subsequent [`Task`]. pub fn and_then<A>(self, f: impl Fn(T) -> Task<A> + MaybeSend + 'static) -> Task<A> where T: MaybeSend + 'static, A: MaybeSend + 'static, { self.then(move |option| option.map_or_else(Task::none, &f)) } } impl<T, E> Task<Result<T, E>> { /// Executes a new [`Task`] after this one, only when it succeeds with an `Ok` value. /// /// The success value is provided to the closure to create the subsequent [`Task`]. pub fn and_then<A>( self, f: impl Fn(T) -> Task<Result<A, E>> + MaybeSend + 'static, ) -> Task<Result<A, E>> where T: MaybeSend + 'static, E: MaybeSend + 'static, A: MaybeSend + 'static, { self.then(move |result| result.map_or_else(|error| Task::done(Err(error)), &f)) } /// Maps the error type of this [`Task`] to a different one using the given /// function. pub fn map_err<E2>(self, f: impl Fn(E) -> E2 + MaybeSend + 'static) -> Task<Result<T, E2>> where T: MaybeSend + 'static, E: MaybeSend + 'static, E2: MaybeSend + 'static, { self.map(move |result| result.map_err(&f)) } } impl<T> Default for Task<T> { fn default() -> Self { Self::none() } } impl<T> From<()> for Task<T> { fn from(_value: ()) -> Self { Self::none() } } /// Creates a new [`Task`] that runs the given [`widget::Operation`] and produces /// its output. pub fn widget<T>(operation: impl widget::Operation<T> + 'static) -> Task<T> where T: Send + 'static, { channel(move |sender| { let operation = widget::operation::map(Box::new(operation), move |value| { let _ = sender.clone().try_send(value); }); Action::Widget(Box::new(operation)) }) } /// Creates a new [`Task`] that executes the [`Action`] returned by the closure and /// produces the value fed to the [`oneshot::Sender`]. pub fn oneshot<T>(f: impl FnOnce(oneshot::Sender<T>) -> Action<T>) -> Task<T> where T: MaybeSend + 'static, { let (sender, receiver) = oneshot::channel(); let action = f(sender); Task { stream: Some(boxed_stream( stream::once(async move { action }).chain( receiver .into_stream() .filter_map(|result| async move { Some(Action::Output(result.ok()?)) }), ), )), units: 1, } } /// Creates a new [`Task`] that executes the [`Action`] returned by the closure and /// produces the values fed to the [`mpsc::Sender`]. pub fn channel<T>(f: impl FnOnce(mpsc::Sender<T>) -> Action<T>) -> Task<T> where T: MaybeSend + 'static, { let (sender, receiver) = mpsc::channel(1); let action = f(sender); Task { stream: Some(boxed_stream( stream::once(async move { action }) .chain(receiver.map(|result| Action::Output(result))), )), units: 1, } } /// Creates a new [`Task`] that executes the given [`Action`] and produces no output. pub fn effect<T>(action: impl Into<Action<Infallible>>) -> Task<T> { let action = action.into(); Task { stream: Some(boxed_stream(stream::once(async move { action.output().expect_err("no output") }))), units: 1, } } /// Returns the underlying [`Stream`] of the [`Task`]. pub fn into_stream<T>(task: Task<T>) -> Option<BoxStream<Action<T>>> { task.stream } /// Creates a new [`Task`] that will run the given closure in a new thread. /// /// Any data sent by the closure through the [`mpsc::Sender`] will be produced /// by the [`Task`]. pub fn blocking<T>(f: impl FnOnce(mpsc::Sender<T>) + Send + 'static) -> Task<T> where T: Send + 'static, { let (sender, receiver) = mpsc::channel(1); let _ = thread::spawn(move || { f(sender); }); Task::stream(receiver) } /// Creates a new [`Task`] that will run the given closure that can fail in a new /// thread. /// /// Any data sent by the closure through the [`mpsc::Sender`] will be produced /// by the [`Task`]. pub fn try_blocking<T, E>( f: impl FnOnce(mpsc::Sender<T>) -> Result<(), E> + Send + 'static, ) -> Task<Result<T, E>> where T: Send + 'static, E: Send + 'static, { let (sender, receiver) = mpsc::channel(1); let (error_sender, error_receiver) = oneshot::channel(); let _ = thread::spawn(move || { if let Err(error) = f(sender) { let _ = error_sender.send(Err(error)); } }); Task::stream(stream::select( receiver.map(Ok), stream::once(error_receiver).filter_map(async |result| result.ok()), )) } async fn yield_now() { struct YieldNow { yielded: bool, } impl Future for YieldNow { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<()> { if self.yielded { return task::Poll::Ready(()); } self.yielded = true; cx.waker().wake_by_ref(); task::Poll::Pending } } YieldNow { yielded: false }.await; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/keyboard.rs
runtime/src/keyboard.rs
//! Track keyboard events. pub use iced_core::keyboard::*;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/widget/selector.rs
runtime/src/widget/selector.rs
//! Find and query widgets in your applications. pub use iced_selector::{Bounded, Candidate, Selector, Target, Text, id, is_focused}; use crate::Task; use crate::task; /// Finds a widget matching the given [`Selector`]. pub fn find<S>(selector: S) -> Task<Option<S::Output>> where S: Selector + Send + 'static, S::Output: Send + Clone + 'static, { task::widget(selector.find()) } /// Finds all widgets matching the given [`Selector`]. pub fn find_all<S>(selector: S) -> Task<Vec<S::Output>> where S: Selector + Send + 'static, S::Output: Send + Clone + 'static, { task::widget(selector.find_all()) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/runtime/src/widget/operation.rs
runtime/src/widget/operation.rs
//! Change internal widget state. use crate::core::widget::Id; use crate::core::widget::operation; use crate::task; use crate::{Action, Task}; pub use crate::core::widget::operation::scrollable::{AbsoluteOffset, RelativeOffset}; /// Snaps the scrollable with the given [`Id`] to the provided [`RelativeOffset`]. pub fn snap_to<T>(id: impl Into<Id>, offset: impl Into<RelativeOffset<Option<f32>>>) -> Task<T> { task::effect(Action::widget(operation::scrollable::snap_to( id.into(), offset.into(), ))) } /// Snaps the scrollable with the given [`Id`] to the [`RelativeOffset::END`]. pub fn snap_to_end<T>(id: impl Into<Id>) -> Task<T> { task::effect(Action::widget(operation::scrollable::snap_to( id.into(), RelativeOffset::END.into(), ))) } /// Scrolls the scrollable with the given [`Id`] to the provided [`AbsoluteOffset`]. pub fn scroll_to<T>(id: impl Into<Id>, offset: impl Into<AbsoluteOffset<Option<f32>>>) -> Task<T> { task::effect(Action::widget(operation::scrollable::scroll_to( id.into(), offset.into(), ))) } /// Scrolls the scrollable with the given [`Id`] by the provided [`AbsoluteOffset`]. pub fn scroll_by<T>(id: impl Into<Id>, offset: AbsoluteOffset) -> Task<T> { task::effect(Action::widget(operation::scrollable::scroll_by( id.into(), offset, ))) } /// Focuses the previous focusable widget. pub fn focus_previous<T>() -> Task<T> { task::effect(Action::widget(operation::focusable::focus_previous())) } /// Focuses the next focusable widget. pub fn focus_next<T>() -> Task<T> { task::effect(Action::widget(operation::focusable::focus_next())) } /// Returns whether the widget with the given [`Id`] is focused or not. pub fn is_focused(id: impl Into<Id>) -> Task<bool> { task::widget(operation::focusable::is_focused(id.into())) } /// Focuses the widget with the given [`Id`]. pub fn focus<T>(id: impl Into<Id>) -> Task<T> { task::effect(Action::widget(operation::focusable::focus(id.into()))) } /// Moves the cursor of the widget with the given [`Id`] to the end. pub fn move_cursor_to_end<T>(id: impl Into<Id>) -> Task<T> { task::effect(Action::widget(operation::text_input::move_cursor_to_end( id.into(), ))) } /// Moves the cursor of the widget with the given [`Id`] to the front. pub fn move_cursor_to_front<T>(id: impl Into<Id>) -> Task<T> { task::effect(Action::widget(operation::text_input::move_cursor_to_front( id.into(), ))) } /// Moves the cursor of the widget with the given [`Id`] to the provided position. pub fn move_cursor_to<T>(id: impl Into<Id>, position: usize) -> Task<T> { task::effect(Action::widget(operation::text_input::move_cursor_to( id.into(), position, ))) } /// Selects all the content of the widget with the given [`Id`]. pub fn select_all<T>(id: impl Into<Id>) -> Task<T> { task::effect(Action::widget(operation::text_input::select_all(id.into()))) } /// Selects the given content range of the widget with the given [`Id`]. pub fn select_range<T>(id: impl Into<Id>, start: usize, end: usize) -> Task<T> { task::effect(Action::widget(operation::text_input::select_range( id.into(), start, end, ))) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/selector/src/lib.rs
selector/src/lib.rs
//! Select data from the widget tree. use iced_core as core; mod find; mod target; pub use find::{Find, FindAll}; pub use target::{Bounded, Candidate, Target, Text}; use crate::core::Point; use crate::core::widget; /// A type that traverses the widget tree to "select" data and produce some output. pub trait Selector { /// The output type of the [`Selector`]. /// /// For most selectors, this will normally be a [`Target`]. However, some /// selectors may want to return a more limited type to encode the selection /// guarantees in the type system. /// /// For instance, the implementations of [`String`] and [`str`] of [`Selector`] /// return a [`target::Text`] instead of a generic [`Target`], since they are /// guaranteed to only select text. type Output; /// Performs a selection of the given [`Candidate`], if applicable. /// /// This method traverses the widget tree in depth-first order. fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output>; /// Returns a short description of the [`Selector`] for debugging purposes. fn description(&self) -> String; /// Returns a [`widget::Operation`] that runs the [`Selector`] and stops after /// the first [`Output`](Self::Output) is produced. fn find(self) -> Find<Self> where Self: Sized, { Find::new(find::One::new(self)) } /// Returns a [`widget::Operation`] that runs the [`Selector`] for the entire /// widget tree and aggregates all of its [`Output`](Self::Output). fn find_all(self) -> FindAll<Self> where Self: Sized, { FindAll::new(find::All::new(self)) } } impl Selector for &str { type Output = target::Text; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { match candidate { Candidate::TextInput { id, bounds, visible_bounds, state, } if state.text() == *self => Some(target::Text::Input { id: id.cloned(), bounds, visible_bounds, }), Candidate::Text { id, bounds, visible_bounds, content, } if content == *self => Some(target::Text::Raw { id: id.cloned(), bounds, visible_bounds, }), _ => None, } } fn description(&self) -> String { format!("text == {self:?}") } } impl Selector for String { type Output = target::Text; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { self.as_str().select(candidate) } fn description(&self) -> String { self.as_str().description() } } impl Selector for widget::Id { type Output = Target; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { if candidate.id() != Some(self) { return None; } Some(Target::from(candidate)) } fn description(&self) -> String { format!("id == {self:?}") } } impl Selector for Point { type Output = Target; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { candidate .visible_bounds() .is_some_and(|visible_bounds| visible_bounds.contains(*self)) .then(|| Target::from(candidate)) } fn description(&self) -> String { format!("bounds contains {self:?}") } } impl<F, T> Selector for F where F: FnMut(Candidate<'_>) -> Option<T>, { type Output = T; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { (self)(candidate) } fn description(&self) -> String { format!("custom selector: {}", std::any::type_name_of_val(self)) } } /// Creates a new [`Selector`] that matches widgets with the given [`widget::Id`]. pub fn id(id: impl Into<widget::Id>) -> impl Selector<Output = Target> { id.into() } /// Returns a [`Selector`] that matches widgets that are currently focused. pub fn is_focused() -> impl Selector<Output = Target> { struct IsFocused; impl Selector for IsFocused { type Output = Target; fn select(&mut self, candidate: Candidate<'_>) -> Option<Self::Output> { if let Candidate::Focusable { state, .. } = candidate && state.is_focused() { Some(Target::from(candidate)) } else { None } } fn description(&self) -> String { "is focused".to_owned() } } IsFocused }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/selector/src/find.rs
selector/src/find.rs
use crate::Selector; use crate::core::widget::operation::{Focusable, Outcome, Scrollable, TextInput}; use crate::core::widget::{Id, Operation}; use crate::core::{Rectangle, Vector}; use crate::target::Candidate; use std::any::Any; /// An [`Operation`] that runs the [`Selector`] and stops after /// the first [`Output`](Selector::Output) is produced. pub type Find<S> = Finder<One<S>>; /// An [`Operation`] that runs the [`Selector`] for the entire /// widget tree and aggregates all of its [`Output`](Selector::Output). pub type FindAll<S> = Finder<All<S>>; #[derive(Debug)] pub struct One<S> where S: Selector, { selector: S, output: Option<S::Output>, } impl<S> One<S> where S: Selector, { pub fn new(selector: S) -> Self { Self { selector, output: None, } } } impl<S> Strategy for One<S> where S: Selector, S::Output: Clone, { type Output = Option<S::Output>; fn feed(&mut self, target: Candidate<'_>) { if let Some(output) = self.selector.select(target) { self.output = Some(output); } } fn is_done(&self) -> bool { self.output.is_some() } fn finish(&self) -> Self::Output { self.output.clone() } } #[derive(Debug)] pub struct All<S> where S: Selector, { selector: S, outputs: Vec<S::Output>, } impl<S> All<S> where S: Selector, { pub fn new(selector: S) -> Self { Self { selector, outputs: Vec::new(), } } } impl<S> Strategy for All<S> where S: Selector, S::Output: Clone, { type Output = Vec<S::Output>; fn feed(&mut self, target: Candidate<'_>) { if let Some(output) = self.selector.select(target) { self.outputs.push(output); } } fn is_done(&self) -> bool { false } fn finish(&self) -> Self::Output { self.outputs.clone() } } pub trait Strategy { type Output; fn feed(&mut self, target: Candidate<'_>); fn is_done(&self) -> bool; fn finish(&self) -> Self::Output; } #[derive(Debug)] pub struct Finder<S> { strategy: S, stack: Vec<(Rectangle, Vector)>, viewport: Rectangle, translation: Vector, } impl<S> Finder<S> { pub fn new(strategy: S) -> Self { Self { strategy, stack: vec![(Rectangle::INFINITE, Vector::ZERO)], viewport: Rectangle::INFINITE, translation: Vector::ZERO, } } } impl<S> Operation<S::Output> for Finder<S> where S: Strategy + Send, S::Output: Send, { fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<S::Output>)) { if self.strategy.is_done() { return; } self.stack.push((self.viewport, self.translation)); operate(self); let _ = self.stack.pop(); let (viewport, translation) = self.stack.last().unwrap(); self.viewport = *viewport; self.translation = *translation; } fn container(&mut self, id: Option<&Id>, bounds: Rectangle) { if self.strategy.is_done() { return; } self.strategy.feed(Candidate::Container { id, bounds, visible_bounds: self.viewport.intersection(&(bounds + self.translation)), }); } fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { if self.strategy.is_done() { return; } self.strategy.feed(Candidate::Focusable { id, bounds, visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } fn scrollable( &mut self, id: Option<&Id>, bounds: Rectangle, content_bounds: Rectangle, translation: Vector, state: &mut dyn Scrollable, ) { if self.strategy.is_done() { return; } let visible_bounds = self.viewport.intersection(&(bounds + self.translation)); self.strategy.feed(Candidate::Scrollable { id, bounds, visible_bounds, content_bounds, translation, state, }); self.translation -= translation; self.viewport = visible_bounds.unwrap_or_default(); } fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { if self.strategy.is_done() { return; } self.strategy.feed(Candidate::TextInput { id, bounds, visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { if self.strategy.is_done() { return; } self.strategy.feed(Candidate::Text { id, bounds, visible_bounds: self.viewport.intersection(&(bounds + self.translation)), content: text, }); } fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { if self.strategy.is_done() { return; } self.strategy.feed(Candidate::Custom { id, bounds, visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } fn finish(&self) -> Outcome<S::Output> { Outcome::Some(self.strategy.finish()) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/selector/src/target.rs
selector/src/target.rs
use crate::core::widget::Id; use crate::core::widget::operation::{Focusable, Scrollable, TextInput}; use crate::core::{Rectangle, Vector}; use std::any::Any; /// A generic widget match produced during selection. #[allow(missing_docs)] #[derive(Debug, Clone, PartialEq)] pub enum Target { Container { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, Focusable { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, Scrollable { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, content_bounds: Rectangle, translation: Vector, }, TextInput { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, content: String, }, Text { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, content: String, }, Custom { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, } impl Target { /// Returns the layout bounds of the [`Target`]. pub fn bounds(&self) -> Rectangle { match self { Target::Container { bounds, .. } | Target::Focusable { bounds, .. } | Target::Scrollable { bounds, .. } | Target::TextInput { bounds, .. } | Target::Text { bounds, .. } | Target::Custom { bounds, .. } => *bounds, } } /// Returns the visible bounds of the [`Target`], in screen coordinates. pub fn visible_bounds(&self) -> Option<Rectangle> { match self { Target::Container { visible_bounds, .. } | Target::Focusable { visible_bounds, .. } | Target::Scrollable { visible_bounds, .. } | Target::TextInput { visible_bounds, .. } | Target::Text { visible_bounds, .. } | Target::Custom { visible_bounds, .. } => *visible_bounds, } } } impl From<Candidate<'_>> for Target { fn from(candidate: Candidate<'_>) -> Self { match candidate { Candidate::Container { id, bounds, visible_bounds, } => Self::Container { id: id.cloned(), bounds, visible_bounds, }, Candidate::Focusable { id, bounds, visible_bounds, .. } => Self::Focusable { id: id.cloned(), bounds, visible_bounds, }, Candidate::Scrollable { id, bounds, visible_bounds, content_bounds, translation, .. } => Self::Scrollable { id: id.cloned(), bounds, visible_bounds, content_bounds, translation, }, Candidate::TextInput { id, bounds, visible_bounds, state, } => Self::TextInput { id: id.cloned(), bounds, visible_bounds, content: state.text().to_owned(), }, Candidate::Text { id, bounds, visible_bounds, content, } => Self::Text { id: id.cloned(), bounds, visible_bounds, content: content.to_owned(), }, Candidate::Custom { id, bounds, visible_bounds, .. } => Self::Custom { id: id.cloned(), bounds, visible_bounds, }, } } } impl Bounded for Target { fn bounds(&self) -> Rectangle { self.bounds() } fn visible_bounds(&self) -> Option<Rectangle> { self.visible_bounds() } } /// A selection candidate. /// /// This is provided to [`Selector::select`](crate::Selector::select). #[allow(missing_docs)] #[derive(Clone)] pub enum Candidate<'a> { Container { id: Option<&'a Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, Focusable { id: Option<&'a Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, state: &'a dyn Focusable, }, Scrollable { id: Option<&'a Id>, bounds: Rectangle, content_bounds: Rectangle, visible_bounds: Option<Rectangle>, translation: Vector, state: &'a dyn Scrollable, }, TextInput { id: Option<&'a Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, state: &'a dyn TextInput, }, Text { id: Option<&'a Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, content: &'a str, }, Custom { id: Option<&'a Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, state: &'a dyn Any, }, } impl<'a> Candidate<'a> { /// Returns the widget [`Id`] of the [`Candidate`]. pub fn id(&self) -> Option<&'a Id> { match self { Candidate::Container { id, .. } | Candidate::Focusable { id, .. } | Candidate::Scrollable { id, .. } | Candidate::TextInput { id, .. } | Candidate::Text { id, .. } | Candidate::Custom { id, .. } => *id, } } /// Returns the layout bounds of the [`Candidate`]. pub fn bounds(&self) -> Rectangle { match self { Candidate::Container { bounds, .. } | Candidate::Focusable { bounds, .. } | Candidate::Scrollable { bounds, .. } | Candidate::TextInput { bounds, .. } | Candidate::Text { bounds, .. } | Candidate::Custom { bounds, .. } => *bounds, } } /// Returns the visible bounds of the [`Candidate`], in screen coordinates. pub fn visible_bounds(&self) -> Option<Rectangle> { match self { Candidate::Container { visible_bounds, .. } | Candidate::Focusable { visible_bounds, .. } | Candidate::Scrollable { visible_bounds, .. } | Candidate::TextInput { visible_bounds, .. } | Candidate::Text { visible_bounds, .. } | Candidate::Custom { visible_bounds, .. } => *visible_bounds, } } } /// A bounded type has both layout bounds and visible bounds. /// /// This trait lets us write generic code over the [`Output`](crate::Selector::Output) /// of a [`Selector`](crate::Selector). pub trait Bounded: std::fmt::Debug { /// Returns the layout bounds. fn bounds(&self) -> Rectangle; /// Returns the visible bounds, in screen coordinates. fn visible_bounds(&self) -> Option<Rectangle>; } /// A text match. #[allow(missing_docs)] #[derive(Debug, Clone, PartialEq)] pub enum Text { Raw { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, Input { id: Option<Id>, bounds: Rectangle, visible_bounds: Option<Rectangle>, }, } impl Text { /// Returns the layout bounds of the [`Text`]. pub fn bounds(&self) -> Rectangle { match self { Text::Raw { bounds, .. } | Text::Input { bounds, .. } => *bounds, } } /// Returns the visible bounds of the [`Text`], in screen coordinates. pub fn visible_bounds(&self) -> Option<Rectangle> { match self { Text::Raw { visible_bounds, .. } | Text::Input { visible_bounds, .. } => { *visible_bounds } } } } impl Bounded for Text { fn bounds(&self) -> Rectangle { self.bounds() } fn visible_bounds(&self) -> Option<Rectangle> { self.visible_bounds() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/slider/src/main.rs
examples/slider/src/main.rs
use iced::widget::{column, container, iced, slider, text, vertical_slider}; use iced::{Center, Element, Fill}; pub fn main() -> iced::Result { iced::run(Slider::update, Slider::view) } #[derive(Debug, Clone)] pub enum Message { SliderChanged(u8), } pub struct Slider { value: u8, } impl Slider { fn new() -> Self { Slider { value: 50 } } fn update(&mut self, message: Message) { match message { Message::SliderChanged(value) => { self.value = value; } } } fn view(&self) -> Element<'_, Message> { let h_slider = container( slider(1..=100, self.value, Message::SliderChanged) .default(50) .shift_step(5), ) .width(250); let v_slider = container( vertical_slider(1..=100, self.value, Message::SliderChanged) .default(50) .shift_step(5), ) .height(200); let text = text(self.value); column![v_slider, h_slider, text, iced(self.value as f32),] .width(Fill) .align_x(Center) .spacing(20) .padding(20) .into() } } impl Default for Slider { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/combo_box/src/main.rs
examples/combo_box/src/main.rs
use iced::widget::{center, column, combo_box, scrollable, space, text}; use iced::{Center, Element, Fill}; pub fn main() -> iced::Result { iced::run(Example::update, Example::view) } struct Example { languages: combo_box::State<Language>, selected_language: Option<Language>, text: String, } #[derive(Debug, Clone, Copy)] enum Message { Selected(Language), OptionHovered(Language), Closed, } impl Example { fn new() -> Self { Self { languages: combo_box::State::new(Language::ALL.to_vec()), selected_language: None, text: String::new(), } } fn update(&mut self, message: Message) { match message { Message::Selected(language) => { self.selected_language = Some(language); self.text = language.hello().to_string(); } Message::OptionHovered(language) => { self.text = language.hello().to_string(); } Message::Closed => { self.text = self .selected_language .map(|language| language.hello().to_string()) .unwrap_or_default(); } } } fn view(&self) -> Element<'_, Message> { let combo_box = combo_box( &self.languages, "Type a language...", self.selected_language.as_ref(), Message::Selected, ) .on_option_hovered(Message::OptionHovered) .on_close(Message::Closed) .width(250); let content = column![ text(&self.text), "What is your language?", combo_box, space().height(150), ] .width(Fill) .align_x(Center) .spacing(10); center(scrollable(content)).into() } } impl Default for Example { fn default() -> Self { Example::new() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Language { Danish, #[default] English, French, German, Italian, Japanese, Portuguese, Spanish, Other, } impl Language { const ALL: [Language; 9] = [ Language::Danish, Language::English, Language::French, Language::German, Language::Italian, Language::Japanese, Language::Portuguese, Language::Spanish, Language::Other, ]; fn hello(&self) -> &str { match self { Language::Danish => "Halloy!", Language::English => "Hello!", Language::French => "Salut!", Language::German => "Hallo!", Language::Italian => "Ciao!", Language::Japanese => "こんにちは!", Language::Portuguese => "Olá!", Language::Spanish => "¡Hola!", Language::Other => "... hello?", } } } impl std::fmt::Display for Language { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Language::Danish => "Danish", Language::English => "English", Language::French => "French", Language::German => "German", Language::Italian => "Italian", Language::Japanese => "日本語", Language::Portuguese => "Portuguese", Language::Spanish => "Spanish", Language::Other => "Some other language", } ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/qr_code/src/main.rs
examples/qr_code/src/main.rs
use iced::widget::{center, column, pick_list, qr_code, row, slider, text, text_input, toggler}; use iced::{Center, Element, Theme}; use std::ops::RangeInclusive; pub fn main() -> iced::Result { iced::application(QRGenerator::default, QRGenerator::update, QRGenerator::view) .theme(QRGenerator::theme) .run() } #[derive(Default)] struct QRGenerator { data: String, qr_code: Option<qr_code::Data>, total_size: Option<f32>, theme: Option<Theme>, } #[derive(Debug, Clone)] enum Message { DataChanged(String), ToggleTotalSize(bool), TotalSizeChanged(f32), ThemeChanged(Theme), } impl QRGenerator { const SIZE_RANGE: RangeInclusive<f32> = 200.0..=400.0; fn update(&mut self, message: Message) { match message { Message::DataChanged(mut data) => { data.truncate(100); self.qr_code = if data.is_empty() { None } else { qr_code::Data::new(&data).ok() }; self.data = data; } Message::ToggleTotalSize(enabled) => { self.total_size = enabled.then_some( Self::SIZE_RANGE.start() + (Self::SIZE_RANGE.end() - Self::SIZE_RANGE.start()) / 2.0, ); } Message::TotalSizeChanged(total_size) => { self.total_size = Some(total_size); } Message::ThemeChanged(theme) => { self.theme = Some(theme); } } } fn view(&self) -> Element<'_, Message> { let title = text("QR Code Generator").size(70); let input = text_input("Type the data of your QR code here...", &self.data) .on_input(Message::DataChanged) .size(30) .padding(15); let toggle_total_size = toggler(self.total_size.is_some()) .on_toggle(Message::ToggleTotalSize) .label("Limit Total Size"); let choose_theme = row![ text("Theme:"), pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeChanged).placeholder("Theme") ] .spacing(10) .align_y(Center); let content = column![ title, input, row![toggle_total_size, choose_theme] .spacing(20) .align_y(Center), self.total_size.map(|total_size| { slider(Self::SIZE_RANGE, total_size, Message::TotalSizeChanged) }), self.qr_code.as_ref().map(|data| { if let Some(total_size) = self.total_size { qr_code(data).total_size(total_size) } else { qr_code(data).cell_size(10.0) } }) ] .width(700) .spacing(20) .align_x(Center); center(content).padding(20).into() } fn theme(&self) -> Option<Theme> { self.theme.clone() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/delineate/src/main.rs
examples/delineate/src/main.rs
use iced::event::{self, Event}; use iced::mouse; use iced::widget::{self, column, container, row, scrollable, selector, space, text}; use iced::window; use iced::{Center, Color, Element, Fill, Font, Point, Rectangle, Subscription, Task, Theme}; pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view) .subscription(Example::subscription) .theme(Theme::Dark) .run() } #[derive(Default)] struct Example { mouse_position: Option<Point>, outer_bounds: Option<Rectangle>, inner_bounds: Option<Rectangle>, } #[derive(Debug, Clone)] enum Message { MouseMoved(Point), WindowResized, Scrolled, OuterFound(Option<selector::Target>), InnerFound(Option<selector::Target>), } impl Example { fn update(&mut self, message: Message) -> Task<Message> { match message { Message::MouseMoved(position) => { self.mouse_position = Some(position); Task::none() } Message::Scrolled | Message::WindowResized => Task::batch(vec![ selector::find(OUTER_CONTAINER).map(Message::OuterFound), selector::find(INNER_CONTAINER).map(Message::InnerFound), ]), Message::OuterFound(outer) => { self.outer_bounds = outer.as_ref().and_then(selector::Target::visible_bounds); Task::none() } Message::InnerFound(inner) => { self.inner_bounds = inner.as_ref().and_then(selector::Target::visible_bounds); Task::none() } } } fn view(&self) -> Element<'_, Message> { let data_row = |label, value, color| { row![ text(label), space::horizontal(), text(value) .font(Font::MONOSPACE) .size(14) .color_maybe(color), ] .height(40) .align_y(Center) }; let view_bounds = |label, bounds: Option<Rectangle>| { data_row( label, match bounds { Some(bounds) => format!("{bounds:?}"), None => "not visible".to_string(), }, if bounds .zip(self.mouse_position) .map(|(bounds, mouse_position)| bounds.contains(mouse_position)) .unwrap_or_default() { Some(Color { g: 1.0, ..Color::BLACK }) } else { None }, ) }; column![ data_row( "Mouse position", match self.mouse_position { Some(Point { x, y }) => format!("({x}, {y})"), None => "unknown".to_string(), }, None, ), view_bounds("Outer container", self.outer_bounds), view_bounds("Inner container", self.inner_bounds), scrollable( column![ text("Scroll me!"), space().height(400), container(text("I am the outer container!")) .id(OUTER_CONTAINER) .padding(40) .style(container::rounded_box), space().height(400), scrollable( column![ text("Scroll me!"), space().height(400), container(text("I am the inner container!")) .id(INNER_CONTAINER) .padding(40) .style(container::rounded_box), space().height(400), ] .padding(20) ) .on_scroll(|_| Message::Scrolled) .width(Fill) .height(300), ] .padding(20) ) .on_scroll(|_| Message::Scrolled) .width(Fill) .height(300), ] .spacing(10) .padding(20) .into() } fn subscription(&self) -> Subscription<Message> { event::listen_with(|event, _status, _window| match event { Event::Mouse(mouse::Event::CursorMoved { position }) => { Some(Message::MouseMoved(position)) } Event::Window(window::Event::Resized { .. }) => Some(Message::WindowResized), _ => None, }) } } const OUTER_CONTAINER: widget::Id = widget::Id::new("outer"); const INNER_CONTAINER: widget::Id = widget::Id::new("inner");
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/pick_list/src/main.rs
examples/pick_list/src/main.rs
use iced::widget::{column, pick_list, scrollable, space}; use iced::{Center, Element, Fill}; pub fn main() -> iced::Result { iced::run(Example::update, Example::view) } #[derive(Default)] struct Example { selected_language: Option<Language>, } #[derive(Debug, Clone, Copy)] enum Message { LanguageSelected(Language), } impl Example { fn update(&mut self, message: Message) { match message { Message::LanguageSelected(language) => { self.selected_language = Some(language); } } } fn view(&self) -> Element<'_, Message> { let pick_list = pick_list( &Language::ALL[..], self.selected_language, Message::LanguageSelected, ) .placeholder("Choose a language..."); let content = column![ space().height(600), "Which is your favorite language?", pick_list, space().height(600), ] .width(Fill) .align_x(Center) .spacing(10); scrollable(content).into() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Language { #[default] Rust, Elm, Ruby, Haskell, C, Javascript, Other, } impl Language { const ALL: [Language; 7] = [ Language::C, Language::Elm, Language::Ruby, Language::Haskell, Language::Rust, Language::Javascript, Language::Other, ]; } impl std::fmt::Display for Language { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Language::Rust => "Rust", Language::Elm => "Elm", Language::Ruby => "Ruby", Language::Haskell => "Haskell", Language::C => "C", Language::Javascript => "Javascript", Language::Other => "Some other language", } ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/multi_window/src/main.rs
examples/multi_window/src/main.rs
use iced::widget::{ button, center, center_x, column, container, operation, scrollable, space, text, text_input, }; use iced::window; use iced::{Center, Element, Fill, Function, Subscription, Task, Theme, Vector}; use std::collections::BTreeMap; fn main() -> iced::Result { iced::daemon(Example::new, Example::update, Example::view) .subscription(Example::subscription) .title(Example::title) .theme(Example::theme) .scale_factor(Example::scale_factor) .run() } struct Example { windows: BTreeMap<window::Id, Window>, } #[derive(Debug)] struct Window { title: String, scale_input: String, current_scale: f32, theme: Theme, } #[derive(Debug, Clone)] enum Message { OpenWindow, WindowOpened(window::Id), WindowClosed(window::Id), ScaleInputChanged(window::Id, String), ScaleChanged(window::Id, String), TitleChanged(window::Id, String), } impl Example { fn new() -> (Self, Task<Message>) { let (_, open) = window::open(window::Settings::default()); ( Self { windows: BTreeMap::new(), }, open.map(Message::WindowOpened), ) } fn title(&self, window: window::Id) -> String { self.windows .get(&window) .map(|window| window.title.clone()) .unwrap_or_default() } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::OpenWindow => { let Some(last_window) = self.windows.keys().last() else { return Task::none(); }; window::position(*last_window) .then(|last_position| { let position = last_position.map_or(window::Position::Default, |last_position| { window::Position::Specific(last_position + Vector::new(20.0, 20.0)) }); let (_, open) = window::open(window::Settings { position, ..window::Settings::default() }); open }) .map(Message::WindowOpened) } Message::WindowOpened(id) => { let window = Window::new(self.windows.len() + 1); let focus_input = operation::focus(format!("input-{id}")); self.windows.insert(id, window); focus_input } Message::WindowClosed(id) => { self.windows.remove(&id); if self.windows.is_empty() { iced::exit() } else { Task::none() } } Message::ScaleInputChanged(id, scale) => { if let Some(window) = self.windows.get_mut(&id) { window.scale_input = scale; } Task::none() } Message::ScaleChanged(id, scale) => { if let Some(window) = self.windows.get_mut(&id) { window.current_scale = scale .parse() .unwrap_or(window.current_scale) .clamp(0.5, 5.0); } Task::none() } Message::TitleChanged(id, title) => { if let Some(window) = self.windows.get_mut(&id) { window.title = title; } Task::none() } } } fn view(&self, window_id: window::Id) -> Element<'_, Message> { if let Some(window) = self.windows.get(&window_id) { center(window.view(window_id)).into() } else { space().into() } } fn theme(&self, window: window::Id) -> Option<Theme> { Some(self.windows.get(&window)?.theme.clone()) } fn scale_factor(&self, window: window::Id) -> f32 { self.windows .get(&window) .map(|window| window.current_scale) .unwrap_or(1.0) } fn subscription(&self) -> Subscription<Message> { window::close_events().map(Message::WindowClosed) } } impl Window { fn new(count: usize) -> Self { Self { title: format!("Window_{count}"), scale_input: "1.0".to_string(), current_scale: 1.0, theme: Theme::ALL[count % Theme::ALL.len()].clone(), } } fn view(&self, id: window::Id) -> Element<'_, Message> { let scale_input = column![ text("Window scale factor:"), text_input("Window Scale", &self.scale_input) .on_input(Message::ScaleInputChanged.with(id)) .on_submit(Message::ScaleChanged(id, self.scale_input.to_string())) ]; let title_input = column![ text("Window title:"), text_input("Window Title", &self.title) .on_input(Message::TitleChanged.with(id)) .id(format!("input-{id}")) ]; let new_window_button = button(text("New Window")).on_press(Message::OpenWindow); let content = column![scale_input, title_input, new_window_button] .spacing(50) .width(Fill) .align_x(Center) .width(200); container(scrollable(center_x(content))).padding(10).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/integration/src/controls.rs
examples/integration/src/controls.rs
use iced_wgpu::Renderer; use iced_widget::{bottom, column, row, slider, text, text_input}; use iced_winit::core::{Color, Element, Theme}; pub struct Controls { background_color: Color, input: String, } #[derive(Debug, Clone)] pub enum Message { BackgroundColorChanged(Color), InputChanged(String), } impl Controls { pub fn new() -> Controls { Controls { background_color: Color::BLACK, input: String::default(), } } pub fn background_color(&self) -> Color { self.background_color } } impl Controls { pub fn update(&mut self, message: Message) { match message { Message::BackgroundColorChanged(color) => { self.background_color = color; } Message::InputChanged(input) => { self.input = input; } } } pub fn view(&self) -> Element<'_, Message, Theme, Renderer> { let background_color = self.background_color; let sliders = row![ slider(0.0..=1.0, background_color.r, move |r| { Message::BackgroundColorChanged(Color { r, ..background_color }) }) .step(0.01), slider(0.0..=1.0, background_color.g, move |g| { Message::BackgroundColorChanged(Color { g, ..background_color }) }) .step(0.01), slider(0.0..=1.0, background_color.b, move |b| { Message::BackgroundColorChanged(Color { b, ..background_color }) }) .step(0.01), ] .width(500) .spacing(20); bottom( column![ text("Background color").color(Color::WHITE), text!("{background_color:?}").size(14).color(Color::WHITE), sliders, text_input("Type something...", &self.input).on_input(Message::InputChanged), ] .spacing(10), ) .padding(10) .into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/integration/src/scene.rs
examples/integration/src/scene.rs
use iced_wgpu::wgpu; use iced_winit::core::Color; pub struct Scene { pipeline: wgpu::RenderPipeline, } impl Scene { pub fn new(device: &wgpu::Device, texture_format: wgpu::TextureFormat) -> Scene { let pipeline = build_pipeline(device, texture_format); Scene { pipeline } } pub fn clear<'a>( target: &'a wgpu::TextureView, encoder: &'a mut wgpu::CommandEncoder, background_color: Color, ) -> wgpu::RenderPass<'a> { encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: target, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear({ let [r, g, b, a] = background_color.into_linear(); wgpu::Color { r: r as f64, g: g as f64, b: b as f64, a: a as f64, } }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }) } pub fn draw<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { render_pass.set_pipeline(&self.pipeline); render_pass.draw(0..3, 0..1); } } fn build_pipeline( device: &wgpu::Device, texture_format: wgpu::TextureFormat, ) -> wgpu::RenderPipeline { let (vs_module, fs_module) = ( device.create_shader_module(wgpu::include_wgsl!("shader/vert.wgsl")), device.create_shader_module(wgpu::include_wgsl!("shader/frag.wgsl")), ); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, push_constant_ranges: &[], bind_group_layouts: &[], }); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { module: &vs_module, entry_point: Some("main"), buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &fs_module, entry_point: Some("main"), targets: &[Some(wgpu::ColorTargetState { format: texture_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent::REPLACE, alpha: wgpu::BlendComponent::REPLACE, }), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Ccw, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview: None, cache: None, }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/integration/src/main.rs
examples/integration/src/main.rs
mod controls; mod scene; use controls::Controls; use scene::Scene; use iced_wgpu::graphics::{Shell, Viewport}; use iced_wgpu::{Engine, Renderer, wgpu}; use iced_winit::Clipboard; use iced_winit::conversion; use iced_winit::core::mouse; use iced_winit::core::renderer; use iced_winit::core::time::Instant; use iced_winit::core::window; use iced_winit::core::{Event, Font, Pixels, Size, Theme}; use iced_winit::futures; use iced_winit::runtime::user_interface::{self, UserInterface}; use iced_winit::winit; use winit::{ event::WindowEvent, event_loop::{ControlFlow, EventLoop}, keyboard::ModifiersState, }; use std::sync::Arc; pub fn main() -> Result<(), winit::error::EventLoopError> { tracing_subscriber::fmt::init(); // Initialize winit let event_loop = EventLoop::new()?; #[allow(clippy::large_enum_variant)] enum Runner { Loading, Ready { window: Arc<winit::window::Window>, queue: wgpu::Queue, device: wgpu::Device, surface: wgpu::Surface<'static>, format: wgpu::TextureFormat, renderer: Renderer, scene: Scene, controls: Controls, events: Vec<Event>, cursor: mouse::Cursor, cache: user_interface::Cache, clipboard: Clipboard, viewport: Viewport, modifiers: ModifiersState, resized: bool, }, } impl winit::application::ApplicationHandler for Runner { fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) { if let Self::Loading = self { let window = Arc::new( event_loop .create_window(winit::window::WindowAttributes::default()) .expect("Create window"), ); let physical_size = window.inner_size(); let viewport = Viewport::with_physical_size( Size::new(physical_size.width, physical_size.height), window.scale_factor() as f32, ); let clipboard = Clipboard::connect(window.clone()); let backend = wgpu::Backends::from_env().unwrap_or_default(); let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { backends: backend, ..Default::default() }); let surface = instance .create_surface(window.clone()) .expect("Create window surface"); let (format, adapter, device, queue) = futures::futures::executor::block_on(async { let adapter = wgpu::util::initialize_adapter_from_env_or_default( &instance, Some(&surface), ) .await .expect("Create adapter"); let adapter_features = adapter.features(); let capabilities = surface.get_capabilities(&adapter); let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor { label: None, required_features: adapter_features & wgpu::Features::default(), required_limits: wgpu::Limits::default(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, experimental_features: wgpu::ExperimentalFeatures::disabled(), }) .await .expect("Request device"); ( capabilities .formats .iter() .copied() .find(wgpu::TextureFormat::is_srgb) .or_else(|| capabilities.formats.first().copied()) .expect("Get preferred format"), adapter, device, queue, ) }); surface.configure( &device, &wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format, width: physical_size.width, height: physical_size.height, present_mode: wgpu::PresentMode::AutoVsync, alpha_mode: wgpu::CompositeAlphaMode::Auto, view_formats: vec![], desired_maximum_frame_latency: 2, }, ); // Initialize scene and GUI controls let scene = Scene::new(&device, format); let controls = Controls::new(); // Initialize iced let renderer = { let engine = Engine::new( &adapter, device.clone(), queue.clone(), format, None, Shell::headless(), ); Renderer::new(engine, Font::default(), Pixels::from(16)) }; // You should change this if you want to render continuously event_loop.set_control_flow(ControlFlow::Wait); *self = Self::Ready { window, device, queue, renderer, surface, format, scene, controls, events: Vec::new(), cursor: mouse::Cursor::Unavailable, modifiers: ModifiersState::default(), cache: user_interface::Cache::new(), clipboard, viewport, resized: false, }; } } fn window_event( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, _window_id: winit::window::WindowId, event: WindowEvent, ) { let Self::Ready { window, device, queue, surface, format, renderer, scene, controls, events, viewport, cursor, modifiers, clipboard, cache, resized, } = self else { return; }; match event { WindowEvent::RedrawRequested => { if *resized { let size = window.inner_size(); *viewport = Viewport::with_physical_size( Size::new(size.width, size.height), window.scale_factor() as f32, ); surface.configure( device, &wgpu::SurfaceConfiguration { format: *format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, width: size.width, height: size.height, present_mode: wgpu::PresentMode::AutoVsync, alpha_mode: wgpu::CompositeAlphaMode::Auto, view_formats: vec![], desired_maximum_frame_latency: 2, }, ); *resized = false; } match surface.get_current_texture() { Ok(frame) => { let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None, }); { // Clear the frame let mut render_pass = Scene::clear(&view, &mut encoder, controls.background_color()); // Draw the scene scene.draw(&mut render_pass); } // Submit the scene queue.submit([encoder.finish()]); // Draw iced on top let mut interface = UserInterface::build( controls.view(), viewport.logical_size(), std::mem::take(cache), renderer, ); let (state, _) = interface.update( &[Event::Window( window::Event::RedrawRequested(Instant::now()), )], *cursor, renderer, clipboard, &mut Vec::new(), ); // Update the mouse cursor if let user_interface::State::Updated { mouse_interaction, .. } = state { // Update the mouse cursor if let Some(icon) = iced_winit::conversion::mouse_interaction(mouse_interaction) { window.set_cursor(icon); window.set_cursor_visible(true); } else { window.set_cursor_visible(false); } } // Draw the interface interface.draw( renderer, &Theme::Dark, &renderer::Style::default(), *cursor, ); *cache = interface.into_cache(); renderer.present(None, frame.texture.format(), &view, viewport); // Present the frame frame.present(); } Err(error) => match error { wgpu::SurfaceError::OutOfMemory => { panic!( "Swapchain error: {error}. \ Rendering cannot continue." ) } _ => { // Try rendering again next frame. window.request_redraw(); } }, } } WindowEvent::CursorMoved { position, .. } => { *cursor = mouse::Cursor::Available(conversion::cursor_position( position, viewport.scale_factor(), )); } WindowEvent::ModifiersChanged(new_modifiers) => { *modifiers = new_modifiers.state(); } WindowEvent::Resized(_) => { *resized = true; } WindowEvent::CloseRequested => { event_loop.exit(); } _ => {} } // Map window event to iced event if let Some(event) = conversion::window_event(event, window.scale_factor() as f32, *modifiers) { events.push(event); } // If there are events pending if !events.is_empty() { // We process them let mut interface = UserInterface::build( controls.view(), viewport.logical_size(), std::mem::take(cache), renderer, ); let mut messages = Vec::new(); let _ = interface.update(events, *cursor, renderer, clipboard, &mut messages); events.clear(); *cache = interface.into_cache(); // update our UI with any messages for message in messages { controls.update(message); } // and request a redraw window.request_redraw(); } } } let mut runner = Runner::Loading; event_loop.run_app(&mut runner) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/loupe/src/main.rs
examples/loupe/src/main.rs
use iced::widget::{button, center, column, text}; use iced::{Center, Element}; use loupe::loupe; pub fn main() -> iced::Result { iced::run(Loupe::update, Loupe::view) } #[derive(Default)] struct Loupe { value: i64, } #[derive(Debug, Clone, Copy)] enum Message { Increment, Decrement, } impl Loupe { fn update(&mut self, message: Message) { match message { Message::Increment => { self.value += 1; } Message::Decrement => { self.value -= 1; } } } fn view(&self) -> Element<'_, Message> { center(loupe( 3.0, column![ button("Increment").on_press(Message::Increment), text(self.value).size(50), button("Decrement").on_press(Message::Decrement) ] .padding(20) .align_x(Center), )) .into() } } mod loupe { use iced::advanced::Renderer as _; use iced::advanced::layout::{self, Layout}; use iced::advanced::renderer; use iced::advanced::widget::{self, Widget}; use iced::mouse; use iced::{Color, Element, Length, Rectangle, Renderer, Size, Theme, Transformation}; pub fn loupe<'a, Message>( zoom: f32, content: impl Into<Element<'a, Message>>, ) -> Loupe<'a, Message> where Message: 'static, { Loupe { zoom, content: content.into().explain(Color::BLACK), } } pub struct Loupe<'a, Message> { zoom: f32, content: Element<'a, Message>, } impl<Message> Widget<Message, Theme, Renderer> for Loupe<'_, Message> { fn tag(&self) -> widget::tree::Tag { self.content.as_widget().tag() } fn state(&self) -> widget::tree::State { self.content.as_widget().state() } fn children(&self) -> Vec<widget::Tree> { self.content.as_widget().children() } fn diff(&self, tree: &mut widget::Tree) { self.content.as_widget().diff(tree); } fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.content.as_widget_mut().layout(tree, renderer, limits) } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let bounds = layout.bounds(); if let Some(position) = cursor.position_in(bounds) { renderer.with_layer(bounds, |renderer| { renderer.with_transformation( Transformation::translate( bounds.x + position.x * (1.0 - self.zoom), bounds.y + position.y * (1.0 - self.zoom), ) * Transformation::scale(self.zoom) * Transformation::translate(-bounds.x, -bounds.y), |renderer| { self.content.as_widget().draw( tree, renderer, theme, style, layout, mouse::Cursor::Unavailable, viewport, ); }, ); }); } else { self.content .as_widget() .draw(tree, renderer, theme, style, layout, cursor, viewport); } } fn mouse_interaction( &self, _tree: &widget::Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { if cursor.is_over(layout.bounds()) { mouse::Interaction::ZoomIn } else { mouse::Interaction::None } } } impl<'a, Message> From<Loupe<'a, Message>> for Element<'a, Message, Theme, Renderer> where Message: 'a, { fn from(loupe: Loupe<'a, Message>) -> Self { Self::new(loupe) } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/tooltip/src/main.rs
examples/tooltip/src/main.rs
use iced::Element; use iced::alignment; use iced::time::seconds; use iced::widget::tooltip::Position; use iced::widget::{button, center, checkbox, column, container, tooltip}; pub fn main() -> iced::Result { iced::run(Tooltip::update, Tooltip::view) } #[derive(Default)] struct Tooltip { position: Position, delay: bool, } #[derive(Debug, Clone)] enum Message { ChangePosition, ToggleDelay(bool), } impl Tooltip { fn update(&mut self, message: Message) { match message { Message::ChangePosition => { let position = match &self.position { Position::Top => Position::Bottom, Position::Bottom => Position::Left, Position::Left => Position::Right, Position::Right => Position::FollowCursor, Position::FollowCursor => Position::Top, }; self.position = position; } Message::ToggleDelay(is_immediate) => { self.delay = is_immediate; } } } fn view(&self) -> Element<'_, Message> { let tooltip = tooltip( button("Press to change position").on_press(Message::ChangePosition), position_to_text(self.position), self.position, ) .gap(10) .delay(seconds(if self.delay { 1 } else { 0 })) .style(container::rounded_box); let checkbox = checkbox(self.delay) .label("Delay") .on_toggle(Message::ToggleDelay); center( column![tooltip, checkbox] .align_x(alignment::Horizontal::Center) .spacing(10), ) .into() } } fn position_to_text<'a>(position: Position) -> &'a str { match position { Position::FollowCursor => "Follow Cursor", Position::Top => "Top", Position::Bottom => "Bottom", Position::Left => "Left", Position::Right => "Right", } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/exit/src/main.rs
examples/exit/src/main.rs
use iced::widget::{button, center, column}; use iced::window; use iced::{Center, Element, Task}; pub fn main() -> iced::Result { iced::run(Exit::update, Exit::view) } #[derive(Default)] struct Exit { show_confirm: bool, } #[derive(Debug, Clone, Copy)] enum Message { Confirm, Exit, } impl Exit { fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Confirm => window::latest().and_then(window::close), Message::Exit => { self.show_confirm = true; Task::none() } } } fn view(&self) -> Element<'_, Message> { let content = if self.show_confirm { column![ "Are you sure you want to exit?", button("Yes, exit now") .padding([10, 20]) .on_press(Message::Confirm), ] } else { column![ "Click the button to exit", button("Exit").padding([10, 20]).on_press(Message::Exit), ] } .spacing(10) .align_x(Center); center(content).padding(20).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_widget/src/main.rs
examples/custom_widget/src/main.rs
//! This example showcases a simple native custom widget that draws a circle. mod circle { use iced::advanced::layout::{self, Layout}; use iced::advanced::renderer; use iced::advanced::widget::{self, Widget}; use iced::border; use iced::mouse; use iced::{Color, Element, Length, Rectangle, Size}; pub struct Circle { radius: f32, } impl Circle { pub fn new(radius: f32) -> Self { Self { radius } } } pub fn circle(radius: f32) -> Circle { Circle::new(radius) } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Circle where Renderer: renderer::Renderer, { fn size(&self) -> Size<Length> { Size { width: Length::Shrink, height: Length::Shrink, } } fn layout( &mut self, _tree: &mut widget::Tree, _renderer: &Renderer, _limits: &layout::Limits, ) -> layout::Node { layout::Node::new(Size::new(self.radius * 2.0, self.radius * 2.0)) } fn draw( &self, _tree: &widget::Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { renderer.fill_quad( renderer::Quad { bounds: layout.bounds(), border: border::rounded(self.radius), ..renderer::Quad::default() }, Color::BLACK, ); } } impl<Message, Theme, Renderer> From<Circle> for Element<'_, Message, Theme, Renderer> where Renderer: renderer::Renderer, { fn from(circle: Circle) -> Self { Self::new(circle) } } } use circle::circle; use iced::widget::{center, column, slider, text}; use iced::{Center, Element}; pub fn main() -> iced::Result { iced::run(Example::update, Example::view) } struct Example { radius: f32, } #[derive(Debug, Clone, Copy)] enum Message { RadiusChanged(f32), } impl Example { fn new() -> Self { Example { radius: 50.0 } } fn update(&mut self, message: Message) { match message { Message::RadiusChanged(radius) => { self.radius = radius; } } } fn view(&self) -> Element<'_, Message> { let content = column![ circle(self.radius), text!("Radius: {:.2}", self.radius), slider(1.0..=100.0, self.radius, Message::RadiusChanged).step(0.01), ] .padding(20) .spacing(20) .max_width(500) .align_x(Center); center(content).into() } } impl Default for Example { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/tour/src/main.rs
examples/tour/src/main.rs
use iced::widget::{Button, Column, Container, Slider}; use iced::widget::{ button, center_x, center_y, checkbox, column, image, radio, rich_text, row, scrollable, slider, space, span, text, text_input, toggler, }; use iced::{Center, Color, Element, Fill, Font, Pixels, color}; pub fn main() -> iced::Result { #[cfg(target_arch = "wasm32")] { console_log::init().expect("Initialize logger"); std::panic::set_hook(Box::new(console_error_panic_hook::hook)); } #[cfg(not(target_arch = "wasm32"))] tracing_subscriber::fmt::init(); iced::application(Tour::default, Tour::update, Tour::view) .title(Tour::title) .centered() .run() } pub struct Tour { screen: Screen, slider: u8, layout: Layout, spacing: u32, text_size: u32, text_color: Color, language: Option<Language>, toggler: bool, image_width: u32, image_filter_method: image::FilterMethod, input_value: String, input_is_secure: bool, input_is_showing_icon: bool, debug: bool, } #[derive(Debug, Clone)] pub enum Message { BackPressed, NextPressed, SliderChanged(u8), LayoutChanged(Layout), SpacingChanged(u32), TextSizeChanged(u32), TextColorChanged(Color), LanguageSelected(Language), ImageWidthChanged(u32), ImageUseNearestToggled(bool), InputChanged(String), ToggleSecureInput(bool), ToggleTextInputIcon(bool), DebugToggled(bool), TogglerChanged(bool), OpenTrunk, } impl Tour { fn title(&self) -> String { let screen = match self.screen { Screen::Welcome => "Welcome", Screen::Radio => "Radio button", Screen::Toggler => "Toggler", Screen::Slider => "Slider", Screen::Text => "Text", Screen::Image => "Image", Screen::RowsAndColumns => "Rows and columns", Screen::Scrollable => "Scrollable", Screen::TextInput => "Text input", Screen::Debugger => "Debugger", Screen::End => "End", }; format!("{screen} - Iced") } fn update(&mut self, event: Message) { match event { Message::BackPressed => { if let Some(screen) = self.screen.previous() { self.screen = screen; } } Message::NextPressed => { if let Some(screen) = self.screen.next() { self.screen = screen; } } Message::SliderChanged(value) => { self.slider = value; } Message::LayoutChanged(layout) => { self.layout = layout; } Message::SpacingChanged(spacing) => { self.spacing = spacing; } Message::TextSizeChanged(text_size) => { self.text_size = text_size; } Message::TextColorChanged(text_color) => { self.text_color = text_color; } Message::LanguageSelected(language) => { self.language = Some(language); } Message::ImageWidthChanged(image_width) => { self.image_width = image_width; } Message::ImageUseNearestToggled(use_nearest) => { self.image_filter_method = if use_nearest { image::FilterMethod::Nearest } else { image::FilterMethod::Linear }; } Message::InputChanged(input_value) => { self.input_value = input_value; } Message::ToggleSecureInput(is_secure) => { self.input_is_secure = is_secure; } Message::ToggleTextInputIcon(show_icon) => { self.input_is_showing_icon = show_icon; } Message::DebugToggled(debug) => { self.debug = debug; } Message::TogglerChanged(toggler) => { self.toggler = toggler; } Message::OpenTrunk => { #[cfg(not(target_arch = "wasm32"))] let _ = open::that_in_background("https://trunkrs.dev"); } } } fn view(&self) -> Element<'_, Message> { let controls = row![ self.screen.previous().is_some().then(|| { padded_button("Back") .on_press(Message::BackPressed) .style(button::secondary) }), space::horizontal(), self.can_continue() .then(|| { padded_button("Next").on_press(Message::NextPressed) }) ]; let screen = match self.screen { Screen::Welcome => self.welcome(), Screen::Radio => self.radio(), Screen::Toggler => self.toggler(), Screen::Slider => self.slider(), Screen::Text => self.text(), Screen::Image => self.image(), Screen::RowsAndColumns => self.rows_and_columns(), Screen::Scrollable => self.scrollable(), Screen::TextInput => self.text_input(), Screen::Debugger => self.debugger(), Screen::End => self.end(), }; let content: Element<_> = column![screen, controls].max_width(540).spacing(20).into(); let scrollable = scrollable(center_x(if self.debug { content.explain(Color::BLACK) } else { content })) .spacing(10) .auto_scroll(true); center_y(scrollable).padding(10).into() } fn can_continue(&self) -> bool { match self.screen { Screen::Welcome => true, Screen::Radio => self.language == Some(Language::Rust), Screen::Toggler => self.toggler, Screen::Slider => true, Screen::Text => true, Screen::Image => true, Screen::RowsAndColumns => true, Screen::Scrollable => true, Screen::TextInput => !self.input_value.is_empty(), Screen::Debugger => true, Screen::End => false, } } fn welcome(&self) -> Column<'_, Message> { Self::container("Welcome!") .push( "This is a simple tour meant to showcase a bunch of \ widgets that come bundled in Iced.", ) .push( "Iced is a cross-platform GUI library for Rust focused on \ simplicity and type-safety. It is heavily inspired by Elm.", ) .push( "It was originally born as part of Coffee, an opinionated \ 2D game engine for Rust.", ) .push( "On native platforms, Iced provides by default a renderer \ built on top of wgpu, a graphics library supporting Vulkan, \ Metal, DX11, and DX12.", ) .push( rich_text![ "Additionally, this tour can also run on WebAssembly ", "by leveraging ", span("trunk") .color(color!(0x7777FF)) .underline(true) .font(Font::MONOSPACE) .link(Message::OpenTrunk), "." ] .on_link_click(std::convert::identity), ) .push( "You will need to interact with the UI in order to reach \ the end!", ) } fn slider(&self) -> Column<'_, Message> { Self::container("Slider") .push( "A slider allows you to smoothly select a value from a range \ of values.", ) .push( "The following slider lets you choose an integer from \ 0 to 100:", ) .push(slider(0..=100, self.slider, Message::SliderChanged)) .push(text(self.slider.to_string()).width(Fill).align_x(Center)) } fn rows_and_columns(&self) -> Column<'_, Message> { let row_radio = radio( "Row", Layout::Row, Some(self.layout), Message::LayoutChanged, ); let column_radio = radio( "Column", Layout::Column, Some(self.layout), Message::LayoutChanged, ); let layout_section: Element<_> = match self.layout { Layout::Row => row![row_radio, column_radio].spacing(self.spacing).into(), Layout::Column => column![row_radio, column_radio] .spacing(self.spacing) .into(), }; let spacing_section = column![ slider(0..=80, self.spacing, Message::SpacingChanged), text!("{} px", self.spacing).width(Fill).align_x(Center), ] .spacing(10); Self::container("Rows and columns") .spacing(self.spacing) .push( "Iced uses a layout model based on flexbox to position UI \ elements.", ) .push( "Rows and columns can be used to distribute content \ horizontally or vertically, respectively.", ) .push(layout_section) .push("You can also easily change the spacing between elements:") .push(spacing_section) } fn text(&self) -> Column<'_, Message> { let size = self.text_size; let color = self.text_color; let size_section = column![ "You can change its size:", text!("This text is {size} pixels").size(size), slider(3..=70, size, Message::TextSizeChanged), ] .padding(20) .spacing(20); let color_sliders = row![ color_slider(color.r, move |r| Color { r, ..color }), color_slider(color.g, move |g| Color { g, ..color }), color_slider(color.b, move |b| Color { b, ..color }), ] .spacing(10); let color_section = column![ "And its color:", text!("{color:?}").color(color), color_sliders, ] .padding(20) .spacing(20); Self::container("Text") .push( "Text is probably the most essential widget for your UI. \ It will try to adapt to the dimensions of its container.", ) .push(size_section) .push(color_section) } fn radio(&self) -> Column<'_, Message> { let question = column![ text("Iced is written in...").size(24), column( Language::all() .iter() .copied() .map(|language| { radio(language, language, self.language, Message::LanguageSelected) }) .map(Element::from) ) .spacing(10) ] .padding(20) .spacing(10); Self::container("Radio button") .push( "A radio button is normally used to represent a choice... \ Surprise test!", ) .push(question) .push( "Iced works very well with iterators! The list above is \ basically created by folding a column over the different \ choices, creating a radio button for each one of them!", ) } fn toggler(&self) -> Column<'_, Message> { Self::container("Toggler") .push("A toggler is mostly used to enable or disable something.") .push( Container::new( toggler(self.toggler) .label("Toggle me to continue...") .on_toggle(Message::TogglerChanged), ) .padding([0, 40]), ) } fn image(&self) -> Column<'_, Message> { let width = self.image_width; let filter_method = self.image_filter_method; Self::container("Image") .push("An image that tries to keep its aspect ratio.") .push(ferris(width, filter_method)) .push(slider(100..=500, width, Message::ImageWidthChanged)) .push(text!("Width: {width} px").width(Fill).align_x(Center)) .push( checkbox(filter_method == image::FilterMethod::Nearest) .label("Use nearest interpolation") .on_toggle(Message::ImageUseNearestToggled), ) .align_x(Center) } fn scrollable(&self) -> Column<'_, Message> { Self::container("Scrollable") .push( "Iced supports scrollable content. Try it out! Find the \ button further below.", ) .push(text("Tip: You can use the scrollbar to scroll down faster!").size(16)) .push(space().height(4096)) .push( text("You are halfway there!") .width(Fill) .size(30) .align_x(Center), ) .push(space().height(4096)) .push(ferris(300, image::FilterMethod::Linear)) .push(text("You made it!").width(Fill).size(50).align_x(Center)) } fn text_input(&self) -> Column<'_, Message> { let value = &self.input_value; let is_secure = self.input_is_secure; let is_showing_icon = self.input_is_showing_icon; let mut text_input = text_input("Type something to continue...", value) .on_input(Message::InputChanged) .padding(10) .size(30); if is_showing_icon { text_input = text_input.icon(text_input::Icon { font: Font::default(), code_point: '🚀', size: Some(Pixels(28.0)), spacing: 10.0, side: text_input::Side::Right, }); } Self::container("Text input") .push("Use a text input to ask for different kinds of information.") .push(text_input.secure(is_secure)) .push( checkbox(is_secure) .label("Enable password mode") .on_toggle(Message::ToggleSecureInput), ) .push( checkbox(is_showing_icon) .label("Show icon") .on_toggle(Message::ToggleTextInputIcon), ) .push( "A text input produces a message every time it changes. It is \ very easy to keep track of its contents:", ) .push( text(if value.is_empty() { "You have not typed anything yet..." } else { value }) .width(Fill) .align_x(Center), ) } fn debugger(&self) -> Column<'_, Message> { Self::container("Debugger") .push( "You can ask Iced to visually explain the layouting of the \ different elements comprising your UI!", ) .push( "Give it a shot! Check the following checkbox to be able to \ see element boundaries.", ) .push( checkbox(self.debug) .label("Explain layout") .on_toggle(Message::DebugToggled), ) .push("Feel free to go back and take a look.") } fn end(&self) -> Column<'_, Message> { Self::container("You reached the end!") .push("This tour will be updated as more features are added.") .push("Make sure to keep an eye on it!") } fn container(title: &str) -> Column<'_, Message> { column![text(title).size(50)].spacing(20) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Screen { Welcome, Slider, RowsAndColumns, Text, Radio, Toggler, Image, Scrollable, TextInput, Debugger, End, } impl Screen { const ALL: &'static [Self] = &[ Self::Welcome, Self::Slider, Self::RowsAndColumns, Self::Text, Self::Radio, Self::Toggler, Self::Image, Self::Scrollable, Self::TextInput, Self::Debugger, Self::End, ]; pub fn next(self) -> Option<Screen> { Self::ALL .get( Self::ALL .iter() .copied() .position(|screen| screen == self) .expect("Screen must exist") + 1, ) .copied() } pub fn previous(self) -> Option<Screen> { let position = Self::ALL .iter() .copied() .position(|screen| screen == self) .expect("Screen must exist"); if position > 0 { Some(Self::ALL[position - 1]) } else { None } } } fn ferris<'a>(width: u32, filter_method: image::FilterMethod) -> Container<'a, Message> { center_x( // This should go away once we unify resource loading on native // platforms if cfg!(target_arch = "wasm32") { image("tour/images/ferris.png") } else { image(concat!(env!("CARGO_MANIFEST_DIR"), "/images/ferris.png")) } .filter_method(filter_method) .width(width), ) } fn padded_button<Message: Clone>(label: &str) -> Button<'_, Message> { button(text(label)).padding([12, 24]) } fn color_slider<'a>( component: f32, update: impl Fn(f32) -> Color + 'a, ) -> Slider<'a, f64, Message> { slider(0.0..=1.0, f64::from(component), move |c| { Message::TextColorChanged(update(c as f32)) }) .step(0.01) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Language { Rust, Elm, Ruby, Haskell, C, Other, } impl Language { fn all() -> [Language; 6] { [ Language::C, Language::Elm, Language::Ruby, Language::Haskell, Language::Rust, Language::Other, ] } } impl From<Language> for String { fn from(language: Language) -> String { String::from(match language { Language::Rust => "Rust", Language::Elm => "Elm", Language::Ruby => "Ruby", Language::Haskell => "Haskell", Language::C => "C", Language::Other => "Other", }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Layout { Row, Column, } impl Default for Tour { fn default() -> Self { Self { screen: Screen::Welcome, slider: 50, layout: Layout::Row, spacing: 20, text_size: 30, text_color: Color::BLACK, language: None, toggler: false, image_width: 300, image_filter_method: image::FilterMethod::Linear, input_value: String::new(), input_is_secure: false, input_is_showing_icon: false, debug: false, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/gallery/src/civitai.rs
examples/gallery/src/civitai.rs
use serde::Deserialize; use sipper::{Straw, sipper}; use tokio::task; use std::fmt; use std::io; use std::sync::{Arc, LazyLock}; static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new); #[derive(Debug, Clone, Deserialize)] pub struct Image { pub id: Id, url: String, hash: String, } impl Image { pub const LIMIT: usize = 96; pub async fn list() -> Result<Vec<Self>, Error> { #[derive(Deserialize)] struct Response { items: Vec<Image>, } let response: Response = CLIENT .get("https://civitai.com/api/v1/images") .query(&[ ("sort", "Most Reactions"), ("period", "Month"), ("nsfw", "None"), ("limit", &Image::LIMIT.to_string()), ]) .send() .await? .error_for_status()? .json() .await?; Ok(response .items .into_iter() .filter(|image| !image.url.ends_with(".mp4")) .collect()) } pub async fn blurhash(self, width: u32, height: u32) -> Result<Blurhash, Error> { task::spawn_blocking(move || { let pixels = blurhash::decode(&self.hash, width, height, 1.0)?; Ok::<_, Error>(Blurhash { rgba: Rgba { width, height, pixels: Bytes(pixels.into()), }, }) }) .await? } pub fn download(self, size: Size) -> impl Straw<Bytes, Blurhash, Error> { sipper(async move |mut sender| { if let Size::Thumbnail { width, height } = size { let image = self.clone(); drop(task::spawn(async move { if let Ok(blurhash) = image.blurhash(width, height).await { sender.send(blurhash).await; } })); } let bytes = CLIENT .get(match size { Size::Original => self.url, Size::Thumbnail { width, .. } => self .url .split("/") .map(|part| { if part.starts_with("width=") || part.starts_with("original=") { format!("width={}", width * 2) // High DPI } else { part.to_owned() } }) .collect::<Vec<_>>() .join("/"), }) .send() .await? .error_for_status()? .bytes() .await?; Ok(Bytes(bytes)) }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] pub struct Id(u32); #[derive(Debug, Clone)] pub struct Blurhash { pub rgba: Rgba, } #[derive(Clone)] pub struct Rgba { pub width: u32, pub height: u32, pub pixels: Bytes, } impl fmt::Debug for Rgba { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Rgba") .field("width", &self.width) .field("height", &self.height) .finish() } } #[derive(Clone)] pub struct Bytes(bytes::Bytes); impl Bytes { pub fn as_slice(&self) -> &[u8] { &self.0 } } impl From<Bytes> for bytes::Bytes { fn from(value: Bytes) -> Self { value.0 } } impl fmt::Debug for Bytes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Compressed") .field("bytes", &self.0.len()) .finish() } } #[derive(Debug, Clone, Copy)] pub enum Size { Original, Thumbnail { width: u32, height: u32 }, } #[derive(Debug, Clone)] #[allow(dead_code)] pub enum Error { RequestFailed(Arc<reqwest::Error>), IOFailed(Arc<io::Error>), JoinFailed(Arc<task::JoinError>), ImageDecodingFailed, BlurhashDecodingFailed(Arc<blurhash::Error>), } impl From<reqwest::Error> for Error { fn from(error: reqwest::Error) -> Self { Self::RequestFailed(Arc::new(error)) } } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Self::IOFailed(Arc::new(error)) } } impl From<task::JoinError> for Error { fn from(error: task::JoinError) -> Self { Self::JoinFailed(Arc::new(error)) } } impl From<blurhash::Error> for Error { fn from(error: blurhash::Error) -> Self { Self::BlurhashDecodingFailed(Arc::new(error)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/gallery/src/main.rs
examples/gallery/src/main.rs
//! A simple gallery that displays the daily featured images of Civitai. //! //! Showcases lazy loading of images in the background, as well as //! some smooth animations. mod civitai; use crate::civitai::{Bytes, Error, Id, Image, Rgba, Size}; use iced::animation; use iced::border; use iced::time::{Instant, milliseconds}; use iced::widget::{ button, container, float, grid, image, mouse_area, opaque, scrollable, sensor, space, stack, }; use iced::window; use iced::{ Animation, Color, ContentFit, Element, Fill, Function, Shadow, Subscription, Task, Theme, color, }; use std::collections::{HashMap, HashSet}; fn main() -> iced::Result { iced::application::timed( Gallery::new, Gallery::update, Gallery::subscription, Gallery::view, ) .window_size((Preview::WIDTH as f32 * 4.0, Preview::HEIGHT as f32 * 2.5)) .theme(Gallery::theme) .run() } struct Gallery { images: Vec<Image>, previews: HashMap<Id, Preview>, visible: HashSet<Id>, downloaded: HashSet<Id>, viewer: Viewer, now: Instant, } #[derive(Debug, Clone)] enum Message { ImagesListed(Result<Vec<Image>, Error>), ImagePoppedIn(Id), ImagePoppedOut(Id), ImageDownloaded(Result<image::Allocation, Error>), ThumbnailDownloaded(Id, Result<Bytes, Error>), ThumbnailAllocated(Id, Result<image::Allocation, image::Error>), ThumbnailHovered(Id, bool), BlurhashDecoded(Id, civitai::Blurhash), Open(Id), Close, Animate, } impl Gallery { pub fn new() -> (Self, Task<Message>) { ( Self { images: Vec::new(), previews: HashMap::new(), visible: HashSet::new(), downloaded: HashSet::new(), viewer: Viewer::new(), now: Instant::now(), }, Task::perform(Image::list(), Message::ImagesListed), ) } pub fn theme(&self) -> Theme { Theme::TokyoNight } pub fn subscription(&self) -> Subscription<Message> { let is_animating = self .previews .values() .any(|preview| preview.is_animating(self.now)) || self.viewer.is_animating(self.now); if is_animating { window::frames().map(|_| Message::Animate) } else { Subscription::none() } } pub fn update(&mut self, message: Message, now: Instant) -> Task<Message> { self.now = now; match message { Message::ImagesListed(Ok(images)) => { self.images = images; Task::none() } Message::ImagePoppedIn(id) => { let Some(image) = self .images .iter() .find(|candidate| candidate.id == id) .cloned() else { return Task::none(); }; let _ = self.visible.insert(id); if self.downloaded.contains(&id) { let Some(Preview::Ready { thumbnail, blurhash, }) = self.previews.get_mut(&id) else { return Task::none(); }; if let Some(blurhash) = blurhash { blurhash.show(now); } return to_rgba(thumbnail.bytes.clone()) .then(image::allocate) .map(Message::ThumbnailAllocated.with(id)); } let _ = self.downloaded.insert(id); Task::sip( image.download(Size::Thumbnail { width: Preview::WIDTH, height: Preview::HEIGHT, }), Message::BlurhashDecoded.with(id), Message::ThumbnailDownloaded.with(id), ) } Message::ImagePoppedOut(id) => { let _ = self.visible.remove(&id); if let Some(Preview::Ready { thumbnail, blurhash, }) = self.previews.get_mut(&id) { thumbnail.reset(); if let Some(blurhash) = blurhash { blurhash.reset(); } } Task::none() } Message::ImageDownloaded(Ok(allocation)) => { self.viewer.show(allocation, self.now); Task::none() } Message::ThumbnailDownloaded(id, Ok(bytes)) => { let preview = if let Some(preview) = self.previews.remove(&id) { preview.load(bytes.clone()) } else { Preview::ready(bytes.clone()) }; let _ = self.previews.insert(id, preview); to_rgba(bytes) .then(image::allocate) .map(Message::ThumbnailAllocated.with(id)) } Message::ThumbnailAllocated(id, Ok(allocation)) => { if !self.visible.contains(&id) { return Task::none(); } let Some(Preview::Ready { thumbnail, .. }) = self.previews.get_mut(&id) else { return Task::none(); }; thumbnail.show(allocation, now); Task::none() } Message::ThumbnailHovered(id, is_hovered) => { if let Some(preview) = self.previews.get_mut(&id) { preview.toggle_zoom(is_hovered, self.now); } Task::none() } Message::BlurhashDecoded(id, blurhash) => { if !self.previews.contains_key(&id) { let _ = self .previews .insert(id, Preview::loading(blurhash.rgba, self.now)); } Task::none() } Message::Open(id) => { let Some(image) = self .images .iter() .find(|candidate| candidate.id == id) .cloned() else { return Task::none(); }; self.viewer.open(self.now); Task::future(image.download(Size::Original)) .and_then(|bytes| { image::allocate(image::Handle::from_bytes(bytes)) .map_err(|_| Error::ImageDecodingFailed) }) .map(Message::ImageDownloaded) } Message::Close => { self.viewer.close(self.now); Task::none() } Message::Animate => Task::none(), Message::ImagesListed(Err(error)) | Message::ImageDownloaded(Err(error)) | Message::ThumbnailDownloaded(_, Err(error)) => { dbg!(error); Task::none() } Message::ThumbnailAllocated(_, Err(error)) => { dbg!(error); Task::none() } } } pub fn view(&self) -> Element<'_, Message> { let images = self .images .iter() .map(|image| { card( image, if self.visible.contains(&image.id) { self.previews.get(&image.id) } else { None }, self.now, ) }) .chain( if self.images.is_empty() { 0..Image::LIMIT } else { 0..0 } .map(|_| placeholder()), ); let gallery = grid(images) .fluid(Preview::WIDTH) .height(grid::aspect_ratio(Preview::WIDTH, Preview::HEIGHT)) .spacing(10); let content = container(scrollable(gallery).spacing(10).auto_scroll(true)).padding(10); let viewer = self.viewer.view(self.now); stack![content, viewer].into() } } fn card<'a>( metadata: &'a Image, preview: Option<&'a Preview>, now: Instant, ) -> Element<'a, Message> { let image = if let Some(preview) = preview { let thumbnail: Element<'_, _> = if let Preview::Ready { thumbnail, .. } = &preview && let Some(allocation) = &thumbnail.allocation { float( image(allocation.handle()) .width(Fill) .content_fit(ContentFit::Cover) .opacity(thumbnail.fade_in.interpolate(0.0, 1.0, now)) .border_radius(BORDER_RADIUS), ) .scale(thumbnail.zoom.interpolate(1.0, 1.1, now)) .translate(move |bounds, viewport| { bounds.zoom(1.1).offset(&viewport.shrink(10)) * thumbnail.zoom.interpolate(0.0, 1.0, now) }) .style(move |_theme| float::Style { shadow: Shadow { color: Color::BLACK.scale_alpha(thumbnail.zoom.interpolate(0.0, 1.0, now)), blur_radius: thumbnail.zoom.interpolate(0.0, 20.0, now), ..Shadow::default() }, shadow_border_radius: border::radius(BORDER_RADIUS), }) .into() } else { space::horizontal().into() }; if let Some(blurhash) = preview.blurhash(now) { let blurhash = image(&blurhash.handle) .width(Fill) .content_fit(ContentFit::Cover) .opacity(blurhash.fade_in.interpolate(0.0, 1.0, now)) .border_radius(BORDER_RADIUS); stack![blurhash, thumbnail].into() } else { thumbnail } } else { space::horizontal().into() }; let card = mouse_area(container(image).style(rounded)) .on_enter(Message::ThumbnailHovered(metadata.id, true)) .on_exit(Message::ThumbnailHovered(metadata.id, false)); let card: Element<'_, _> = if let Some(preview) = preview { let is_thumbnail = matches!(preview, Preview::Ready { .. }); button(card) .on_press_maybe(is_thumbnail.then_some(Message::Open(metadata.id))) .padding(0) .style(button::text) .into() } else { card.into() }; sensor(card) .on_show(|_| Message::ImagePoppedIn(metadata.id)) .on_hide(Message::ImagePoppedOut(metadata.id)) .into() } fn placeholder<'a>() -> Element<'a, Message> { container(space()).style(rounded).into() } enum Preview { Loading { blurhash: Blurhash, }, Ready { blurhash: Option<Blurhash>, thumbnail: Thumbnail, }, } struct Blurhash { handle: image::Handle, fade_in: Animation<bool>, } impl Blurhash { pub fn show(&mut self, now: Instant) { self.fade_in.go_mut(true, now); } pub fn reset(&mut self) { self.fade_in = Animation::new(false) .easing(animation::Easing::EaseIn) .very_quick(); } } struct Thumbnail { bytes: Bytes, allocation: Option<image::Allocation>, fade_in: Animation<bool>, zoom: Animation<bool>, } impl Preview { const WIDTH: u32 = 320; const HEIGHT: u32 = 410; fn loading(rgba: Rgba, now: Instant) -> Self { Self::Loading { blurhash: Blurhash { fade_in: Animation::new(false) .duration(milliseconds(700)) .easing(animation::Easing::EaseIn) .go(true, now), handle: image::Handle::from_rgba(rgba.width, rgba.height, rgba.pixels), }, } } fn ready(bytes: Bytes) -> Self { Self::Ready { blurhash: None, thumbnail: Thumbnail::new(bytes), } } fn load(self, bytes: Bytes) -> Self { let Self::Loading { blurhash } = self else { return self; }; Self::Ready { blurhash: Some(blurhash), thumbnail: Thumbnail::new(bytes), } } fn toggle_zoom(&mut self, enabled: bool, now: Instant) { if let Self::Ready { thumbnail, .. } = self { thumbnail.zoom.go_mut(enabled, now); } } fn is_animating(&self, now: Instant) -> bool { match &self { Self::Loading { blurhash } => blurhash.fade_in.is_animating(now), Self::Ready { thumbnail, blurhash, } => { thumbnail.fade_in.is_animating(now) || thumbnail.zoom.is_animating(now) || blurhash .as_ref() .is_some_and(|blurhash| blurhash.fade_in.is_animating(now)) } } } fn blurhash(&self, now: Instant) -> Option<&Blurhash> { match self { Self::Loading { blurhash, .. } => Some(blurhash), Self::Ready { blurhash: Some(blurhash), thumbnail, .. } if !thumbnail.fade_in.value() || thumbnail.fade_in.is_animating(now) => { Some(blurhash) } Self::Ready { .. } => None, } } } impl Thumbnail { pub fn new(bytes: Bytes) -> Self { Self { bytes, allocation: None, fade_in: Animation::new(false) .easing(animation::Easing::EaseIn) .slow(), zoom: Animation::new(false) .quick() .easing(animation::Easing::EaseInOut), } } pub fn reset(&mut self) { self.allocation = None; self.fade_in = Animation::new(false) .easing(animation::Easing::EaseIn) .quick(); } pub fn show(&mut self, allocation: image::Allocation, now: Instant) { self.allocation = Some(allocation); self.fade_in.go_mut(true, now); } } struct Viewer { image: Option<image::Allocation>, background_fade_in: Animation<bool>, image_fade_in: Animation<bool>, } impl Viewer { fn new() -> Self { Self { image: None, background_fade_in: Animation::new(false) .very_slow() .easing(animation::Easing::EaseInOut), image_fade_in: Animation::new(false) .very_slow() .easing(animation::Easing::EaseInOut), } } fn open(&mut self, now: Instant) { self.image = None; self.background_fade_in.go_mut(true, now); } fn show(&mut self, allocation: image::Allocation, now: Instant) { self.image = Some(allocation); self.background_fade_in.go_mut(true, now); self.image_fade_in.go_mut(true, now); } fn close(&mut self, now: Instant) { self.background_fade_in.go_mut(false, now); self.image_fade_in.go_mut(false, now); } fn is_animating(&self, now: Instant) -> bool { self.background_fade_in.is_animating(now) || self.image_fade_in.is_animating(now) } fn view(&self, now: Instant) -> Option<Element<'_, Message>> { let opacity = self.background_fade_in.interpolate(0.0, 0.8, now); if opacity <= 0.0 { return None; } let image = self.image.as_ref().map(|allocation| { image(allocation.handle()) .width(Fill) .height(Fill) .opacity(self.image_fade_in.interpolate(0.0, 1.0, now)) .scale(self.image_fade_in.interpolate(1.5, 1.0, now)) }); Some(opaque( mouse_area( container(image) .center(Fill) .style(move |_theme| { container::Style::default().background(color!(0x000000, opacity)) }) .padding(20), ) .on_press(Message::Close), )) } } fn to_rgba(bytes: Bytes) -> Task<image::Handle> { Task::future(async move { tokio::task::spawn_blocking(move || match ::image::load_from_memory(bytes.as_slice()) { Ok(image) => { let rgba = image.to_rgba8(); image::Handle::from_rgba(rgba.width(), rgba.height(), rgba.into_raw()) } _ => image::Handle::from_bytes(bytes), }) .await .unwrap() }) } fn rounded(theme: &Theme) -> container::Style { container::dark(theme).border(border::rounded(BORDER_RADIUS)) } const BORDER_RADIUS: u32 = 10;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/pane_grid/src/main.rs
examples/pane_grid/src/main.rs
use iced::keyboard; use iced::widget::pane_grid::{self, PaneGrid}; use iced::widget::{button, center_y, column, container, responsive, row, scrollable, text}; use iced::{Center, Color, Element, Fill, Size, Subscription}; pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view) .subscription(Example::subscription) .run() } struct Example { panes: pane_grid::State<Pane>, panes_created: usize, focus: Option<pane_grid::Pane>, } #[derive(Debug, Clone, Copy)] enum Message { Split(pane_grid::Axis, pane_grid::Pane), SplitFocused(pane_grid::Axis), FocusAdjacent(pane_grid::Direction), Clicked(pane_grid::Pane), Dragged(pane_grid::DragEvent), Resized(pane_grid::ResizeEvent), TogglePin(pane_grid::Pane), Maximize(pane_grid::Pane), Restore, Close(pane_grid::Pane), CloseFocused, } impl Example { fn new() -> Self { let (panes, _) = pane_grid::State::new(Pane::new(0)); Example { panes, panes_created: 1, focus: None, } } fn update(&mut self, message: Message) { match message { Message::Split(axis, pane) => { let result = self.panes.split(axis, pane, Pane::new(self.panes_created)); if let Some((pane, _)) = result { self.focus = Some(pane); } self.panes_created += 1; } Message::SplitFocused(axis) => { if let Some(pane) = self.focus { let result = self.panes.split(axis, pane, Pane::new(self.panes_created)); if let Some((pane, _)) = result { self.focus = Some(pane); } self.panes_created += 1; } } Message::FocusAdjacent(direction) => { if let Some(pane) = self.focus && let Some(adjacent) = self.panes.adjacent(pane, direction) { self.focus = Some(adjacent); } } Message::Clicked(pane) => { self.focus = Some(pane); } Message::Resized(pane_grid::ResizeEvent { split, ratio }) => { self.panes.resize(split, ratio); } Message::Dragged(pane_grid::DragEvent::Dropped { pane, target }) => { self.panes.drop(pane, target); } Message::Dragged(_) => {} Message::TogglePin(pane) => { if let Some(Pane { is_pinned, .. }) = self.panes.get_mut(pane) { *is_pinned = !*is_pinned; } } Message::Maximize(pane) => self.panes.maximize(pane), Message::Restore => { self.panes.restore(); } Message::Close(pane) => { if let Some((_, sibling)) = self.panes.close(pane) { self.focus = Some(sibling); } } Message::CloseFocused => { if let Some(pane) = self.focus && let Some(Pane { is_pinned, .. }) = self.panes.get(pane) && !is_pinned && let Some((_, sibling)) = self.panes.close(pane) { self.focus = Some(sibling); } } } } fn subscription(&self) -> Subscription<Message> { keyboard::listen().filter_map(|event| { let keyboard::Event::KeyPressed { key, modifiers, .. } = event else { return None; }; if !modifiers.command() { return None; } handle_hotkey(key) }) } fn view(&self) -> Element<'_, Message> { let focus = self.focus; let total_panes = self.panes.len(); let pane_grid = PaneGrid::new(&self.panes, |id, pane, is_maximized| { let is_focused = focus == Some(id); let pin_button = button(text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14)) .on_press(Message::TogglePin(id)) .padding(3); let title = row![ pin_button, "Pane", text(pane.id.to_string()).color(if is_focused { PANE_ID_COLOR_FOCUSED } else { PANE_ID_COLOR_UNFOCUSED }), ] .spacing(5); let title_bar = pane_grid::TitleBar::new(title) .controls(pane_grid::Controls::dynamic( view_controls(id, total_panes, pane.is_pinned, is_maximized), button(text("X").size(14)) .style(button::danger) .padding(3) .on_press_maybe(if total_panes > 1 && !pane.is_pinned { Some(Message::Close(id)) } else { None }), )) .padding(10) .style(if is_focused { style::title_bar_focused } else { style::title_bar_active }); pane_grid::Content::new(responsive(move |size| { view_content(id, total_panes, pane.is_pinned, size) })) .title_bar(title_bar) .style(if is_focused { style::pane_focused } else { style::pane_active }) }) .width(Fill) .height(Fill) .spacing(10) .on_click(Message::Clicked) .on_drag(Message::Dragged) .on_resize(10, Message::Resized); container(pane_grid).padding(10).into() } } impl Default for Example { fn default() -> Self { Example::new() } } const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( 0xFF as f32 / 255.0, 0xC7 as f32 / 255.0, 0xC7 as f32 / 255.0, ); const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( 0xFF as f32 / 255.0, 0x47 as f32 / 255.0, 0x47 as f32 / 255.0, ); fn handle_hotkey(key: keyboard::Key) -> Option<Message> { use keyboard::key::{self, Key}; use pane_grid::{Axis, Direction}; match key.as_ref() { Key::Character("v") => Some(Message::SplitFocused(Axis::Vertical)), Key::Character("h") => Some(Message::SplitFocused(Axis::Horizontal)), Key::Character("w") => Some(Message::CloseFocused), Key::Named(key) => { let direction = match key { key::Named::ArrowUp => Some(Direction::Up), key::Named::ArrowDown => Some(Direction::Down), key::Named::ArrowLeft => Some(Direction::Left), key::Named::ArrowRight => Some(Direction::Right), _ => None, }; direction.map(Message::FocusAdjacent) } _ => None, } } #[derive(Clone, Copy)] struct Pane { id: usize, pub is_pinned: bool, } impl Pane { fn new(id: usize) -> Self { Self { id, is_pinned: false, } } } fn view_content<'a>( pane: pane_grid::Pane, total_panes: usize, is_pinned: bool, size: Size, ) -> Element<'a, Message> { let button = |label, message| { button(text(label).width(Fill).align_x(Center).size(16)) .width(Fill) .padding(8) .on_press(message) }; let controls = column![ button( "Split horizontally", Message::Split(pane_grid::Axis::Horizontal, pane), ), button( "Split vertically", Message::Split(pane_grid::Axis::Vertical, pane), ), if total_panes > 1 && !is_pinned { Some(button("Close", Message::Close(pane)).style(button::danger)) } else { None } ] .spacing(5) .max_width(160); let content = column![text!("{}x{}", size.width, size.height).size(24), controls,] .spacing(10) .align_x(Center); center_y(scrollable(content)).padding(5).into() } fn view_controls<'a>( pane: pane_grid::Pane, total_panes: usize, is_pinned: bool, is_maximized: bool, ) -> Element<'a, Message> { let maximize = if total_panes > 1 { let (content, message) = if is_maximized { ("Restore", Message::Restore) } else { ("Maximize", Message::Maximize(pane)) }; Some( button(text(content).size(14)) .style(button::secondary) .padding(3) .on_press(message), ) } else { None }; let close = button(text("Close").size(14)) .style(button::danger) .padding(3) .on_press_maybe(if total_panes > 1 && !is_pinned { Some(Message::Close(pane)) } else { None }); row![maximize, close].spacing(5).into() } mod style { use iced::widget::container; use iced::{Border, Theme}; pub fn title_bar_active(theme: &Theme) -> container::Style { let palette = theme.extended_palette(); container::Style { text_color: Some(palette.background.strong.text), background: Some(palette.background.strong.color.into()), ..Default::default() } } pub fn title_bar_focused(theme: &Theme) -> container::Style { let palette = theme.extended_palette(); container::Style { text_color: Some(palette.primary.strong.text), background: Some(palette.primary.strong.color.into()), ..Default::default() } } pub fn pane_active(theme: &Theme) -> container::Style { let palette = theme.extended_palette(); container::Style { background: Some(palette.background.weak.color.into()), border: Border { width: 2.0, color: palette.background.strong.color, ..Border::default() }, ..Default::default() } } pub fn pane_focused(theme: &Theme) -> container::Style { let palette = theme.extended_palette(); container::Style { background: Some(palette.background.weak.color.into()), border: Border { width: 2.0, color: palette.primary.strong.color, ..Border::default() }, ..Default::default() } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/checkbox/src/main.rs
examples/checkbox/src/main.rs
use iced::widget::{center, checkbox, column, row, text}; use iced::{Element, Font}; const ICON_FONT: Font = Font::with_name("icons"); pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view) .font(include_bytes!("../fonts/icons.ttf").as_slice()) .run() } #[derive(Default)] struct Example { default: bool, styled: bool, custom: bool, } #[derive(Debug, Clone, Copy)] enum Message { DefaultToggled(bool), CustomToggled(bool), StyledToggled(bool), } impl Example { fn update(&mut self, message: Message) { match message { Message::DefaultToggled(default) => { self.default = default; } Message::StyledToggled(styled) => { self.styled = styled; } Message::CustomToggled(custom) => { self.custom = custom; } } } fn view(&self) -> Element<'_, Message> { let default_checkbox = checkbox(self.default) .label("Default") .on_toggle(Message::DefaultToggled); let styled_checkbox = |label| { checkbox(self.styled) .label(label) .on_toggle_maybe(self.default.then_some(Message::StyledToggled)) }; let checkboxes = row![ styled_checkbox("Primary").style(checkbox::primary), styled_checkbox("Secondary").style(checkbox::secondary), styled_checkbox("Success").style(checkbox::success), styled_checkbox("Danger").style(checkbox::danger), ] .spacing(20); let custom_checkbox = checkbox(self.custom) .label("Custom") .on_toggle(Message::CustomToggled) .icon(checkbox::Icon { font: ICON_FONT, code_point: '\u{e901}', size: None, line_height: text::LineHeight::Relative(1.0), shaping: text::Shaping::Basic, }); let content = column![default_checkbox, checkboxes, custom_checkbox].spacing(20); center(content).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/multitouch/src/main.rs
examples/multitouch/src/main.rs
//! This example shows how to use touch events in `Canvas` to draw //! a circle around each fingertip. This only works on touch-enabled //! computers like Microsoft Surface. use iced::mouse; use iced::touch; use iced::widget::canvas::stroke::{self, Stroke}; use iced::widget::canvas::{self, Canvas, Event, Geometry}; use iced::{Color, Element, Fill, Point, Rectangle, Renderer, Theme}; use std::collections::HashMap; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(Multitouch::default, Multitouch::update, Multitouch::view) .centered() .run() } #[derive(Default)] struct Multitouch { cache: canvas::Cache, fingers: HashMap<touch::Finger, Point>, } #[derive(Debug, Clone)] enum Message { FingerPressed { id: touch::Finger, position: Point }, FingerLifted { id: touch::Finger }, } impl Multitouch { fn update(&mut self, message: Message) { match message { Message::FingerPressed { id, position } => { self.fingers.insert(id, position); self.cache.clear(); } Message::FingerLifted { id } => { self.fingers.remove(&id); self.cache.clear(); } } } fn view(&self) -> Element<'_, Message> { Canvas::new(self).width(Fill).height(Fill).into() } } impl canvas::Program<Message> for Multitouch { type State = (); fn update( &self, _state: &mut Self::State, event: &Event, _bounds: Rectangle, _cursor: mouse::Cursor, ) -> Option<canvas::Action<Message>> { let message = match event.clone() { Event::Touch( touch::Event::FingerPressed { id, position } | touch::Event::FingerMoved { id, position }, ) => Some(Message::FingerPressed { id, position }), Event::Touch( touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. }, ) => Some(Message::FingerLifted { id }), _ => None, }; message .map(canvas::Action::publish) .map(canvas::Action::and_capture) } fn draw( &self, _state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { let fingerweb = self.cache.draw(renderer, bounds.size(), |frame| { if self.fingers.len() < 2 { return; } // Collect tuples of (id, point); let mut zones: Vec<(u64, Point)> = self.fingers.iter().map(|(id, pt)| (id.0, *pt)).collect(); // Sort by ID zones.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); // Generate sorted list of points let vpoints: Vec<(f64, f64)> = zones .iter() .map(|(_, p)| (f64::from(p.x), f64::from(p.y))) .collect(); let diagram: voronator::VoronoiDiagram<voronator::delaunator::Point> = voronator::VoronoiDiagram::from_tuple(&(0.0, 0.0), &(700.0, 700.0), &vpoints) .expect("Generate Voronoi diagram"); for (cell, zone) in diagram.cells().iter().zip(zones) { let mut builder = canvas::path::Builder::new(); for (index, p) in cell.points().iter().enumerate() { let p = Point::new(p.x as f32, p.y as f32); match index { 0 => builder.move_to(p), _ => builder.line_to(p), } } let path = builder.build(); let color_r = (10 % (zone.0 + 1)) as f32 / 20.0; let color_g = (10 % (zone.0 + 8)) as f32 / 20.0; let color_b = (10 % (zone.0 + 3)) as f32 / 20.0; frame.fill( &path, Color { r: color_r, g: color_g, b: color_b, a: 1.0, }, ); frame.stroke( &path, Stroke { style: stroke::Style::Solid(Color::BLACK), width: 3.0, ..Stroke::default() }, ); } }); vec![fingerweb] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/styling/src/main.rs
examples/styling/src/main.rs
use iced::keyboard; use iced::widget::{ button, center_x, center_y, checkbox, column, container, pick_list, progress_bar, row, rule, scrollable, slider, space, text, text_input, toggler, }; use iced::{Center, Element, Fill, Shrink, Subscription, Theme}; pub fn main() -> iced::Result { iced::application(Styling::default, Styling::update, Styling::view) .subscription(Styling::subscription) .theme(Styling::theme) .run() } #[derive(Default)] struct Styling { theme: Option<Theme>, input_value: String, slider_value: f32, checkbox_value: bool, toggler_value: bool, } #[derive(Debug, Clone)] enum Message { ThemeChanged(Theme), InputChanged(String), ButtonPressed, SliderChanged(f32), CheckboxToggled(bool), TogglerToggled(bool), PreviousTheme, NextTheme, ClearTheme, } impl Styling { fn update(&mut self, message: Message) { match message { Message::ThemeChanged(theme) => { self.theme = Some(theme); } Message::InputChanged(value) => self.input_value = value, Message::ButtonPressed => {} Message::SliderChanged(value) => self.slider_value = value, Message::CheckboxToggled(value) => self.checkbox_value = value, Message::TogglerToggled(value) => self.toggler_value = value, Message::PreviousTheme | Message::NextTheme => { let current = Theme::ALL .iter() .position(|candidate| self.theme.as_ref() == Some(candidate)); self.theme = Some(if matches!(message, Message::NextTheme) { Theme::ALL[current.map(|current| current + 1).unwrap_or(0) % Theme::ALL.len()] .clone() } else { let current = current.unwrap_or(0); if current == 0 { Theme::ALL .last() .expect("Theme::ALL must not be empty") .clone() } else { Theme::ALL[current - 1].clone() } }); } Message::ClearTheme => { self.theme = None; } } } fn view(&self) -> Element<'_, Message> { let choose_theme = column![ text("Theme:"), pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeChanged) .width(Fill) .placeholder("System"), ] .spacing(10); let text_input = text_input("Type something...", &self.input_value) .on_input(Message::InputChanged) .padding(10) .size(20); let buttons = { let styles = [ ("Primary", button::primary as fn(&Theme, _) -> _), ("Secondary", button::secondary), ("Success", button::success), ("Warning", button::warning), ("Danger", button::danger), ]; let styled_button = |label| button(text(label).width(Fill).center()).padding(10); column![ row(styles.into_iter().map(|(name, style)| styled_button(name) .on_press(Message::ButtonPressed) .style(style) .into())) .spacing(10) .align_y(Center), row(styles .into_iter() .map(|(name, style)| styled_button(name).style(style).into())) .spacing(10) .align_y(Center), ] .spacing(10) }; let slider = || slider(0.0..=100.0, self.slider_value, Message::SliderChanged); let progress_bar = || progress_bar(0.0..=100.0, self.slider_value); let scroll_me = scrollable(column!["Scroll me!", space().height(800), "You did it!"]) .width(Fill) .height(Fill) .auto_scroll(true); let check = checkbox(self.checkbox_value) .label("Check me!") .on_toggle(Message::CheckboxToggled); let check_disabled = checkbox(self.checkbox_value).label("Disabled"); let toggle = toggler(self.toggler_value) .label("Toggle me!") .on_toggle(Message::TogglerToggled); let disabled_toggle = toggler(self.toggler_value).label("Disabled"); let card = { container(column![text("Card Example").size(24), slider(), progress_bar(),].spacing(20)) .width(Fill) .padding(20) .style(container::bordered_box) }; let content = column![ choose_theme, rule::horizontal(1), text_input, buttons, slider(), progress_bar(), row![ scroll_me, rule::vertical(1), column![check, check_disabled, toggle, disabled_toggle].spacing(10), ] .spacing(10) .height(Shrink) .align_y(Center), card ] .spacing(20) .padding(20) .max_width(600); center_y(scrollable(center_x(content)).spacing(10)) .padding(10) .into() } fn subscription(&self) -> Subscription<Message> { keyboard::listen().filter_map(|event| { let keyboard::Event::KeyPressed { modified_key: keyboard::Key::Named(modified_key), repeat: false, .. } = event else { return None; }; match modified_key { keyboard::key::Named::ArrowUp | keyboard::key::Named::ArrowLeft => { Some(Message::PreviousTheme) } keyboard::key::Named::ArrowDown | keyboard::key::Named::ArrowRight => { Some(Message::NextTheme) } keyboard::key::Named::Space => Some(Message::ClearTheme), _ => None, } }) } fn theme(&self) -> Option<Theme> { self.theme.clone() } } #[cfg(test)] mod tests { use super::*; use rayon::prelude::*; use iced_test::{Error, simulator}; #[test] #[ignore] fn it_showcases_every_theme() -> Result<(), Error> { Theme::ALL .par_iter() .cloned() .map(|theme| { let mut styling = Styling::default(); styling.update(Message::ThemeChanged(theme.clone())); let mut ui = simulator(styling.view()); let snapshot = ui.snapshot(&theme)?; assert!( snapshot.matches_hash(format!( "snapshots/{theme}", theme = theme.to_string().to_ascii_lowercase().replace(" ", "_") ))?, "snapshots for {theme} should match!" ); Ok(()) }) .collect() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/lazy/src/main.rs
examples/lazy/src/main.rs
use iced::widget::{button, column, lazy, pick_list, row, scrollable, space, text, text_input}; use iced::{Element, Fill}; use std::collections::HashSet; use std::hash::Hash; pub fn main() -> iced::Result { iced::run(App::update, App::view) } struct App { version: u8, items: HashSet<Item>, input: String, order: Order, } impl Default for App { fn default() -> Self { Self { version: 0, items: ["Foo", "Bar", "Baz", "Qux", "Corge", "Waldo", "Fred"] .into_iter() .map(From::from) .collect(), input: String::default(), order: Order::Ascending, } } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] enum Color { #[default] Black, Red, Orange, Yellow, Green, Blue, Purple, } impl Color { const ALL: &'static [Color] = &[ Color::Black, Color::Red, Color::Orange, Color::Yellow, Color::Green, Color::Blue, Color::Purple, ]; } impl std::fmt::Display for Color { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Black => "Black", Self::Red => "Red", Self::Orange => "Orange", Self::Yellow => "Yellow", Self::Green => "Green", Self::Blue => "Blue", Self::Purple => "Purple", }) } } impl From<Color> for iced::Color { fn from(value: Color) -> Self { match value { Color::Black => iced::Color::from_rgb8(0, 0, 0), Color::Red => iced::Color::from_rgb8(220, 50, 47), Color::Orange => iced::Color::from_rgb8(203, 75, 22), Color::Yellow => iced::Color::from_rgb8(181, 137, 0), Color::Green => iced::Color::from_rgb8(133, 153, 0), Color::Blue => iced::Color::from_rgb8(38, 139, 210), Color::Purple => iced::Color::from_rgb8(108, 113, 196), } } } #[derive(Clone, Debug, Eq)] struct Item { name: String, color: Color, } impl Hash for Item { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.name.hash(state); } } impl PartialEq for Item { fn eq(&self, other: &Self) -> bool { self.name.eq(&other.name) } } impl From<&str> for Item { fn from(s: &str) -> Self { Self { name: s.to_owned(), color: Color::default(), } } } #[derive(Debug, Clone)] enum Message { InputChanged(String), ToggleOrder, DeleteItem(Item), AddItem(String), ItemColorChanged(Item, Color), } impl App { fn update(&mut self, message: Message) { match message { Message::InputChanged(input) => { self.input = input; } Message::ToggleOrder => { self.version = self.version.wrapping_add(1); self.order = match self.order { Order::Ascending => Order::Descending, Order::Descending => Order::Ascending, } } Message::AddItem(name) => { self.version = self.version.wrapping_add(1); self.items.insert(name.as_str().into()); self.input.clear(); } Message::DeleteItem(item) => { self.version = self.version.wrapping_add(1); self.items.remove(&item); } Message::ItemColorChanged(item, color) => { self.version = self.version.wrapping_add(1); if self.items.remove(&item) { self.items.insert(Item { name: item.name, color, }); } } } } fn view(&self) -> Element<'_, Message> { let options = lazy(self.version, |_| { let mut items: Vec<_> = self.items.iter().cloned().collect(); items.sort_by(|a, b| match self.order { Order::Ascending => a.name.to_lowercase().cmp(&b.name.to_lowercase()), Order::Descending => b.name.to_lowercase().cmp(&a.name.to_lowercase()), }); column(items.into_iter().map(|item| { let button = button("Delete") .on_press(Message::DeleteItem(item.clone())) .style(button::danger); row![ text(item.name.clone()).color(item.color), space::horizontal(), pick_list(Color::ALL, Some(item.color), move |color| { Message::ItemColorChanged(item.clone(), color) }), button ] .spacing(20) .into() })) .spacing(10) }); column![ scrollable(options).height(Fill), row![ text_input("Add a new option", &self.input) .on_input(Message::InputChanged) .on_submit(Message::AddItem(self.input.clone())), button(text!("Toggle Order ({})", self.order)).on_press(Message::ToggleOrder) ] .spacing(10) ] .spacing(20) .padding(20) .into() } } #[derive(Debug, Hash)] enum Order { Ascending, Descending, } impl std::fmt::Display for Order { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Self::Ascending => "Ascending", Self::Descending => "Descending", } ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/geometry/src/main.rs
examples/geometry/src/main.rs
//! This example showcases a simple native custom widget that renders using //! arbitrary low-level geometry. mod rainbow { use iced::advanced::graphics::color; use iced::advanced::layout::{self, Layout}; use iced::advanced::renderer; use iced::advanced::widget::{self, Widget}; use iced::advanced::{Clipboard, Shell}; use iced::mouse; use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Transformation, Vector}; #[derive(Debug, Clone, Copy, Default)] pub struct Rainbow; pub fn rainbow() -> Rainbow { Rainbow } impl<Message> Widget<Message, Theme, Renderer> for Rainbow { fn size(&self) -> Size<Length> { Size { width: Length::Fill, height: Length::Shrink, } } fn layout( &mut self, _tree: &mut widget::Tree, _renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let width = limits.max().width; layout::Node::new(Size::new(width, width)) } fn update( &mut self, _state: &mut widget::Tree, _event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, _renderer: &Renderer, _clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, _viewport: &Rectangle, ) { if cursor.is_over(layout.bounds()) { shell.request_redraw(); } } fn draw( &self, _tree: &widget::Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, ) { use iced::advanced::Renderer as _; use iced::advanced::graphics::mesh::{self, Mesh, Renderer as _, SolidVertex2D}; let bounds = layout.bounds(); // R O Y G B I V let color_r = [1.0, 0.0, 0.0, 1.0]; let color_o = [1.0, 0.5, 0.0, 1.0]; let color_y = [1.0, 1.0, 0.0, 1.0]; let color_g = [0.0, 1.0, 0.0, 1.0]; let color_gb = [0.0, 1.0, 0.5, 1.0]; let color_b = [0.0, 0.2, 1.0, 1.0]; let color_i = [0.5, 0.0, 1.0, 1.0]; let color_v = [0.75, 0.0, 0.5, 1.0]; let posn_center = { if let Some(cursor_position) = cursor.position_in(bounds) { [cursor_position.x, cursor_position.y] } else { [bounds.width / 2.0, bounds.height / 2.0] } }; let posn_tl = [0.0, 0.0]; let posn_t = [bounds.width / 2.0, 0.0]; let posn_tr = [bounds.width, 0.0]; let posn_r = [bounds.width, bounds.height / 2.0]; let posn_br = [bounds.width, bounds.height]; let posn_b = [(bounds.width / 2.0), bounds.height]; let posn_bl = [0.0, bounds.height]; let posn_l = [0.0, bounds.height / 2.0]; let mesh = Mesh::Solid { buffers: mesh::Indexed { vertices: vec![ SolidVertex2D { position: posn_center, color: color::pack([1.0, 1.0, 1.0, 1.0]), }, SolidVertex2D { position: posn_tl, color: color::pack(color_r), }, SolidVertex2D { position: posn_t, color: color::pack(color_o), }, SolidVertex2D { position: posn_tr, color: color::pack(color_y), }, SolidVertex2D { position: posn_r, color: color::pack(color_g), }, SolidVertex2D { position: posn_br, color: color::pack(color_gb), }, SolidVertex2D { position: posn_b, color: color::pack(color_b), }, SolidVertex2D { position: posn_bl, color: color::pack(color_i), }, SolidVertex2D { position: posn_l, color: color::pack(color_v), }, ], indices: vec![ 0, 1, 2, // TL 0, 2, 3, // T 0, 3, 4, // TR 0, 4, 5, // R 0, 5, 6, // BR 0, 6, 7, // B 0, 7, 8, // BL 0, 8, 1, // L ], }, transformation: Transformation::IDENTITY, clip_bounds: Rectangle::INFINITE, }; renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { renderer.draw_mesh(mesh); }); } } impl<Message> From<Rainbow> for Element<'_, Message> { fn from(rainbow: Rainbow) -> Self { Self::new(rainbow) } } } use iced::widget::{center_x, center_y, column, scrollable}; use iced::{Element, Never}; use rainbow::rainbow; pub fn main() -> iced::Result { iced::run((), view) } fn view(_state: &()) -> Element<'_, Never> { let content = column![ rainbow(), "In this example we draw a custom widget Rainbow, using \ the Mesh2D primitive. This primitive supplies a list of \ triangles, expressed as vertices and indices.", "Move your cursor over it, and see the center vertex \ follow you!", "Every Vertex2D defines its own color. You could use the \ Mesh2D primitive to render virtually any two-dimensional \ geometry for your widget.", ] .padding(20) .spacing(20) .max_width(500); let scrollable = scrollable(center_x(content)); center_y(scrollable).into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene.rs
examples/custom_shader/src/scene.rs
mod camera; mod pipeline; use camera::Camera; use pipeline::Pipeline; use crate::wgpu; use pipeline::cube::{self, Cube}; use iced::mouse; use iced::time::Duration; use iced::widget::shader::{self, Viewport}; use iced::{Color, Rectangle}; use glam::Vec3; use rand::Rng; use std::cmp::Ordering; use std::iter; pub const MAX: u32 = 500; #[derive(Clone)] pub struct Scene { pub size: f32, pub cubes: Vec<Cube>, pub camera: Camera, pub show_depth_buffer: bool, pub light_color: Color, } impl Scene { pub fn new() -> Self { let mut scene = Self { size: 0.2, cubes: vec![], camera: Camera::default(), show_depth_buffer: false, light_color: Color::WHITE, }; scene.change_amount(MAX); scene } pub fn update(&mut self, time: Duration) { for cube in self.cubes.iter_mut() { cube.update(self.size, time.as_secs_f32()); } } pub fn change_amount(&mut self, amount: u32) { let curr_cubes = self.cubes.len() as u32; match amount.cmp(&curr_cubes) { Ordering::Greater => { // spawn let cubes_2_spawn = (amount - curr_cubes) as usize; let mut cubes = 0; self.cubes.extend(iter::from_fn(|| { if cubes < cubes_2_spawn { cubes += 1; Some(Cube::new(self.size, rnd_origin())) } else { None } })); } Ordering::Less => { // chop let cubes_2_cut = curr_cubes - amount; let new_len = self.cubes.len() - cubes_2_cut as usize; self.cubes.truncate(new_len); } Ordering::Equal => {} } } } impl<Message> shader::Program<Message> for Scene { type State = (); type Primitive = Primitive; fn draw( &self, _state: &Self::State, _cursor: mouse::Cursor, bounds: Rectangle, ) -> Self::Primitive { Primitive::new( &self.cubes, &self.camera, bounds, self.show_depth_buffer, self.light_color, ) } } /// A collection of `Cube`s that can be rendered. #[derive(Debug)] pub struct Primitive { cubes: Vec<cube::Raw>, uniforms: pipeline::Uniforms, show_depth_buffer: bool, } impl Primitive { pub fn new( cubes: &[Cube], camera: &Camera, bounds: Rectangle, show_depth_buffer: bool, light_color: Color, ) -> Self { let uniforms = pipeline::Uniforms::new(camera, bounds, light_color); Self { cubes: cubes .iter() .map(cube::Raw::from_cube) .collect::<Vec<cube::Raw>>(), uniforms, show_depth_buffer, } } } impl shader::Primitive for Primitive { type Pipeline = Pipeline; fn prepare( &self, pipeline: &mut Pipeline, device: &wgpu::Device, queue: &wgpu::Queue, _bounds: &Rectangle, viewport: &Viewport, ) { // Upload data to GPU pipeline.update( device, queue, viewport.physical_size(), &self.uniforms, self.cubes.len(), &self.cubes, ); } fn render( &self, pipeline: &Pipeline, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, clip_bounds: &Rectangle<u32>, ) { // Render primitive pipeline.render( target, encoder, *clip_bounds, self.cubes.len() as u32, self.show_depth_buffer, ); } } fn rnd_origin() -> Vec3 { Vec3::new( rand::thread_rng().gen_range(-4.0..4.0), rand::thread_rng().gen_range(-4.0..4.0), rand::thread_rng().gen_range(-4.0..2.0), ) } impl shader::Pipeline for Pipeline { fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Pipeline { Self::new(device, queue, format) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/main.rs
examples/custom_shader/src/main.rs
mod scene; use scene::Scene; use iced::time::Instant; use iced::wgpu; use iced::widget::{center, checkbox, column, row, shader, slider, text}; use iced::window; use iced::{Center, Color, Element, Fill, Subscription}; fn main() -> iced::Result { iced::application(IcedCubes::default, IcedCubes::update, IcedCubes::view) .subscription(IcedCubes::subscription) .run() } struct IcedCubes { start: Instant, scene: Scene, } #[derive(Debug, Clone)] enum Message { CubeAmountChanged(u32), CubeSizeChanged(f32), Tick(Instant), ShowDepthBuffer(bool), LightColorChanged(Color), } impl IcedCubes { fn new() -> Self { Self { start: Instant::now(), scene: Scene::new(), } } fn update(&mut self, message: Message) { match message { Message::CubeAmountChanged(amount) => { self.scene.change_amount(amount); } Message::CubeSizeChanged(size) => { self.scene.size = size; } Message::Tick(time) => { self.scene.update(time - self.start); } Message::ShowDepthBuffer(show) => { self.scene.show_depth_buffer = show; } Message::LightColorChanged(color) => { self.scene.light_color = color; } } } fn view(&self) -> Element<'_, Message> { let top_controls = row![ control( "Amount", slider( 1..=scene::MAX, self.scene.cubes.len() as u32, Message::CubeAmountChanged ) .width(100) ), control( "Size", slider(0.1..=0.25, self.scene.size, Message::CubeSizeChanged) .step(0.01) .width(100), ), checkbox(self.scene.show_depth_buffer) .label("Show Depth Buffer") .on_toggle(Message::ShowDepthBuffer), ] .spacing(40); let bottom_controls = row![ control( "R", slider(0.0..=1.0, self.scene.light_color.r, move |r| { Message::LightColorChanged(Color { r, ..self.scene.light_color }) }) .step(0.01) .width(100) ), control( "G", slider(0.0..=1.0, self.scene.light_color.g, move |g| { Message::LightColorChanged(Color { g, ..self.scene.light_color }) }) .step(0.01) .width(100) ), control( "B", slider(0.0..=1.0, self.scene.light_color.b, move |b| { Message::LightColorChanged(Color { b, ..self.scene.light_color }) }) .step(0.01) .width(100) ) ] .spacing(40); let controls = column![top_controls, bottom_controls,] .spacing(10) .padding(20) .align_x(Center); let shader = shader(&self.scene).width(Fill).height(Fill); center(column![shader, controls].align_x(Center)).into() } fn subscription(&self) -> Subscription<Message> { window::frames().map(Message::Tick) } } impl Default for IcedCubes { fn default() -> Self { Self::new() } } fn control<'a>( label: &'static str, control: impl Into<Element<'a, Message>>, ) -> Element<'a, Message> { row![text(label), control.into()].spacing(10).into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/pipeline.rs
examples/custom_shader/src/scene/pipeline.rs
pub mod cube; mod buffer; mod uniforms; mod vertex; pub use uniforms::Uniforms; use buffer::Buffer; use vertex::Vertex; use crate::wgpu; use crate::wgpu::util::DeviceExt; use iced::{Rectangle, Size}; const SKY_TEXTURE_SIZE: u32 = 128; pub struct Pipeline { pipeline: wgpu::RenderPipeline, vertices: wgpu::Buffer, cubes: Buffer, uniforms: wgpu::Buffer, uniform_bind_group: wgpu::BindGroup, depth_texture_size: Size<u32>, depth_view: wgpu::TextureView, depth_pipeline: DepthPipeline, } impl Pipeline { pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { //vertices of one cube let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("cubes vertex buffer"), contents: bytemuck::cast_slice(&cube::Raw::vertices()), usage: wgpu::BufferUsages::VERTEX, }); //cube instance data let cubes_buffer = Buffer::new( device, "cubes instance buffer", std::mem::size_of::<cube::Raw>() as u64, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); //uniforms for all cubes let uniforms = device.create_buffer(&wgpu::BufferDescriptor { label: Some("cubes uniform buffer"), size: std::mem::size_of::<Uniforms>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); //depth buffer let depth_texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("cubes depth texture"), size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Depth32Float, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); let normal_map_data = load_normal_map_data(); //normal map let normal_texture = device.create_texture_with_data( queue, &wgpu::TextureDescriptor { label: Some("cubes normal map texture"), size: wgpu::Extent3d { width: 1024, height: 1024, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, usage: wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }, wgpu::util::TextureDataOrder::LayerMajor, &normal_map_data, ); let normal_view = normal_texture.create_view(&wgpu::TextureViewDescriptor::default()); //skybox texture for reflection/refraction let skybox_data = load_skybox_data(); let skybox_texture = device.create_texture_with_data( queue, &wgpu::TextureDescriptor { label: Some("cubes skybox texture"), size: wgpu::Extent3d { width: SKY_TEXTURE_SIZE, height: SKY_TEXTURE_SIZE, depth_or_array_layers: 6, //one for each face of the cube }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, usage: wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }, wgpu::util::TextureDataOrder::LayerMajor, &skybox_data, ); let sky_view = skybox_texture.create_view(&wgpu::TextureViewDescriptor { label: Some("cubes skybox texture view"), dimension: Some(wgpu::TextureViewDimension::Cube), ..Default::default() }); let sky_sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("cubes skybox sampler"), address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear, ..Default::default() }); let uniform_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("cubes uniform bind group layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::Cube, multisampled: false, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, count: None, }, ], }); let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("cubes uniform bind group"), layout: &uniform_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: uniforms.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&sky_view), }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&sky_sampler), }, wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&normal_view), }, ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("cubes pipeline layout"), bind_group_layouts: &[&uniform_bind_group_layout], push_constant_ranges: &[], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("cubes shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( "../shaders/cubes.wgsl" ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("cubes pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[Vertex::desc(), cube::Raw::desc()], compilation_options: wgpu::PipelineCompilationOptions::default(), }, primitive: wgpu::PrimitiveState::default(), depth_stencil: Some(wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth32Float, depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::SrcAlpha, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Max, }, }), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), multiview: None, cache: None, }); let depth_pipeline = DepthPipeline::new( device, format, depth_texture.create_view(&wgpu::TextureViewDescriptor::default()), ); Self { pipeline, cubes: cubes_buffer, uniforms, uniform_bind_group, vertices, depth_texture_size: Size::new(1, 1), depth_view, depth_pipeline, } } fn update_depth_texture(&mut self, device: &wgpu::Device, size: Size<u32>) { if self.depth_texture_size.height != size.height || self.depth_texture_size.width != size.width { let text = device.create_texture(&wgpu::TextureDescriptor { label: Some("cubes depth texture"), size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Depth32Float, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); self.depth_view = text.create_view(&wgpu::TextureViewDescriptor::default()); self.depth_texture_size = size; self.depth_pipeline.update(device, &text); } } pub fn update( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, target_size: Size<u32>, uniforms: &Uniforms, num_cubes: usize, cubes: &[cube::Raw], ) { //recreate depth texture if surface texture size has changed self.update_depth_texture(device, target_size); // update uniforms queue.write_buffer(&self.uniforms, 0, bytemuck::bytes_of(uniforms)); //resize cubes vertex buffer if cubes amount changed let new_size = num_cubes * std::mem::size_of::<cube::Raw>(); self.cubes.resize(device, new_size as u64); //always write new cube data since they are constantly rotating queue.write_buffer(&self.cubes.raw, 0, bytemuck::cast_slice(cubes)); } pub fn render( &self, target: &wgpu::TextureView, encoder: &mut wgpu::CommandEncoder, clip_bounds: Rectangle<u32>, num_cubes: u32, show_depth: bool, ) { { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("cubes.pipeline.pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: target, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Store, }), stencil_ops: None, }), timestamp_writes: None, occlusion_query_set: None, }); pass.set_viewport( clip_bounds.x as f32, clip_bounds.y as f32, clip_bounds.width as f32, clip_bounds.height as f32, 0.0, 1.0, ); pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &self.uniform_bind_group, &[]); pass.set_vertex_buffer(0, self.vertices.slice(..)); pass.set_vertex_buffer(1, self.cubes.raw.slice(..)); pass.draw(0..36, 0..num_cubes); } if show_depth { self.depth_pipeline.render(encoder, target, clip_bounds); } } } struct DepthPipeline { pipeline: wgpu::RenderPipeline, bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, sampler: wgpu::Sampler, depth_view: wgpu::TextureView, } impl DepthPipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, depth_texture: wgpu::TextureView, ) -> Self { let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("cubes.depth_pipeline.sampler"), ..Default::default() }); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("cubes.depth_pipeline.bind_group_layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering), count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, count: None, }, ], }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("cubes.depth_pipeline.bind_group"), layout: &bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Sampler(&sampler), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&depth_texture), }, ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("cubes.depth_pipeline.layout"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("cubes.depth_pipeline.shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( "../shaders/depth.wgsl" ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("cubes.depth_pipeline.pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, primitive: wgpu::PrimitiveState::default(), depth_stencil: Some(wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth32Float, depth_write_enabled: false, depth_compare: wgpu::CompareFunction::Less, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState::default(), fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), multiview: None, cache: None, }); Self { pipeline, bind_group_layout, bind_group, sampler, depth_view: depth_texture, } } pub fn update(&mut self, device: &wgpu::Device, depth_texture: &wgpu::Texture) { self.depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("cubes.depth_pipeline.bind_group"), layout: &self.bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Sampler(&self.sampler), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&self.depth_view), }, ], }); } pub fn render( &self, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, clip_bounds: Rectangle<u32>, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("cubes.pipeline.depth_pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: target, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth_view, depth_ops: None, stencil_ops: None, }), timestamp_writes: None, occlusion_query_set: None, }); pass.set_viewport( clip_bounds.x as f32, clip_bounds.y as f32, clip_bounds.width as f32, clip_bounds.height as f32, 0.0, 1.0, ); pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &self.bind_group, &[]); pass.draw(0..6, 0..1); } } fn load_skybox_data() -> Vec<u8> { let pos_x: &[u8] = include_bytes!("../../textures/skybox/pos_x.jpg"); let neg_x: &[u8] = include_bytes!("../../textures/skybox/neg_x.jpg"); let pos_y: &[u8] = include_bytes!("../../textures/skybox/pos_y.jpg"); let neg_y: &[u8] = include_bytes!("../../textures/skybox/neg_y.jpg"); let pos_z: &[u8] = include_bytes!("../../textures/skybox/pos_z.jpg"); let neg_z: &[u8] = include_bytes!("../../textures/skybox/neg_z.jpg"); let data: [&[u8]; 6] = [pos_x, neg_x, pos_y, neg_y, pos_z, neg_z]; data.iter().fold(vec![], |mut acc, bytes| { let i = image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg) .unwrap() .to_rgba8() .into_raw(); acc.extend(i); acc }) } fn load_normal_map_data() -> Vec<u8> { let bytes: &[u8] = include_bytes!("../../textures/ice_cube_normal_map.png"); image::load_from_memory_with_format(bytes, image::ImageFormat::Png) .unwrap() .to_rgba8() .into_raw() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/camera.rs
examples/custom_shader/src/scene/camera.rs
use glam::{mat4, vec3, vec4}; use iced::Rectangle; #[derive(Copy, Clone)] pub struct Camera { eye: glam::Vec3, target: glam::Vec3, up: glam::Vec3, fov_y: f32, near: f32, far: f32, } impl Default for Camera { fn default() -> Self { Self { eye: vec3(0.0, 2.0, 3.0), target: glam::Vec3::ZERO, up: glam::Vec3::Y, fov_y: 45.0, near: 0.1, far: 100.0, } } } pub const OPENGL_TO_WGPU_MATRIX: glam::Mat4 = mat4( vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 0.5, 0.0), vec4(0.0, 0.0, 0.5, 1.0), ); impl Camera { pub fn build_view_proj_matrix(&self, bounds: Rectangle) -> glam::Mat4 { let aspect_ratio = bounds.width / bounds.height; let view = glam::Mat4::look_at_rh(self.eye, self.target, self.up); let proj = glam::Mat4::perspective_rh(self.fov_y, aspect_ratio, self.near, self.far); OPENGL_TO_WGPU_MATRIX * proj * view } pub fn position(&self) -> glam::Vec4 { glam::Vec4::from((self.eye, 0.0)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/pipeline/uniforms.rs
examples/custom_shader/src/scene/pipeline/uniforms.rs
use crate::scene::Camera; use iced::{Color, Rectangle}; #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct Uniforms { camera_proj: glam::Mat4, camera_pos: glam::Vec4, light_color: glam::Vec4, } impl Uniforms { pub fn new(camera: &Camera, bounds: Rectangle, light_color: Color) -> Self { let camera_proj = camera.build_view_proj_matrix(bounds); Self { camera_proj, camera_pos: camera.position(), light_color: glam::Vec4::from(light_color.into_linear()), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/pipeline/cube.rs
examples/custom_shader/src/scene/pipeline/cube.rs
use crate::scene::pipeline::Vertex; use crate::wgpu; use glam::{Vec3, vec2, vec3}; use rand::{Rng, thread_rng}; /// A single instance of a cube. #[derive(Debug, Clone)] pub struct Cube { pub rotation: glam::Quat, pub position: Vec3, pub size: f32, rotation_dir: f32, rotation_axis: glam::Vec3, } impl Default for Cube { fn default() -> Self { Self { rotation: glam::Quat::IDENTITY, position: glam::Vec3::ZERO, size: 0.1, rotation_dir: 1.0, rotation_axis: glam::Vec3::Y, } } } impl Cube { pub fn new(size: f32, origin: Vec3) -> Self { let rnd = thread_rng().gen_range(0.0..=1.0f32); Self { rotation: glam::Quat::IDENTITY, position: origin + Vec3::new(0.1, 0.1, 0.1), size, rotation_dir: if rnd <= 0.5 { -1.0 } else { 1.0 }, rotation_axis: if rnd <= 0.33 { glam::Vec3::Y } else if rnd <= 0.66 { glam::Vec3::X } else { glam::Vec3::Z }, } } pub fn update(&mut self, size: f32, time: f32) { self.rotation = glam::Quat::from_axis_angle(self.rotation_axis, time / 2.0 * self.rotation_dir); self.size = size; } } #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Debug)] #[repr(C)] pub struct Raw { transformation: glam::Mat4, normal: glam::Mat3, _padding: [f32; 3], } impl Raw { const ATTRIBS: [wgpu::VertexAttribute; 7] = wgpu::vertex_attr_array![ //cube transformation matrix 4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Float32x4, //normal rotation matrix 8 => Float32x3, 9 => Float32x3, 10 => Float32x3, ]; pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &Self::ATTRIBS, } } } impl Raw { pub fn from_cube(cube: &Cube) -> Raw { Raw { transformation: glam::Mat4::from_scale_rotation_translation( glam::vec3(cube.size, cube.size, cube.size), cube.rotation, cube.position, ), normal: glam::Mat3::from_quat(cube.rotation), _padding: [0.0; 3], } } pub fn vertices() -> [Vertex; 36] { [ //face 1 Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(0.5, -0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(0.5, 0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, 0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, 0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(0.0, 0.0, -1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, //face 2 Vertex { pos: vec3(-0.5, -0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(0.5, -0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, 0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, 0.5), normal: vec3(0.0, 0.0, 1.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, //face 3 Vertex { pos: vec3(-0.5, 0.5, 0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(-0.5, 0.5, -0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, 0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(-0.5, 0.5, 0.5), normal: vec3(-1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 1.0), }, //face 4 Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(0.5, 0.5, -0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(0.5, -0.5, -0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, -0.5, -0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, -0.5, 0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(1.0, 0.0, 0.0), tangent: vec3(0.0, 0.0, -1.0), uv: vec2(0.0, 1.0), }, //face 5 Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(0.5, -0.5, -0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(0.5, -0.5, 0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, -0.5, 0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, 0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(-0.5, -0.5, -0.5), normal: vec3(0.0, -1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, //face 6 Vertex { pos: vec3(-0.5, 0.5, -0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, Vertex { pos: vec3(0.5, 0.5, -0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 1.0), }, Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(0.5, 0.5, 0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(1.0, 0.0), }, Vertex { pos: vec3(-0.5, 0.5, 0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 0.0), }, Vertex { pos: vec3(-0.5, 0.5, -0.5), normal: vec3(0.0, 1.0, 0.0), tangent: vec3(1.0, 0.0, 0.0), uv: vec2(0.0, 1.0), }, ] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/pipeline/buffer.rs
examples/custom_shader/src/scene/pipeline/buffer.rs
use crate::wgpu; // A custom buffer container for dynamic resizing. pub struct Buffer { pub raw: wgpu::Buffer, label: &'static str, size: u64, usage: wgpu::BufferUsages, } impl Buffer { pub fn new( device: &wgpu::Device, label: &'static str, size: u64, usage: wgpu::BufferUsages, ) -> Self { Self { raw: device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false, }), label, size, usage, } } pub fn resize(&mut self, device: &wgpu::Device, new_size: u64) { if new_size > self.size { self.raw = device.create_buffer(&wgpu::BufferDescriptor { label: Some(self.label), size: new_size, usage: self.usage, mapped_at_creation: false, }); } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_shader/src/scene/pipeline/vertex.rs
examples/custom_shader/src/scene/pipeline/vertex.rs
use crate::wgpu; #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct Vertex { pub pos: glam::Vec3, pub normal: glam::Vec3, pub tangent: glam::Vec3, pub uv: glam::Vec2, } impl Vertex { const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![ //position 0 => Float32x3, //normal 1 => Float32x3, //tangent 2 => Float32x3, //uv 3 => Float32x2, ]; pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &Self::ATTRIBS, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/editor/src/main.rs
examples/editor/src/main.rs
use iced::highlighter; use iced::keyboard; use iced::widget::{ button, center_x, column, container, operation, pick_list, row, space, text, text_editor, toggler, tooltip, }; use iced::window; use iced::{Center, Element, Fill, Font, Task, Theme, Window}; use std::ffi; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; pub fn main() -> iced::Result { iced::application(Editor::new, Editor::update, Editor::view) .theme(Editor::theme) .font(include_bytes!("../fonts/icons.ttf").as_slice()) .default_font(Font::MONOSPACE) .run() } struct Editor { file: Option<PathBuf>, content: text_editor::Content, theme: highlighter::Theme, word_wrap: bool, is_loading: bool, is_dirty: bool, } #[derive(Debug, Clone)] enum Message { ActionPerformed(text_editor::Action), ThemeSelected(highlighter::Theme), WordWrapToggled(bool), NewFile, OpenFile, FileOpened(Result<(PathBuf, Arc<String>), Error>), SaveFile, FileSaved(Result<PathBuf, Error>), } impl Editor { fn new() -> (Self, Task<Message>) { ( Self { file: None, content: text_editor::Content::new(), theme: highlighter::Theme::SolarizedDark, word_wrap: true, is_loading: true, is_dirty: false, }, Task::batch([ Task::perform( load_file(concat!(env!("CARGO_MANIFEST_DIR"), "/src/main.rs",)), Message::FileOpened, ), operation::focus(EDITOR), ]), ) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::ActionPerformed(action) => { self.is_dirty = self.is_dirty || action.is_edit(); self.content.perform(action); Task::none() } Message::ThemeSelected(theme) => { self.theme = theme; Task::none() } Message::WordWrapToggled(word_wrap) => { self.word_wrap = word_wrap; Task::none() } Message::NewFile => { if !self.is_loading { self.file = None; self.content = text_editor::Content::new(); } Task::none() } Message::OpenFile => { if self.is_loading { Task::none() } else { self.is_loading = true; window::oldest() .and_then(|id| window::run(id, open_file)) .then(Task::future) .map(Message::FileOpened) } } Message::FileOpened(result) => { self.is_loading = false; self.is_dirty = false; if let Ok((path, contents)) = result { self.file = Some(path); self.content = text_editor::Content::with_text(&contents); } Task::none() } Message::SaveFile => { if self.is_loading { Task::none() } else { self.is_loading = true; let mut text = self.content.text(); if let Some(ending) = self.content.line_ending() && !text.ends_with(ending.as_str()) { text.push_str(ending.as_str()); } Task::perform(save_file(self.file.clone(), text), Message::FileSaved) } } Message::FileSaved(result) => { self.is_loading = false; if let Ok(path) = result { self.file = Some(path); self.is_dirty = false; } Task::none() } } } fn view(&self) -> Element<'_, Message> { let controls = row![ action(new_icon(), "New file", Some(Message::NewFile)), action( open_icon(), "Open file", (!self.is_loading).then_some(Message::OpenFile) ), action( save_icon(), "Save file", self.is_dirty.then_some(Message::SaveFile) ), space::horizontal(), toggler(self.word_wrap) .label("Word Wrap") .on_toggle(Message::WordWrapToggled), pick_list( highlighter::Theme::ALL, Some(self.theme), Message::ThemeSelected ) .text_size(14) .padding([5, 10]) ] .spacing(10) .align_y(Center); let status = row![ text(if let Some(path) = &self.file { let path = path.display().to_string(); if path.len() > 60 { format!("...{}", &path[path.len() - 40..]) } else { path } } else { String::from("New file") }), space::horizontal(), text({ let cursor = self.content.cursor(); format!( "{}:{}", cursor.position.line + 1, cursor.position.column + 1 ) }) ] .spacing(10); column![ controls, text_editor(&self.content) .id(EDITOR) .height(Fill) .on_action(Message::ActionPerformed) .wrapping(if self.word_wrap { text::Wrapping::Word } else { text::Wrapping::None }) .highlight( self.file .as_deref() .and_then(Path::extension) .and_then(ffi::OsStr::to_str) .unwrap_or("rs"), self.theme, ) .key_binding(|key_press| { match key_press.key.as_ref() { keyboard::Key::Character("s") if key_press.modifiers.command() => { Some(text_editor::Binding::Custom(Message::SaveFile)) } _ => text_editor::Binding::from_key_press(key_press), } }), status, ] .spacing(10) .padding(10) .into() } fn theme(&self) -> Theme { if self.theme.is_dark() { Theme::Dark } else { Theme::Light } } } #[derive(Debug, Clone)] pub enum Error { DialogClosed, IoError(io::ErrorKind), } fn open_file( window: &dyn Window, ) -> impl Future<Output = Result<(PathBuf, Arc<String>), Error>> + use<> { let dialog = rfd::AsyncFileDialog::new() .set_title("Open a text file...") .set_parent(&window); async move { let picked_file = dialog.pick_file().await.ok_or(Error::DialogClosed)?; load_file(picked_file).await } } async fn load_file(path: impl Into<PathBuf>) -> Result<(PathBuf, Arc<String>), Error> { let path = path.into(); let contents = tokio::fs::read_to_string(&path) .await .map(Arc::new) .map_err(|error| Error::IoError(error.kind()))?; Ok((path, contents)) } async fn save_file(path: Option<PathBuf>, contents: String) -> Result<PathBuf, Error> { let path = if let Some(path) = path { path } else { rfd::AsyncFileDialog::new() .save_file() .await .as_ref() .map(rfd::FileHandle::path) .map(Path::to_owned) .ok_or(Error::DialogClosed)? }; tokio::fs::write(&path, contents) .await .map_err(|error| Error::IoError(error.kind()))?; Ok(path) } fn action<'a, Message: Clone + 'a>( content: impl Into<Element<'a, Message>>, label: &'a str, on_press: Option<Message>, ) -> Element<'a, Message> { let action = button(center_x(content).width(30)); if let Some(on_press) = on_press { tooltip( action.on_press(on_press), label, tooltip::Position::FollowCursor, ) .style(container::rounded_box) .into() } else { action.style(button::secondary).into() } } fn new_icon<'a, Message>() -> Element<'a, Message> { icon('\u{0e800}') } fn save_icon<'a, Message>() -> Element<'a, Message> { icon('\u{0e801}') } fn open_icon<'a, Message>() -> Element<'a, Message> { icon('\u{0f115}') } fn icon<'a, Message>(codepoint: char) -> Element<'a, Message> { const ICON_FONT: Font = Font::with_name("editor-icons"); text(codepoint) .font(ICON_FONT) .shaping(text::Shaping::Basic) .into() } const EDITOR: &str = "editor";
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/scrollable/src/main.rs
examples/scrollable/src/main.rs
use iced::widget::{ button, column, container, operation, progress_bar, radio, row, scrollable, slider, space, text, }; use iced::{Border, Center, Color, Element, Fill, Task, Theme}; pub fn main() -> iced::Result { iced::application( ScrollableDemo::default, ScrollableDemo::update, ScrollableDemo::view, ) .theme(ScrollableDemo::theme) .run() } struct ScrollableDemo { scrollable_direction: Direction, scrollbar_width: u32, scrollbar_margin: u32, scroller_width: u32, current_scroll_offset: scrollable::RelativeOffset, anchor: scrollable::Anchor, } #[derive(Debug, Clone, Eq, PartialEq, Copy)] enum Direction { Vertical, Horizontal, Multi, } #[derive(Debug, Clone)] enum Message { SwitchDirection(Direction), AlignmentChanged(scrollable::Anchor), ScrollbarWidthChanged(u32), ScrollbarMarginChanged(u32), ScrollerWidthChanged(u32), ScrollToBeginning, ScrollToEnd, Scrolled(scrollable::Viewport), } impl ScrollableDemo { fn new() -> Self { ScrollableDemo { scrollable_direction: Direction::Vertical, scrollbar_width: 10, scrollbar_margin: 0, scroller_width: 10, current_scroll_offset: scrollable::RelativeOffset::START, anchor: scrollable::Anchor::Start, } } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::SwitchDirection(direction) => { self.current_scroll_offset = scrollable::RelativeOffset::START; self.scrollable_direction = direction; operation::snap_to(SCROLLABLE, self.current_scroll_offset) } Message::AlignmentChanged(alignment) => { self.current_scroll_offset = scrollable::RelativeOffset::START; self.anchor = alignment; operation::snap_to(SCROLLABLE, self.current_scroll_offset) } Message::ScrollbarWidthChanged(width) => { self.scrollbar_width = width; Task::none() } Message::ScrollbarMarginChanged(margin) => { self.scrollbar_margin = margin; Task::none() } Message::ScrollerWidthChanged(width) => { self.scroller_width = width; Task::none() } Message::ScrollToBeginning => { self.current_scroll_offset = scrollable::RelativeOffset::START; operation::snap_to(SCROLLABLE, self.current_scroll_offset) } Message::ScrollToEnd => { self.current_scroll_offset = scrollable::RelativeOffset::END; operation::snap_to(SCROLLABLE, self.current_scroll_offset) } Message::Scrolled(viewport) => { self.current_scroll_offset = viewport.relative_offset(); Task::none() } } } fn view(&self) -> Element<'_, Message> { let scrollbar_width_slider = slider(0..=15, self.scrollbar_width, Message::ScrollbarWidthChanged); let scrollbar_margin_slider = slider( 0..=15, self.scrollbar_margin, Message::ScrollbarMarginChanged, ); let scroller_width_slider = slider(0..=15, self.scroller_width, Message::ScrollerWidthChanged); let scroll_slider_controls = column![ text("Scrollbar width:"), scrollbar_width_slider, text("Scrollbar margin:"), scrollbar_margin_slider, text("Scroller width:"), scroller_width_slider, ] .spacing(10); let scroll_orientation_controls = column![ text("Scrollbar direction:"), radio( "Vertical", Direction::Vertical, Some(self.scrollable_direction), Message::SwitchDirection, ), radio( "Horizontal", Direction::Horizontal, Some(self.scrollable_direction), Message::SwitchDirection, ), radio( "Both!", Direction::Multi, Some(self.scrollable_direction), Message::SwitchDirection, ), ] .spacing(10); let scroll_alignment_controls = column![ text("Scrollable alignment:"), radio( "Start", scrollable::Anchor::Start, Some(self.anchor), Message::AlignmentChanged, ), radio( "End", scrollable::Anchor::End, Some(self.anchor), Message::AlignmentChanged, ) ] .spacing(10); let scroll_controls = row![ scroll_slider_controls, scroll_orientation_controls, scroll_alignment_controls ] .spacing(20); let scroll_to_end_button = || { button("Scroll to end") .padding(10) .on_press(Message::ScrollToEnd) }; let scroll_to_beginning_button = || { button("Scroll to beginning") .padding(10) .on_press(Message::ScrollToBeginning) }; let scrollable_content: Element<Message> = Element::from(match self.scrollable_direction { Direction::Vertical => scrollable( column![ scroll_to_end_button(), text("Beginning!"), space().height(1200), text("Middle!"), space().height(1200), text("End!"), scroll_to_beginning_button(), ] .align_x(Center) .padding([40, 0]) .spacing(40), ) .direction(scrollable::Direction::Vertical( scrollable::Scrollbar::new() .width(self.scrollbar_width) .margin(self.scrollbar_margin) .scroller_width(self.scroller_width) .anchor(self.anchor), )) .width(Fill) .height(Fill) .id(SCROLLABLE) .on_scroll(Message::Scrolled) .auto_scroll(true), Direction::Horizontal => scrollable( row![ scroll_to_end_button(), text("Beginning!"), space().width(1200), text("Middle!"), space().width(1200), text("End!"), scroll_to_beginning_button(), ] .height(450) .align_y(Center) .padding([0, 40]) .spacing(40), ) .direction(scrollable::Direction::Horizontal( scrollable::Scrollbar::new() .width(self.scrollbar_width) .margin(self.scrollbar_margin) .scroller_width(self.scroller_width) .anchor(self.anchor), )) .width(Fill) .height(Fill) .id(SCROLLABLE) .on_scroll(Message::Scrolled) .auto_scroll(true), Direction::Multi => scrollable( //horizontal content row![ column![text("Let's do some scrolling!"), space().height(2400)], scroll_to_end_button(), text("Horizontal - Beginning!"), space().width(1200), //vertical content column![ text("Horizontal - Middle!"), scroll_to_end_button(), text("Vertical - Beginning!"), space().height(1200), text("Vertical - Middle!"), space().height(1200), text("Vertical - End!"), scroll_to_beginning_button(), space().height(40), ] .spacing(40), space().width(1200), text("Horizontal - End!"), scroll_to_beginning_button(), ] .align_y(Center) .padding([0, 40]) .spacing(40), ) .direction({ let scrollbar = scrollable::Scrollbar::new() .width(self.scrollbar_width) .margin(self.scrollbar_margin) .scroller_width(self.scroller_width) .anchor(self.anchor); scrollable::Direction::Both { horizontal: scrollbar, vertical: scrollbar, } }) .width(Fill) .height(Fill) .id(SCROLLABLE) .on_scroll(Message::Scrolled) .auto_scroll(true), }); let progress_bars: Element<Message> = match self.scrollable_direction { Direction::Vertical => progress_bar(0.0..=1.0, self.current_scroll_offset.y).into(), Direction::Horizontal => progress_bar(0.0..=1.0, self.current_scroll_offset.x) .style(progress_bar_custom_style) .into(), Direction::Multi => column![ progress_bar(0.0..=1.0, self.current_scroll_offset.y), progress_bar(0.0..=1.0, self.current_scroll_offset.x) .style(progress_bar_custom_style) ] .spacing(10) .into(), }; let content: Element<Message> = column![scroll_controls, scrollable_content, progress_bars] .align_x(Center) .spacing(10) .into(); container(content).padding(20).into() } fn theme(&self) -> Theme { Theme::Dark } } impl Default for ScrollableDemo { fn default() -> Self { Self::new() } } fn progress_bar_custom_style(theme: &Theme) -> progress_bar::Style { progress_bar::Style { background: theme.extended_palette().background.strong.color.into(), bar: Color::from_rgb8(250, 85, 134).into(), border: Border::default(), } } const SCROLLABLE: &str = "scrollable";
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/solar_system/src/main.rs
examples/solar_system/src/main.rs
//! An animated solar system. //! //! This example showcases how to use a `Canvas` widget with transforms to draw //! using different coordinate systems. //! //! Inspired by the example found in the MDN docs[1]. //! //! [1]: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations#An_animated_solar_system use iced::mouse; use iced::widget::canvas::stroke::{self, Stroke}; use iced::widget::canvas::{Geometry, Path}; use iced::widget::{canvas, image}; use iced::window; use iced::{Color, Element, Fill, Point, Rectangle, Renderer, Size, Subscription, Theme, Vector}; use std::time::Instant; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application::timed( SolarSystem::new, SolarSystem::update, SolarSystem::subscription, SolarSystem::view, ) .theme(SolarSystem::theme) .run() } struct SolarSystem { state: State, } #[derive(Debug, Clone, Copy)] enum Message { Tick, } impl SolarSystem { fn new() -> Self { Self { state: State::new(), } } fn update(&mut self, message: Message, now: Instant) { match message { Message::Tick => { self.state.update(now); } } } fn view(&self) -> Element<'_, Message> { canvas(&self.state).width(Fill).height(Fill).into() } fn theme(&self) -> Theme { Theme::Moonfly } fn subscription(&self) -> Subscription<Message> { window::frames().map(|_| Message::Tick) } } #[derive(Debug)] struct State { sun: image::Handle, earth: image::Handle, moon: image::Handle, space_cache: canvas::Cache, system_cache: canvas::Cache, start: Instant, now: Instant, stars: Vec<(Point, f32)>, } impl State { const SUN_RADIUS: f32 = 70.0; const ORBIT_RADIUS: f32 = 150.0; const EARTH_RADIUS: f32 = 12.0; const MOON_RADIUS: f32 = 4.0; const MOON_DISTANCE: f32 = 28.0; pub fn new() -> State { let now = Instant::now(); let size = window::Settings::default().size; State { sun: image::Handle::from_bytes(include_bytes!("../assets/sun.png").as_slice()), earth: image::Handle::from_bytes(include_bytes!("../assets/earth.png").as_slice()), moon: image::Handle::from_bytes(include_bytes!("../assets/moon.png").as_slice()), space_cache: canvas::Cache::default(), system_cache: canvas::Cache::default(), start: now, now, stars: Self::generate_stars(size.width, size.height), } } pub fn update(&mut self, now: Instant) { self.start = self.start.min(now); self.now = now; self.system_cache.clear(); } fn generate_stars(width: f32, height: f32) -> Vec<(Point, f32)> { use rand::Rng; let mut rng = rand::thread_rng(); (0..100) .map(|_| { ( Point::new( rng.gen_range((-width / 2.0)..(width / 2.0)), rng.gen_range((-height / 2.0)..(height / 2.0)), ), rng.gen_range(0.5..1.0), ) }) .collect() } } impl<Message> canvas::Program<Message> for State { type State = (); fn draw( &self, _state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { use std::f32::consts::PI; let background = self.space_cache.draw(renderer, bounds.size(), |frame| { frame.fill_rectangle(Point::ORIGIN, frame.size(), Color::BLACK); let stars = Path::new(|path| { for (p, size) in &self.stars { path.rectangle(*p, Size::new(*size, *size)); } }); frame.translate(frame.center() - Point::ORIGIN); frame.fill(&stars, Color::WHITE); }); let system = self.system_cache.draw(renderer, bounds.size(), |frame| { let center = frame.center(); frame.translate(Vector::new(center.x, center.y)); frame.draw_image(Rectangle::with_radius(Self::SUN_RADIUS), &self.sun); let orbit = Path::circle(Point::ORIGIN, Self::ORBIT_RADIUS); frame.stroke( &orbit, Stroke { style: stroke::Style::Solid(Color::WHITE.scale_alpha(0.1)), width: 1.0, line_dash: canvas::LineDash { offset: 0, segments: &[3.0, 6.0], }, ..Stroke::default() }, ); let elapsed = self.now - self.start; let rotation = (2.0 * PI / 60.0) * elapsed.as_secs() as f32 + (2.0 * PI / 60_000.0) * elapsed.subsec_millis() as f32; frame.rotate(rotation); frame.translate(Vector::new(Self::ORBIT_RADIUS, 0.0)); frame.draw_image( Rectangle::with_radius(Self::EARTH_RADIUS), canvas::Image::new(&self.earth).rotation(-rotation * 20.0), ); frame.rotate(rotation * 10.0); frame.translate(Vector::new(0.0, Self::MOON_DISTANCE)); frame.draw_image(Rectangle::with_radius(Self::MOON_RADIUS), &self.moon); }); vec![background, system] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/sandpiles/src/main.rs
examples/sandpiles/src/main.rs
use iced::mouse; use iced::widget::{canvas, column, container, row, slider, text}; use iced::window; use iced::{ Center, Element, Event, Fill, Font, Point, Rectangle, Renderer, Size, Subscription, Theme, Vector, }; use std::collections::{HashMap, HashSet}; pub fn main() -> iced::Result { iced::application(Sandpiles::new, Sandpiles::update, Sandpiles::view) .subscription(Sandpiles::subscription) .run() } struct Sandpiles { grid: Grid, sandfalls: HashSet<Cell>, cache: canvas::Cache, speed: u32, } #[derive(Debug, Clone, Copy)] enum Message { Tick, Add(Cell), SpeedChanged(u32), } impl Sandpiles { fn new() -> Self { Self { grid: Grid::new(), sandfalls: HashSet::from_iter( std::iter::once(Cell::ORIGIN).chain( [(-1, -1), (-1, 1), (1, -1), (1, 1)] .iter() .map(|(i, j)| Cell { row: 3 * i, column: 3 * j, }), ), ), cache: canvas::Cache::new(), speed: 1, } } fn update(&mut self, message: Message) { match message { Message::Tick => { let topples = (0..self.speed).find(|_| !self.grid.topple()); if topples == Some(0) { for sandfall in &self.sandfalls { self.grid.add(*sandfall, 1); } } self.cache.clear(); } Message::Add(sandfall) => { self.sandfalls.insert(sandfall); self.grid.add(sandfall, 1); } Message::SpeedChanged(speed) => { self.speed = speed; } } } fn view(&self) -> Element<'_, Message> { let viewer = canvas(Viewer { grid: &self.grid, cache: &self.cache, }) .width(Fill) .height(Fill); let speed = container( row![ text("Speed").font(Font::MONOSPACE), slider(1..=1000, self.speed, Message::SpeedChanged), text!("x{:>04}", self.speed) .font(Font::MONOSPACE) .align_x(Center) ] .spacing(10) .padding(10) .align_y(Center) .width(500), ) .width(Fill) .align_x(Center) .style(container::dark); column![viewer, speed].into() } fn subscription(&self) -> Subscription<Message> { if self.sandfalls.is_empty() { return Subscription::none(); } window::frames().map(|_| Message::Tick) } } #[derive(Debug)] struct Grid { sand: HashMap<Cell, u32>, saturated: HashSet<Cell>, } impl Grid { pub fn new() -> Self { Self { sand: HashMap::new(), saturated: HashSet::new(), } } pub fn add(&mut self, cell: Cell, amount: u32) { let grains = self.sand.entry(cell).or_default(); *grains += amount; if *grains >= 4 { self.saturated.insert(cell); } } pub fn topple(&mut self) -> bool { let Some(cell) = self.saturated.iter().next().copied() else { return false; }; let grains = self.sand.entry(cell).or_default(); let amount = *grains / 4; *grains %= 4; for neighbor in cell.neighbors() { self.add(neighbor, amount); } let _ = self.saturated.remove(&cell); true } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct Cell { row: isize, column: isize, } impl Cell { pub const ORIGIN: Self = Self { row: 0, column: 0 }; pub fn neighbors(self) -> impl Iterator<Item = Cell> { [(0, -1), (-1, 0), (1, 0), (0, 1)] .into_iter() .map(move |(i, j)| Cell { row: self.row + i, column: self.column + j, }) } } struct Viewer<'a> { grid: &'a Grid, cache: &'a canvas::Cache, } impl Viewer<'_> { const CELL_SIZE: f32 = 10.0; } impl canvas::Program<Message> for Viewer<'_> { type State = (); fn update( &self, _state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<canvas::Action<Message>> { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { let position = cursor.position_in(bounds)? - (bounds.center() - Point::ORIGIN); let row = (position.x / Self::CELL_SIZE).round() as isize; let column = (position.y / Self::CELL_SIZE).round() as isize; Some(canvas::Action::publish(Message::Add(Cell { row, column }))) } Event::Mouse(mouse::Event::CursorMoved { .. }) if cursor.is_over(bounds) => { Some(canvas::Action::request_redraw()) } _ => None, } } fn draw( &self, _state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec<canvas::Geometry<Renderer>> { let geometry = self.cache.draw(renderer, bounds.size(), |frame| { let palette = theme.extended_palette(); let cells_x = (frame.width() / Self::CELL_SIZE).ceil() as isize; let cells_y = (frame.height() / Self::CELL_SIZE).ceil() as isize; let rows = -cells_x / 2..=cells_x / 2; let columns = -cells_y / 2..=cells_y / 2; frame.translate( frame.center() - Point::ORIGIN - Vector::new(Self::CELL_SIZE, Self::CELL_SIZE) / 2.0, ); for row in rows { for column in columns.clone() { let grains = self .grid .sand .get(&Cell { row, column }) .copied() .unwrap_or_default(); if grains == 0 { continue; } frame.fill_rectangle( Point::new( row as f32 * Self::CELL_SIZE, column as f32 * Self::CELL_SIZE, ), Size::new(Self::CELL_SIZE, Self::CELL_SIZE), match grains { 4.. => palette.secondary.base.color, 3 => palette.background.strongest.color, 2 => palette.background.strong.color, _ => palette.background.weak.color, }, ); } } }); let cursor = { let mut frame = canvas::Frame::new(renderer, bounds.size()); if let Some(position) = cursor.position_in(bounds) { let translation = frame.center() - Point::ORIGIN; let position = position - translation; frame.translate(translation - Vector::new(Self::CELL_SIZE, Self::CELL_SIZE) / 2.0); frame.fill_rectangle( Point::new( (position.x / Self::CELL_SIZE).round() * Self::CELL_SIZE, (position.y / Self::CELL_SIZE).round() * Self::CELL_SIZE, ), Size::new(Self::CELL_SIZE, Self::CELL_SIZE), theme.palette().primary, ); } frame.into_geometry() }; vec![geometry, cursor] } fn mouse_interaction( &self, _state: &Self::State, bounds: Rectangle, cursor: mouse::Cursor, ) -> mouse::Interaction { if cursor.is_over(bounds) { mouse::Interaction::Crosshair } else { mouse::Interaction::None } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/custom_quad/src/main.rs
examples/custom_quad/src/main.rs
//! This example showcases a drawing a quad. use iced::border; use iced::widget::{center, column, slider, text, toggler}; use iced::{Center, Color, Element, Shadow, Vector}; pub fn main() -> iced::Result { iced::run(Example::update, Example::view) } struct Example { radius: border::Radius, border_width: f32, shadow: Shadow, snap: bool, } #[derive(Debug, Clone, Copy)] #[allow(clippy::enum_variant_names)] enum Message { RadiusTopLeftChanged(f32), RadiusTopRightChanged(f32), RadiusBottomRightChanged(f32), RadiusBottomLeftChanged(f32), BorderWidthChanged(f32), ShadowXOffsetChanged(f32), ShadowYOffsetChanged(f32), ShadowBlurRadiusChanged(f32), SnapToggled(bool), } impl Example { fn new() -> Self { Self { radius: border::radius(50), border_width: 0.0, shadow: Shadow { color: Color::from_rgba(0.0, 0.0, 0.0, 0.8), offset: Vector::new(0.0, 8.0), blur_radius: 16.0, }, snap: false, } } fn update(&mut self, message: Message) { match message { Message::RadiusTopLeftChanged(radius) => { self.radius = self.radius.top_left(radius); } Message::RadiusTopRightChanged(radius) => { self.radius = self.radius.top_right(radius); } Message::RadiusBottomRightChanged(radius) => { self.radius = self.radius.bottom_right(radius); } Message::RadiusBottomLeftChanged(radius) => { self.radius = self.radius.bottom_left(radius); } Message::BorderWidthChanged(width) => { self.border_width = width; } Message::ShadowXOffsetChanged(x) => { self.shadow.offset.x = x; } Message::ShadowYOffsetChanged(y) => { self.shadow.offset.y = y; } Message::ShadowBlurRadiusChanged(s) => { self.shadow.blur_radius = s; } Message::SnapToggled(snap) => { self.snap = snap; } } } fn view(&self) -> Element<'_, Message> { let border::Radius { top_left, top_right, bottom_right, bottom_left, } = self.radius; let Shadow { offset: Vector { x: sx, y: sy }, blur_radius: sr, .. } = self.shadow; let content = column![ quad::CustomQuad::new( 200.0, self.radius, self.border_width, self.shadow, self.snap, ), text!("Radius: {top_left:.2}/{top_right:.2}/{bottom_right:.2}/{bottom_left:.2}"), slider(1.0..=200.0, top_left, Message::RadiusTopLeftChanged).step(0.01), slider(1.0..=200.0, top_right, Message::RadiusTopRightChanged).step(0.01), slider(1.0..=200.0, bottom_right, Message::RadiusBottomRightChanged).step(0.01), slider(1.0..=200.0, bottom_left, Message::RadiusBottomLeftChanged).step(0.01), slider(0.0..=10.0, self.border_width, Message::BorderWidthChanged).step(0.01), text!("Shadow: {sx:.2}x{sy:.2}, {sr:.2}"), slider(-100.0..=100.0, sx, Message::ShadowXOffsetChanged).step(0.01), slider(-100.0..=100.0, sy, Message::ShadowYOffsetChanged).step(0.01), slider(0.0..=100.0, sr, Message::ShadowBlurRadiusChanged).step(0.01), toggler(self.snap) .label("Snap to pixel grid") .on_toggle(Message::SnapToggled), ] .padding(20) .spacing(20) .max_width(500) .align_x(Center); center(content).into() } } impl Default for Example { fn default() -> Self { Self::new() } } mod quad { use iced::advanced::layout::{self, Layout}; use iced::advanced::renderer; use iced::advanced::widget::{self, Widget}; use iced::border; use iced::mouse; use iced::{Border, Color, Element, Length, Rectangle, Shadow, Size}; pub struct CustomQuad { size: f32, radius: border::Radius, border_width: f32, shadow: Shadow, snap: bool, } impl CustomQuad { pub fn new( size: f32, radius: border::Radius, border_width: f32, shadow: Shadow, snap: bool, ) -> Self { Self { size, radius, border_width, shadow, snap, } } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for CustomQuad where Renderer: renderer::Renderer, { fn size(&self) -> Size<Length> { Size { width: Length::Shrink, height: Length::Shrink, } } fn layout( &mut self, _tree: &mut widget::Tree, _renderer: &Renderer, _limits: &layout::Limits, ) -> layout::Node { layout::Node::new(Size::new(self.size, self.size)) } fn draw( &self, _tree: &widget::Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { renderer.fill_quad( renderer::Quad { bounds: layout.bounds(), border: Border { radius: self.radius, width: self.border_width, color: Color::from_rgb(1.0, 0.0, 0.0), }, shadow: self.shadow, snap: self.snap, }, Color::BLACK, ); } } impl<Message> From<CustomQuad> for Element<'_, Message> { fn from(circle: CustomQuad) -> Self { Self::new(circle) } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/events/src/main.rs
examples/events/src/main.rs
use iced::event::{self, Event}; use iced::widget::{Column, button, center, checkbox, text}; use iced::window; use iced::{Center, Element, Fill, Subscription, Task}; pub fn main() -> iced::Result { iced::application(Events::default, Events::update, Events::view) .subscription(Events::subscription) .exit_on_close_request(false) .run() } #[derive(Debug, Default)] struct Events { last: Vec<Event>, enabled: bool, } #[derive(Debug, Clone)] enum Message { EventOccurred(Event), Toggled(bool), Exit, } impl Events { fn update(&mut self, message: Message) -> Task<Message> { match message { Message::EventOccurred(event) if self.enabled => { self.last.push(event); if self.last.len() > 5 { let _ = self.last.remove(0); } Task::none() } Message::EventOccurred(event) => { if let Event::Window(window::Event::CloseRequested) = event { window::latest().and_then(window::close) } else { Task::none() } } Message::Toggled(enabled) => { self.enabled = enabled; Task::none() } Message::Exit => window::latest().and_then(window::close), } } fn subscription(&self) -> Subscription<Message> { event::listen().map(Message::EventOccurred) } fn view(&self) -> Element<'_, Message> { let events = Column::with_children( self.last .iter() .map(|event| text!("{event:?}").size(40)) .map(Element::from), ); let toggle = checkbox(self.enabled) .label("Listen to runtime events") .on_toggle(Message::Toggled); let exit = button(text("Exit").width(Fill).align_x(Center)) .width(100) .padding(10) .on_press(Message::Exit); let content = Column::new() .align_x(Center) .spacing(20) .push(events) .push(toggle) .push(exit); center(content).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/layout/src/main.rs
examples/layout/src/main.rs
use iced::border; use iced::keyboard; use iced::mouse; use iced::widget::{ button, canvas, center, center_y, checkbox, column, container, pick_list, pin, responsive, row, rule, scrollable, space, stack, text, }; use iced::{ Center, Element, Fill, Font, Length, Point, Rectangle, Renderer, Shrink, Subscription, Theme, color, }; pub fn main() -> iced::Result { iced::application(Layout::default, Layout::update, Layout::view) .subscription(Layout::subscription) .theme(Layout::theme) .title(Layout::title) .run() } #[derive(Debug, Default)] struct Layout { example: Example, explain: bool, theme: Option<Theme>, } #[derive(Debug, Clone)] enum Message { Next, Previous, ExplainToggled(bool), ThemeSelected(Theme), } impl Layout { fn title(&self) -> String { format!("{} - Layout - Iced", self.example.title) } fn update(&mut self, message: Message) { match message { Message::Next => { self.example = self.example.next(); } Message::Previous => { self.example = self.example.previous(); } Message::ExplainToggled(explain) => { self.explain = explain; } Message::ThemeSelected(theme) => { self.theme = Some(theme); } } } fn subscription(&self) -> Subscription<Message> { use keyboard::key; keyboard::listen().filter_map(|event| { let keyboard::Event::KeyPressed { modified_key, repeat: false, .. } = event else { return None; }; match modified_key { keyboard::Key::Named(key::Named::ArrowLeft) => Some(Message::Previous), keyboard::Key::Named(key::Named::ArrowRight) => Some(Message::Next), _ => None, } }) } fn view(&self) -> Element<'_, Message> { let header = row![ text(self.example.title).size(20).font(Font::MONOSPACE), space::horizontal(), checkbox(self.explain) .label("Explain") .on_toggle(Message::ExplainToggled), pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeSelected).placeholder("Theme"), ] .spacing(20) .align_y(Center); let example = center(if self.explain { self.example.view().explain(color!(0x0000ff)) } else { self.example.view() }) .style(|theme| { let palette = theme.extended_palette(); container::Style::default() .border(border::color(palette.background.strong.color).width(4)) }) .padding(4); let controls = row![ (!self.example.is_first()).then_some( button(text("← Previous")) .padding([5, 10]) .on_press(Message::Previous) ), space::horizontal(), (!self.example.is_last()).then_some( button(text("Next →")) .padding([5, 10]) .on_press(Message::Next) ), ]; column![header, example, controls] .spacing(10) .padding(20) .into() } fn theme(&self) -> Option<Theme> { self.theme.clone() } } #[derive(Debug, Clone, Copy, Eq)] struct Example { title: &'static str, view: fn() -> Element<'static, Message>, } impl Example { const LIST: &'static [Self] = &[ Self { title: "Centered", view: centered, }, Self { title: "Column", view: column_, }, Self { title: "Row", view: row_, }, Self { title: "Space", view: space_, }, Self { title: "Application", view: application, }, Self { title: "Quotes", view: quotes, }, Self { title: "Pinning", view: pinning, }, Self { title: "Responsive", view: responsive_, }, ]; fn is_first(self) -> bool { Self::LIST.first() == Some(&self) } fn is_last(self) -> bool { Self::LIST.last() == Some(&self) } fn previous(self) -> Self { let Some(index) = Self::LIST.iter().position(|&example| example == self) else { return self; }; Self::LIST .get(index.saturating_sub(1)) .copied() .unwrap_or(self) } fn next(self) -> Self { let Some(index) = Self::LIST.iter().position(|&example| example == self) else { return self; }; Self::LIST.get(index + 1).copied().unwrap_or(self) } fn view(&self) -> Element<'_, Message> { (self.view)() } } impl Default for Example { fn default() -> Self { Self::LIST[0] } } impl PartialEq for Example { fn eq(&self, other: &Self) -> bool { self.title == other.title } } fn centered<'a>() -> Element<'a, Message> { center(text("I am centered!").size(50)).into() } fn column_<'a>() -> Element<'a, Message> { column![ "A column can be used to", "lay out widgets vertically.", square(50), square(50), square(50), "The amount of space between", "elements can be configured!", ] .spacing(40) .into() } fn row_<'a>() -> Element<'a, Message> { row![ "A row works like a column...", square(50), square(50), square(50), "but lays out widgets horizontally!", ] .spacing(40) .into() } fn space_<'a>() -> Element<'a, Message> { row!["Left!", space::horizontal(), "Right!"].into() } fn application<'a>() -> Element<'a, Message> { let header = container( row![ square(40), space::horizontal(), "Header!", space::horizontal(), square(40), ] .padding(10) .align_y(Center), ) .style(|theme| { let palette = theme.extended_palette(); container::Style::default().border(border::color(palette.background.strong.color).width(1)) }); let sidebar = center_y( column!["Sidebar!", square(50), square(50)] .spacing(40) .padding(10) .width(200) .align_x(Center), ) .style(container::rounded_box); let content = container( scrollable( column![ "Content!", row((1..10).map(|i| square(if i % 2 == 0 { 80 } else { 160 }))) .spacing(20) .align_y(Center) .wrap(), "The end" ] .spacing(40) .align_x(Center) .width(Fill), ) .height(Fill), ) .padding(10); column![header, row![sidebar, content]].into() } fn quotes<'a>() -> Element<'a, Message> { fn quote<'a>(content: impl Into<Element<'a, Message>>) -> Element<'a, Message> { row![rule::vertical(1), content.into()] .spacing(10) .height(Shrink) .into() } fn reply<'a>( original: impl Into<Element<'a, Message>>, reply: impl Into<Element<'a, Message>>, ) -> Element<'a, Message> { column![quote(original), reply.into()].spacing(10).into() } column![ reply( reply("This is the original message", "This is a reply"), "This is another reply", ), rule::horizontal(1), text("A separator ↑"), ] .width(Shrink) .spacing(10) .into() } fn pinning<'a>() -> Element<'a, Message> { column![ "The pin widget can be used to position a widget \ at some fixed coordinates inside some other widget.", stack![ container(pin("• (50, 50)").x(50).y(50)) .width(500) .height(500) .style(container::bordered_box), pin("• (300, 300)").x(300).y(300), ] ] .align_x(Center) .spacing(10) .into() } fn responsive_<'a>() -> Element<'a, Message> { column![ responsive(|size| { container(center( text!("{}x{}px", size.width, size.width).font(Font::MONOSPACE), )) .clip(true) .width(size.width / 4.0) .height(size.width / 4.0) .style(container::bordered_box) .into() }) .width(Shrink) .height(Shrink), responsive(|size| { let size = size.ratio(16.0 / 9.0); container(center( text!("{:.0}x{:.0}px (16:9)", size.width, size.height).font(Font::MONOSPACE), )) .clip(true) .width(size.width) .height(size.height) .style(container::bordered_box) .into() }) .width(Shrink) .height(Shrink) ] .align_x(Center) .spacing(10) .padding(10) .into() } fn square<'a>(size: impl Into<Length> + Copy) -> Element<'a, Message> { struct Square; impl canvas::Program<Message> for Square { type State = (); fn draw( &self, _state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<canvas::Geometry> { let mut frame = canvas::Frame::new(renderer, bounds.size()); let palette = theme.extended_palette(); frame.fill_rectangle( Point::ORIGIN, bounds.size(), palette.background.strong.color, ); vec![frame.into_geometry()] } } canvas(Square).width(size).height(size).into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/system_information/src/main.rs
examples/system_information/src/main.rs
use iced::system; use iced::widget::{button, center, column, text}; use iced::{Element, Task}; pub fn main() -> iced::Result { iced::application(Example::new, Example::update, Example::view).run() } #[derive(Default)] #[allow(clippy::large_enum_variant)] enum Example { #[default] Loading, Loaded { information: system::Information, }, } #[derive(Clone, Debug)] #[allow(clippy::large_enum_variant)] enum Message { InformationReceived(system::Information), Refresh, } impl Example { fn new() -> (Self, Task<Message>) { ( Self::Loading, system::information().map(Message::InformationReceived), ) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Refresh => { let (state, refresh) = Self::new(); *self = state; refresh } Message::InformationReceived(information) => { *self = Self::Loaded { information }; Task::none() } } } fn view(&self) -> Element<'_, Message> { use bytesize::ByteSize; let content: Element<_> = match self { Example::Loading => text("Loading...").size(40).into(), Example::Loaded { information } => { let system_name = text!( "System name: {}", information .system_name .as_ref() .unwrap_or(&"unknown".to_string()) ); let system_kernel = text!( "System kernel: {}", information .system_kernel .as_ref() .unwrap_or(&"unknown".to_string()) ); let system_version = text!( "System version: {}", information .system_version .as_ref() .unwrap_or(&"unknown".to_string()) ); let system_short_version = text!( "System short version: {}", information .system_short_version .as_ref() .unwrap_or(&"unknown".to_string()) ); let cpu_brand = text!("Processor brand: {}", information.cpu_brand); let cpu_cores = text!( "Processor cores: {}", information .cpu_cores .map_or("unknown".to_string(), |cores| cores.to_string()) ); let memory_readable = ByteSize::b(information.memory_total).to_string_as(true); let memory_total = text!( "Memory (total): {} bytes ({memory_readable})", information.memory_total, ); let memory_text = if let Some(memory_used) = information.memory_used { let memory_readable = ByteSize::b(memory_used).to_string_as(true); format!("{memory_used} bytes ({memory_readable})") } else { String::from("None") }; let memory_used = text!("Memory (used): {memory_text}"); let graphics_adapter = text!("Graphics adapter: {}", information.graphics_adapter); let graphics_backend = text!("Graphics backend: {}", information.graphics_backend); column![ system_name.size(30), system_kernel.size(30), system_version.size(30), system_short_version.size(30), cpu_brand.size(30), cpu_cores.size(30), memory_total.size(30), memory_used.size(30), graphics_adapter.size(30), graphics_backend.size(30), button("Refresh").on_press(Message::Refresh) ] .spacing(10) .into() } }; center(content).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/counter/src/main.rs
examples/counter/src/main.rs
use iced::Center; use iced::widget::{Column, button, column, text}; pub fn main() -> iced::Result { iced::run(Counter::update, Counter::view) } #[derive(Default)] struct Counter { value: i64, } #[derive(Debug, Clone, Copy)] enum Message { Increment, Decrement, } impl Counter { fn update(&mut self, message: Message) { match message { Message::Increment => { self.value += 1; } Message::Decrement => { self.value -= 1; } } } fn view(&self) -> Column<'_, Message> { column![ button("Increment").on_press(Message::Increment), text(self.value).size(50), button("Decrement").on_press(Message::Decrement) ] .padding(20) .align_x(Center) } } #[cfg(test)] mod tests { use super::*; use iced_test::{Error, simulator}; #[test] fn it_counts() -> Result<(), Error> { let mut counter = Counter { value: 0 }; let mut ui = simulator(counter.view()); let _ = ui.click("Increment")?; let _ = ui.click("Increment")?; let _ = ui.click("Decrement")?; for message in ui.into_messages() { counter.update(message); } assert_eq!(counter.value, 1); let mut ui = simulator(counter.view()); assert!(ui.find("1").is_ok(), "Counter should display 1!"); Ok(()) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/pokedex/src/main.rs
examples/pokedex/src/main.rs
use iced::futures; use iced::widget::{self, center, column, image, row, text}; use iced::{Center, Element, Fill, Right, Task}; pub fn main() -> iced::Result { iced::application(Pokedex::new, Pokedex::update, Pokedex::view) .title(Pokedex::title) .run() } #[derive(Debug)] enum Pokedex { Loading, Loaded { pokemon: Pokemon }, Errored, } #[derive(Debug, Clone)] enum Message { PokemonFound(Result<Pokemon, Error>), Search, } impl Pokedex { fn new() -> (Self, Task<Message>) { (Self::Loading, Self::search()) } fn search() -> Task<Message> { Task::perform(Pokemon::search(), Message::PokemonFound) } fn title(&self) -> String { let subtitle = match self { Pokedex::Loading => "Loading", Pokedex::Loaded { pokemon, .. } => &pokemon.name, Pokedex::Errored => "Whoops!", }; format!("{subtitle} - Pokédex") } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::PokemonFound(Ok(pokemon)) => { *self = Pokedex::Loaded { pokemon }; Task::none() } Message::PokemonFound(Err(_error)) => { *self = Pokedex::Errored; Task::none() } Message::Search => match self { Pokedex::Loading => Task::none(), _ => { *self = Pokedex::Loading; Self::search() } }, } } fn view(&self) -> Element<'_, Message> { let content: Element<_> = match self { Pokedex::Loading => text("Searching for Pokémon...").size(40).into(), Pokedex::Loaded { pokemon } => column![ pokemon.view(), button("Keep searching!").on_press(Message::Search) ] .max_width(500) .spacing(20) .align_x(Right) .into(), Pokedex::Errored => column![ text("Whoops! Something went wrong...").size(40), button("Try again").on_press(Message::Search) ] .spacing(20) .align_x(Right) .into(), }; center(content).into() } } #[derive(Debug, Clone)] struct Pokemon { number: u16, name: String, description: String, image: image::Handle, } impl Pokemon { const TOTAL: u16 = 807; fn view(&self) -> Element<'_, Message> { row![ image::viewer(self.image.clone()), column![ row![ text(&self.name).size(30).width(Fill), text!("#{}", self.number).size(20).color([0.5, 0.5, 0.5]), ] .align_y(Center) .spacing(20), self.description.as_ref(), ] .spacing(20), ] .spacing(20) .align_y(Center) .into() } async fn search() -> Result<Pokemon, Error> { use rand::Rng; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Entry { name: String, flavor_text_entries: Vec<FlavorText>, } #[derive(Debug, Deserialize)] struct FlavorText { flavor_text: String, language: Language, } #[derive(Debug, Deserialize)] struct Language { name: String, } let id = { let mut rng = rand::rngs::OsRng; rng.gen_range(0..Pokemon::TOTAL) }; let fetch_entry = async { let url = format!("https://pokeapi.co/api/v2/pokemon-species/{id}"); reqwest::get(&url).await?.json().await }; let (entry, image): (Entry, _) = futures::future::try_join(fetch_entry, Self::fetch_image(id)).await?; let description = entry .flavor_text_entries .iter() .find(|text| text.language.name == "en") .ok_or(Error::LanguageError)?; Ok(Pokemon { number: id, name: entry.name.to_uppercase(), description: description .flavor_text .chars() .map(|c| if c.is_control() { ' ' } else { c }) .collect(), image, }) } async fn fetch_image(id: u16) -> Result<image::Handle, reqwest::Error> { let url = format!( "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{id}.png" ); #[cfg(not(target_arch = "wasm32"))] { let bytes = reqwest::get(&url).await?.bytes().await?; Ok(image::Handle::from_bytes(bytes)) } #[cfg(target_arch = "wasm32")] Ok(image::Handle::from_path(url)) } } #[derive(Debug, Clone)] enum Error { APIError, LanguageError, } impl From<reqwest::Error> for Error { fn from(error: reqwest::Error) -> Error { dbg!(error); Error::APIError } } fn button(text: &str) -> widget::Button<'_, Message> { widget::button(text).padding(10) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/ferris/src/main.rs
examples/ferris/src/main.rs
use iced::time::Instant; use iced::widget::{center, checkbox, column, container, image, pick_list, row, slider, text}; use iced::window; use iced::{ Bottom, Center, Color, ContentFit, Degrees, Element, Fill, Radians, Rotation, Subscription, Theme, }; pub fn main() -> iced::Result { iced::application(Image::default, Image::update, Image::view) .subscription(Image::subscription) .theme(Theme::TokyoNight) .run() } struct Image { width: f32, opacity: f32, rotation: Rotation, content_fit: ContentFit, spin: bool, last_tick: Instant, } #[derive(Debug, Clone, Copy)] enum Message { WidthChanged(f32), OpacityChanged(f32), RotationStrategyChanged(RotationStrategy), RotationChanged(Degrees), ContentFitChanged(ContentFit), SpinToggled(bool), RedrawRequested(Instant), } impl Image { fn update(&mut self, message: Message) { match message { Message::WidthChanged(width) => { self.width = width; } Message::OpacityChanged(opacity) => { self.opacity = opacity; } Message::RotationStrategyChanged(strategy) => { self.rotation = match strategy { RotationStrategy::Floating => Rotation::Floating(self.rotation.radians()), RotationStrategy::Solid => Rotation::Solid(self.rotation.radians()), }; } Message::RotationChanged(rotation) => { self.rotation = match self.rotation { Rotation::Floating(_) => Rotation::Floating(rotation.into()), Rotation::Solid(_) => Rotation::Solid(rotation.into()), }; } Message::ContentFitChanged(content_fit) => { self.content_fit = content_fit; } Message::SpinToggled(spin) => { self.spin = spin; self.last_tick = Instant::now(); } Message::RedrawRequested(now) => { const ROTATION_SPEED: Degrees = Degrees(360.0); let delta = (now - self.last_tick).as_millis() as f32 / 1_000.0; *self.rotation.radians_mut() = (self.rotation.radians() + ROTATION_SPEED * delta) % (2.0 * Radians::PI); self.last_tick = now; } } } fn subscription(&self) -> Subscription<Message> { if self.spin { window::frames().map(Message::RedrawRequested) } else { Subscription::none() } } fn view(&self) -> Element<'_, Message> { let i_am_ferris = column![ "Hello!", Element::from( image(concat!( env!("CARGO_MANIFEST_DIR"), "/../tour/images/ferris.png", )) .width(self.width) .content_fit(self.content_fit) .rotation(self.rotation) .opacity(self.opacity) ) .explain(Color::WHITE), "I am Ferris!" ] .spacing(20) .align_x(Center); let fit = row![ pick_list( [ ContentFit::Contain, ContentFit::Cover, ContentFit::Fill, ContentFit::None, ContentFit::ScaleDown ], Some(self.content_fit), Message::ContentFitChanged ) .width(Fill), pick_list( [RotationStrategy::Floating, RotationStrategy::Solid], Some(match self.rotation { Rotation::Floating(_) => RotationStrategy::Floating, Rotation::Solid(_) => RotationStrategy::Solid, }), Message::RotationStrategyChanged, ) .width(Fill), ] .spacing(10) .align_y(Bottom); let properties = row![ with_value( slider(100.0..=500.0, self.width, Message::WidthChanged), format!("Width: {}px", self.width) ), with_value( slider(0.0..=1.0, self.opacity, Message::OpacityChanged).step(0.01), format!("Opacity: {:.2}", self.opacity) ), with_value( row![ slider( Degrees::RANGE, self.rotation.degrees(), Message::RotationChanged ), checkbox(self.spin) .label("Spin!") .text_size(12) .on_toggle(Message::SpinToggled) .size(12) ] .spacing(10) .align_y(Center), format!("Rotation: {:.0}°", f32::from(self.rotation.degrees())) ) ] .spacing(10) .align_y(Bottom); container(column![fit, center(i_am_ferris), properties].spacing(10)) .padding(10) .into() } } impl Default for Image { fn default() -> Self { Self { width: 300.0, opacity: 1.0, rotation: Rotation::default(), content_fit: ContentFit::default(), spin: false, last_tick: Instant::now(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum RotationStrategy { Floating, Solid, } impl std::fmt::Display for RotationStrategy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Floating => "Floating", Self::Solid => "Solid", }) } } fn with_value<'a>(control: impl Into<Element<'a, Message>>, value: String) -> Element<'a, Message> { column![control.into(), text(value).size(12).line_height(1.0)] .spacing(2) .align_x(Center) .into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/color_palette/src/main.rs
examples/color_palette/src/main.rs
use iced::alignment; use iced::mouse; use iced::widget::canvas::{self, Canvas, Frame, Geometry, Path}; use iced::widget::{Slider, column, row, text}; use iced::{Center, Color, Element, Fill, Font, Pixels, Point, Rectangle, Renderer, Size, Vector}; use palette::{Darken, Hsl, Lighten, ShiftHue, convert::FromColor, rgb::Rgb}; use std::marker::PhantomData; use std::ops::RangeInclusive; pub fn main() -> iced::Result { iced::application( ColorPalette::default, ColorPalette::update, ColorPalette::view, ) .theme(ColorPalette::theme) .default_font(Font::MONOSPACE) .run() } #[derive(Default)] pub struct ColorPalette { theme: Theme, rgb: ColorPicker<Color>, hsl: ColorPicker<palette::Hsl>, hsv: ColorPicker<palette::Hsv>, hwb: ColorPicker<palette::Hwb>, lab: ColorPicker<palette::Lab>, lch: ColorPicker<palette::Lch>, } #[derive(Debug, Clone, Copy)] pub enum Message { RgbColorChanged(Color), HslColorChanged(palette::Hsl), HsvColorChanged(palette::Hsv), HwbColorChanged(palette::Hwb), LabColorChanged(palette::Lab), LchColorChanged(palette::Lch), } impl ColorPalette { fn update(&mut self, message: Message) { let srgb = match message { Message::RgbColorChanged(rgb) => to_rgb(rgb), Message::HslColorChanged(hsl) => Rgb::from_color(hsl), Message::HsvColorChanged(hsv) => Rgb::from_color(hsv), Message::HwbColorChanged(hwb) => Rgb::from_color(hwb), Message::LabColorChanged(lab) => Rgb::from_color(lab), Message::LchColorChanged(lch) => Rgb::from_color(lch), }; self.theme = Theme::new(to_color(srgb)); } fn view(&self) -> Element<'_, Message> { let base = self.theme.base; let srgb = to_rgb(base); let hsl = palette::Hsl::from_color(srgb); let hsv = palette::Hsv::from_color(srgb); let hwb = palette::Hwb::from_color(srgb); let lab = palette::Lab::from_color(srgb); let lch = palette::Lch::from_color(srgb); column![ self.rgb.view(base).map(Message::RgbColorChanged), self.hsl.view(hsl).map(Message::HslColorChanged), self.hsv.view(hsv).map(Message::HsvColorChanged), self.hwb.view(hwb).map(Message::HwbColorChanged), self.lab.view(lab).map(Message::LabColorChanged), self.lch.view(lch).map(Message::LchColorChanged), self.theme.view(), ] .padding(10) .spacing(10) .into() } fn theme(&self) -> iced::Theme { iced::Theme::custom( String::from("Custom"), iced::theme::Palette { background: self.theme.base, primary: *self.theme.lower.first().unwrap(), text: *self.theme.higher.last().unwrap(), success: *self.theme.lower.last().unwrap(), warning: *self.theme.higher.last().unwrap(), danger: *self.theme.higher.last().unwrap(), }, ) } } #[derive(Debug)] struct Theme { lower: Vec<Color>, base: Color, higher: Vec<Color>, canvas_cache: canvas::Cache, } impl Theme { pub fn new(base: impl Into<Color>) -> Theme { let base = base.into(); // Convert to HSL color for manipulation let hsl = Hsl::from_color(to_rgb(base)); let lower = [ hsl.shift_hue(-135.0).lighten(0.075), hsl.shift_hue(-120.0), hsl.shift_hue(-105.0).darken(0.075), hsl.darken(0.075), ]; let higher = [ hsl.lighten(0.075), hsl.shift_hue(105.0).darken(0.075), hsl.shift_hue(120.0), hsl.shift_hue(135.0).lighten(0.075), ]; Theme { lower: lower .iter() .map(|&color| to_color(Rgb::from_color(color))) .collect(), base, higher: higher .iter() .map(|&color| to_color(Rgb::from_color(color))) .collect(), canvas_cache: canvas::Cache::default(), } } pub fn len(&self) -> usize { self.lower.len() + self.higher.len() + 1 } pub fn colors(&self) -> impl Iterator<Item = &Color> { self.lower .iter() .chain(std::iter::once(&self.base)) .chain(self.higher.iter()) } pub fn view(&self) -> Element<'_, Message> { Canvas::new(self).width(Fill).height(Fill).into() } fn draw(&self, frame: &mut Frame, text_color: Color) { let pad = 20.0; let box_size = Size { width: frame.width() / self.len() as f32, height: frame.height() / 2.0 - pad, }; let triangle = Path::new(|path| { path.move_to(Point { x: 0.0, y: -0.5 }); path.line_to(Point { x: -0.5, y: 0.0 }); path.line_to(Point { x: 0.5, y: 0.0 }); path.close(); }); let mut text = canvas::Text { align_x: text::Alignment::Center, align_y: alignment::Vertical::Top, size: Pixels(15.0), color: text_color, ..canvas::Text::default() }; for (i, &color) in self.colors().enumerate() { let anchor = Point { x: (i as f32) * box_size.width, y: 0.0, }; frame.fill_rectangle(anchor, box_size, color); // We show a little indicator for the base color if color == self.base { let triangle_x = anchor.x + box_size.width / 2.0; frame.with_save(|frame| { frame.translate(Vector::new(triangle_x, 0.0)); frame.scale(10.0); frame.rotate(std::f32::consts::PI); frame.fill(&triangle, Color::WHITE); }); frame.with_save(|frame| { frame.translate(Vector::new(triangle_x, box_size.height)); frame.scale(10.0); frame.fill(&triangle, Color::WHITE); }); } frame.fill_text(canvas::Text { content: color_hex_string(&color), position: Point { x: anchor.x + box_size.width / 2.0, y: box_size.height, }, ..text }); } text.align_y = alignment::Vertical::Bottom; let hsl = Hsl::from_color(to_rgb(self.base)); for i in 0..self.len() { let pct = (i as f32 + 1.0) / (self.len() as f32 + 1.0); let graded = Hsl { lightness: 1.0 - pct, ..hsl }; let color: Color = to_color(Rgb::from_color(graded)); let anchor = Point { x: (i as f32) * box_size.width, y: box_size.height + 2.0 * pad, }; frame.fill_rectangle(anchor, box_size, color); frame.fill_text(canvas::Text { content: color_hex_string(&color), position: Point { x: anchor.x + box_size.width / 2.0, y: box_size.height + 2.0 * pad, }, ..text }); } } } impl<Message> canvas::Program<Message> for Theme { type State = (); fn draw( &self, _state: &Self::State, renderer: &Renderer, theme: &iced::Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { let theme = self.canvas_cache.draw(renderer, bounds.size(), |frame| { let palette = theme.extended_palette(); self.draw(frame, palette.background.base.text); }); vec![theme] } } impl Default for Theme { fn default() -> Self { Theme::new(Color::from_rgb8(75, 128, 190)) } } fn color_hex_string(color: &Color) -> String { format!( "#{:x}{:x}{:x}", (255.0 * color.r).round() as u8, (255.0 * color.g).round() as u8, (255.0 * color.b).round() as u8 ) } #[derive(Default)] struct ColorPicker<C: ColorSpace> { color_space: PhantomData<C>, } trait ColorSpace: Sized { const LABEL: &'static str; const COMPONENT_RANGES: [RangeInclusive<f64>; 3]; fn new(a: f32, b: f32, c: f32) -> Self; fn components(&self) -> [f32; 3]; fn to_string(&self) -> String; } impl<C: ColorSpace + Copy> ColorPicker<C> { fn view(&self, color: C) -> Element<'_, C> { let [c1, c2, c3] = color.components(); let [cr1, cr2, cr3] = C::COMPONENT_RANGES; fn slider<'a, C: Clone>( range: RangeInclusive<f64>, component: f32, update: impl Fn(f32) -> C + 'a, ) -> Slider<'a, f64, C> { Slider::new(range, f64::from(component), move |v| update(v as f32)).step(0.01) } row![ text(C::LABEL).width(50), slider(cr1, c1, move |v| C::new(v, c2, c3)), slider(cr2, c2, move |v| C::new(c1, v, c3)), slider(cr3, c3, move |v| C::new(c1, c2, v)), text(color.to_string()).width(185).size(12), ] .spacing(10) .align_y(Center) .into() } } impl ColorSpace for Color { const LABEL: &'static str = "RGB"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=1.0, 0.0..=1.0, 0.0..=1.0]; fn new(r: f32, g: f32, b: f32) -> Self { Color::from_rgb(r, g, b) } fn components(&self) -> [f32; 3] { [self.r, self.g, self.b] } fn to_string(&self) -> String { format!( "rgb({:.0}, {:.0}, {:.0})", 255.0 * self.r, 255.0 * self.g, 255.0 * self.b ) } } impl ColorSpace for palette::Hsl { const LABEL: &'static str = "HSL"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, saturation: f32, lightness: f32) -> Self { palette::Hsl::new(palette::RgbHue::from_degrees(hue), saturation, lightness) } fn components(&self) -> [f32; 3] { [ self.hue.into_positive_degrees(), self.saturation, self.lightness, ] } fn to_string(&self) -> String { format!( "hsl({:.1}, {:.1}%, {:.1}%)", self.hue.into_positive_degrees(), 100.0 * self.saturation, 100.0 * self.lightness ) } } impl ColorSpace for palette::Hsv { const LABEL: &'static str = "HSV"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, saturation: f32, value: f32) -> Self { palette::Hsv::new(palette::RgbHue::from_degrees(hue), saturation, value) } fn components(&self) -> [f32; 3] { [ self.hue.into_positive_degrees(), self.saturation, self.value, ] } fn to_string(&self) -> String { format!( "hsv({:.1}, {:.1}%, {:.1}%)", self.hue.into_positive_degrees(), 100.0 * self.saturation, 100.0 * self.value ) } } impl ColorSpace for palette::Hwb { const LABEL: &'static str = "HWB"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, whiteness: f32, blackness: f32) -> Self { palette::Hwb::new(palette::RgbHue::from_degrees(hue), whiteness, blackness) } fn components(&self) -> [f32; 3] { [ self.hue.into_positive_degrees(), self.whiteness, self.blackness, ] } fn to_string(&self) -> String { format!( "hwb({:.1}, {:.1}%, {:.1}%)", self.hue.into_positive_degrees(), 100.0 * self.whiteness, 100.0 * self.blackness ) } } impl ColorSpace for palette::Lab { const LABEL: &'static str = "Lab"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=100.0, -128.0..=127.0, -128.0..=127.0]; fn new(l: f32, a: f32, b: f32) -> Self { palette::Lab::new(l, a, b) } fn components(&self) -> [f32; 3] { [self.l, self.a, self.b] } fn to_string(&self) -> String { format!("Lab({:.1}, {:.1}, {:.1})", self.l, self.a, self.b) } } impl ColorSpace for palette::Lch { const LABEL: &'static str = "Lch"; const COMPONENT_RANGES: [RangeInclusive<f64>; 3] = [0.0..=100.0, 0.0..=128.0, 0.0..=360.0]; fn new(l: f32, chroma: f32, hue: f32) -> Self { palette::Lch::new(l, chroma, palette::LabHue::from_degrees(hue)) } fn components(&self) -> [f32; 3] { [self.l, self.chroma, self.hue.into_positive_degrees()] } fn to_string(&self) -> String { format!( "Lch({:.1}, {:.1}, {:.1})", self.l, self.chroma, self.hue.into_positive_degrees() ) } } fn to_rgb(color: Color) -> Rgb { Rgb { red: color.r, green: color.g, blue: color.b, ..Rgb::default() } } fn to_color(rgb: Rgb) -> Color { Color { r: rgb.red, g: rgb.green, b: rgb.blue, a: 1.0, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/toast/src/main.rs
examples/toast/src/main.rs
use iced::event::{self, Event}; use iced::keyboard; use iced::keyboard::key; use iced::widget::{button, center, column, operation, pick_list, row, slider, text, text_input}; use iced::{Center, Element, Fill, Subscription, Task}; use toast::{Status, Toast}; pub fn main() -> iced::Result { iced::application(App::default, App::update, App::view) .subscription(App::subscription) .run() } struct App { toasts: Vec<Toast>, editing: Toast, timeout_secs: u64, } #[derive(Debug, Clone)] #[allow(clippy::enum_variant_names)] enum Message { Add, Close(usize), Title(String), Body(String), Status(Status), Timeout(f64), Event(Event), } impl App { fn new() -> Self { App { toasts: vec![Toast { title: "Example Toast".into(), body: "Add more toasts in the form below!".into(), status: Status::Primary, }], timeout_secs: toast::DEFAULT_TIMEOUT, editing: Toast::default(), } } fn subscription(&self) -> Subscription<Message> { event::listen().map(Message::Event) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Add => { if !self.editing.title.is_empty() && !self.editing.body.is_empty() { self.toasts.push(std::mem::take(&mut self.editing)); } Task::none() } Message::Close(index) => { self.toasts.remove(index); Task::none() } Message::Title(title) => { self.editing.title = title; Task::none() } Message::Body(body) => { self.editing.body = body; Task::none() } Message::Status(status) => { self.editing.status = status; Task::none() } Message::Timeout(timeout) => { self.timeout_secs = timeout as u64; Task::none() } Message::Event(Event::Keyboard(keyboard::Event::KeyPressed { key: keyboard::Key::Named(key::Named::Tab), modifiers, .. })) if modifiers.shift() => operation::focus_previous(), Message::Event(Event::Keyboard(keyboard::Event::KeyPressed { key: keyboard::Key::Named(key::Named::Tab), .. })) => operation::focus_next(), Message::Event(_) => Task::none(), } } fn view(&self) -> Element<'_, Message> { let subtitle = |title, content: Element<'static, Message>| { column![text(title).size(14), content].spacing(5) }; let add_toast = button("Add Toast").on_press_maybe( (!self.editing.body.is_empty() && !self.editing.title.is_empty()) .then_some(Message::Add), ); let content = center( column![ subtitle( "Title", text_input("", &self.editing.title) .on_input(Message::Title) .on_submit(Message::Add) .into() ), subtitle( "Message", text_input("", &self.editing.body) .on_input(Message::Body) .on_submit(Message::Add) .into() ), subtitle( "Status", pick_list( toast::Status::ALL, Some(self.editing.status), Message::Status ) .width(Fill) .into() ), subtitle( "Timeout", row![ text!("{:0>2} sec", self.timeout_secs), slider(1.0..=30.0, self.timeout_secs as f64, Message::Timeout).step(1.0) ] .spacing(5) .into() ), column![add_toast].align_x(Center) ] .spacing(10) .max_width(200), ); toast::Manager::new(content, &self.toasts, Message::Close) .timeout(self.timeout_secs) .into() } } impl Default for App { fn default() -> Self { Self::new() } } mod toast { use std::fmt; use iced::advanced::layout::{self, Layout}; use iced::advanced::overlay; use iced::advanced::renderer; use iced::advanced::widget::{self, Operation, Tree}; use iced::advanced::{Clipboard, Shell, Widget}; use iced::mouse; use iced::time::{self, Duration, Instant}; use iced::widget::{button, column, container, row, rule, space, text}; use iced::window; use iced::{ Alignment, Center, Element, Event, Fill, Length, Point, Rectangle, Renderer, Size, Theme, Vector, }; pub const DEFAULT_TIMEOUT: u64 = 5; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Status { #[default] Primary, Secondary, Success, Danger, Warning, } impl Status { pub const ALL: &'static [Self] = &[ Self::Primary, Self::Secondary, Self::Success, Self::Danger, Self::Warning, ]; } impl fmt::Display for Status { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Status::Primary => "Primary", Status::Secondary => "Secondary", Status::Success => "Success", Status::Danger => "Danger", Status::Warning => "Warning", } .fmt(f) } } #[derive(Debug, Clone, Default)] pub struct Toast { pub title: String, pub body: String, pub status: Status, } pub struct Manager<'a, Message> { content: Element<'a, Message>, toasts: Vec<Element<'a, Message>>, timeout_secs: u64, on_close: Box<dyn Fn(usize) -> Message + 'a>, } impl<'a, Message> Manager<'a, Message> where Message: 'a + Clone, { pub fn new( content: impl Into<Element<'a, Message>>, toasts: &'a [Toast], on_close: impl Fn(usize) -> Message + 'a, ) -> Self { let toasts = toasts .iter() .enumerate() .map(|(index, toast)| { container(column![ container( row![ text(toast.title.as_str()), space::horizontal(), button("X").on_press((on_close)(index)).padding(3), ] .align_y(Center) ) .width(Fill) .padding(5) .style(match toast.status { Status::Primary => container::primary, Status::Secondary => container::secondary, Status::Success => container::success, Status::Danger => container::danger, Status::Warning => container::warning, }), rule::horizontal(1), container(text(toast.body.as_str())) .width(Fill) .padding(5) .style(container::rounded_box), ]) .max_width(200) .into() }) .collect(); Self { content: content.into(), toasts, timeout_secs: DEFAULT_TIMEOUT, on_close: Box::new(on_close), } } pub fn timeout(self, seconds: u64) -> Self { Self { timeout_secs: seconds, ..self } } } impl<Message> Widget<Message, Theme, Renderer> for Manager<'_, Message> { fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.content .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) } fn tag(&self) -> widget::tree::Tag { struct Marker; widget::tree::Tag::of::<Marker>() } fn state(&self) -> widget::tree::State { widget::tree::State::new(Vec::<Option<Instant>>::new()) } fn children(&self) -> Vec<Tree> { std::iter::once(Tree::new(&self.content)) .chain(self.toasts.iter().map(Tree::new)) .collect() } fn diff(&self, tree: &mut Tree) { let instants = tree.state.downcast_mut::<Vec<Option<Instant>>>(); // Invalidating removed instants to None allows us to remove // them here so that diffing for removed / new toast instants // is accurate instants.retain(Option::is_some); match (instants.len(), self.toasts.len()) { (old, new) if old > new => { instants.truncate(new); } (old, new) if old < new => { instants.extend(std::iter::repeat_n(Some(Instant::now()), new - old)); } _ => {} } tree.diff_children( &std::iter::once(&self.content) .chain(self.toasts.iter()) .collect::<Vec<_>>(), ); } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { operation.container(None, layout.bounds()); operation.traverse(&mut |operation| { self.content.as_widget_mut().operate( &mut tree.children[0], 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.content.as_widget_mut().update( &mut tree.children[0], 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, ) { self.content.as_widget().draw( &tree.children[0], renderer, theme, style, layout, cursor, viewport, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.content.as_widget().mouse_interaction( &tree.children[0], 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>> { let instants = tree.state.downcast_mut::<Vec<Option<Instant>>>(); let (content_state, toasts_state) = tree.children.split_at_mut(1); let content = self.content.as_widget_mut().overlay( &mut content_state[0], layout, renderer, viewport, translation, ); let toasts = (!self.toasts.is_empty()).then(|| { overlay::Element::new(Box::new(Overlay { position: layout.bounds().position() + translation, viewport: *viewport, toasts: &mut self.toasts, trees: toasts_state, instants, on_close: &self.on_close, timeout_secs: self.timeout_secs, })) }); let overlays = content.into_iter().chain(toasts).collect::<Vec<_>>(); (!overlays.is_empty()).then(|| overlay::Group::with_children(overlays).overlay()) } } struct Overlay<'a, 'b, Message> { position: Point, viewport: Rectangle, toasts: &'b mut [Element<'a, Message>], trees: &'b mut [Tree], instants: &'b mut [Option<Instant>], on_close: &'b dyn Fn(usize) -> Message, timeout_secs: u64, } impl<Message> overlay::Overlay<Message, Theme, Renderer> for Overlay<'_, '_, Message> { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { let limits = layout::Limits::new(Size::ZERO, bounds); layout::flex::resolve( layout::flex::Axis::Vertical, renderer, &limits, Fill, Fill, 10.into(), 10.0, Alignment::End, self.toasts, self.trees, ) .translate(Vector::new(self.position.x, self.position.y)) } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { if let Event::Window(window::Event::RedrawRequested(now)) = &event { self.instants .iter_mut() .enumerate() .for_each(|(index, maybe_instant)| { if let Some(instant) = maybe_instant.as_mut() { let remaining = time::seconds(self.timeout_secs).saturating_sub(instant.elapsed()); if remaining == Duration::ZERO { maybe_instant.take(); shell.publish((self.on_close)(index)); } else { shell.request_redraw_at(*now + remaining); } } }); } let viewport = layout.bounds(); for (((child, state), layout), instant) in self .toasts .iter_mut() .zip(self.trees.iter_mut()) .zip(layout.children()) .zip(self.instants.iter_mut()) { let mut local_messages = vec![]; let mut local_shell = Shell::new(&mut local_messages); child.as_widget_mut().update( state, event, layout, cursor, renderer, clipboard, &mut local_shell, &viewport, ); if !local_shell.is_empty() { instant.take(); } shell.merge(local_shell, std::convert::identity); } } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { let viewport = layout.bounds(); for ((child, tree), layout) in self .toasts .iter() .zip(self.trees.iter()) .zip(layout.children()) { child .as_widget() .draw(tree, renderer, theme, style, layout, cursor, &viewport); } } fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { operation.container(None, layout.bounds()); operation.traverse(&mut |operation| { self.toasts .iter_mut() .zip(self.trees.iter_mut()) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, layout, renderer, operation); }); }); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.toasts .iter() .zip(self.trees.iter()) .zip(layout.children()) .map(|((child, state), layout)| { child .as_widget() .mouse_interaction(state, layout, cursor, &self.viewport, renderer) .max(if cursor.is_over(layout.bounds()) { mouse::Interaction::Idle } else { Default::default() }) }) .max() .unwrap_or_default() } } impl<'a, Message> From<Manager<'a, Message>> for Element<'a, Message> where Message: 'a, { fn from(manager: Manager<'a, Message>) -> Self { Element::new(manager) } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/vectorial_text/src/main.rs
examples/vectorial_text/src/main.rs
use iced::alignment; use iced::mouse; use iced::widget::{canvas, checkbox, column, row, slider, space, text}; use iced::{Center, Element, Fill, Point, Rectangle, Renderer, Theme, Vector}; pub fn main() -> iced::Result { iced::application( VectorialText::default, VectorialText::update, VectorialText::view, ) .theme(Theme::Dark) .run() } #[derive(Default)] struct VectorialText { state: State, } #[derive(Debug, Clone, Copy)] enum Message { SizeChanged(f32), AngleChanged(f32), ScaleChanged(f32), ToggleJapanese(bool), } impl VectorialText { fn update(&mut self, message: Message) { match message { Message::SizeChanged(size) => { self.state.size = size; } Message::AngleChanged(angle) => { self.state.angle = angle; } Message::ScaleChanged(scale) => { self.state.scale = scale; } Message::ToggleJapanese(use_japanese) => { self.state.use_japanese = use_japanese; } } self.state.cache.clear(); } fn view(&self) -> Element<'_, Message> { let slider_with_label = |label, range, value, message: fn(f32) -> _| { column![ row![text(label), space::horizontal(), text!("{:.2}", value)], slider(range, value, message).step(0.01) ] .spacing(2) }; column![ canvas(&self.state).width(Fill).height(Fill), column![ checkbox(self.state.use_japanese,) .label("Use Japanese") .on_toggle(Message::ToggleJapanese), row![ slider_with_label( "Size", 2.0..=80.0, self.state.size, Message::SizeChanged, ), slider_with_label( "Angle", 0.0..=360.0, self.state.angle, Message::AngleChanged, ), slider_with_label( "Scale", 1.0..=20.0, self.state.scale, Message::ScaleChanged, ), ] .spacing(20), ] .align_x(Center) .spacing(10) ] .spacing(10) .padding(20) .into() } } struct State { size: f32, angle: f32, scale: f32, use_japanese: bool, cache: canvas::Cache, } impl State { pub fn new() -> Self { Self { size: 40.0, angle: 0.0, scale: 1.0, use_japanese: false, cache: canvas::Cache::new(), } } } impl<Message> canvas::Program<Message> for State { type State = (); fn draw( &self, _tree: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<canvas::Geometry> { let geometry = self.cache.draw(renderer, bounds.size(), |frame| { let palette = theme.palette(); let center = bounds.center(); frame.translate(Vector::new(center.x, center.y)); frame.scale(self.scale); frame.rotate(self.angle * std::f32::consts::PI / 180.0); frame.fill_text(canvas::Text { position: Point::new(0.0, 0.0), color: palette.text, size: self.size.into(), content: String::from(if self.use_japanese { "ベクトルテキスト🎉" } else { "Vectorial Text! 🎉" }), align_x: text::Alignment::Center, align_y: alignment::Vertical::Center, shaping: text::Shaping::Advanced, ..canvas::Text::default() }); }); vec![geometry] } } impl Default for State { fn default() -> Self { State::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/url_handler/src/main.rs
examples/url_handler/src/main.rs
use iced::event; use iced::widget::{center, text}; use iced::{Element, Subscription}; pub fn main() -> iced::Result { iced::application(App::default, App::update, App::view) .subscription(App::subscription) .run() } #[derive(Debug, Default)] struct App { url: Option<String>, } #[derive(Debug, Clone)] enum Message { UrlReceived(String), } impl App { fn update(&mut self, message: Message) { match message { Message::UrlReceived(url) => { self.url = Some(url); } } } fn subscription(&self) -> Subscription<Message> { event::listen_url().map(Message::UrlReceived) } fn view(&self) -> Element<'_, Message> { let content = match &self.url { Some(url) => text(url), None => text("No URL received yet!"), }; center(content.size(48)).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/modal/src/main.rs
examples/modal/src/main.rs
use iced::event::{self, Event}; use iced::keyboard; use iced::keyboard::key; use iced::widget::{ button, center, column, container, mouse_area, opaque, operation, pick_list, row, space, stack, text, text_input, }; use iced::{Bottom, Color, Element, Fill, Subscription, Task}; use std::fmt; pub fn main() -> iced::Result { iced::application(App::default, App::update, App::view) .subscription(App::subscription) .run() } #[derive(Default)] struct App { show_modal: bool, email: String, password: String, plan: Plan, } #[derive(Debug, Clone)] enum Message { ShowModal, HideModal, Email(String), Password(String), Plan(Plan), Submit, Event(Event), } impl App { fn subscription(&self) -> Subscription<Message> { event::listen().map(Message::Event) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::ShowModal => { self.show_modal = true; operation::focus_next() } Message::HideModal => { self.hide_modal(); Task::none() } Message::Email(email) => { self.email = email; Task::none() } Message::Password(password) => { self.password = password; Task::none() } Message::Plan(plan) => { self.plan = plan; Task::none() } Message::Submit => { if !self.email.is_empty() && !self.password.is_empty() { self.hide_modal(); } Task::none() } Message::Event(event) => match event { Event::Keyboard(keyboard::Event::KeyPressed { key: keyboard::Key::Named(key::Named::Tab), modifiers, .. }) => { if modifiers.shift() { operation::focus_previous() } else { operation::focus_next() } } Event::Keyboard(keyboard::Event::KeyPressed { key: keyboard::Key::Named(key::Named::Escape), .. }) => { self.hide_modal(); Task::none() } _ => Task::none(), }, } } fn view(&self) -> Element<'_, Message> { let content = container( column![ row![text("Top Left"), space::horizontal(), text("Top Right")].height(Fill), center(button(text("Show Modal")).on_press(Message::ShowModal)), row![ text("Bottom Left"), space::horizontal(), text("Bottom Right") ] .align_y(Bottom) .height(Fill), ] .height(Fill), ) .padding(10); if self.show_modal { let signup = container( column![ text("Sign Up").size(24), column![ column![ text("Email").size(12), text_input("abc@123.com", &self.email,) .on_input(Message::Email) .on_submit(Message::Submit) .padding(5), ] .spacing(5), column![ text("Password").size(12), text_input("", &self.password) .on_input(Message::Password) .on_submit(Message::Submit) .secure(true) .padding(5), ] .spacing(5), column![ text("Plan").size(12), pick_list(Plan::ALL, Some(self.plan), Message::Plan).padding(5), ] .spacing(5), button(text("Submit")).on_press(Message::HideModal), ] .spacing(10) ] .spacing(20), ) .width(300) .padding(10) .style(container::rounded_box); modal(content, signup, Message::HideModal) } else { content.into() } } } impl App { fn hide_modal(&mut self) { self.show_modal = false; self.email.clear(); self.password.clear(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] enum Plan { #[default] Basic, Pro, Enterprise, } impl Plan { pub const ALL: &'static [Self] = &[Self::Basic, Self::Pro, Self::Enterprise]; } impl fmt::Display for Plan { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Plan::Basic => "Basic", Plan::Pro => "Pro", Plan::Enterprise => "Enterprise", } .fmt(f) } } fn modal<'a, Message>( base: impl Into<Element<'a, Message>>, content: impl Into<Element<'a, Message>>, on_blur: Message, ) -> Element<'a, Message> where Message: Clone + 'a, { stack![ base.into(), opaque( mouse_area(center(opaque(content)).style(|_theme| { container::Style { background: Some( Color { a: 0.8, ..Color::BLACK } .into(), ), ..container::Style::default() } })) .on_press(on_blur) ) ] .into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/sierpinski_triangle/src/main.rs
examples/sierpinski_triangle/src/main.rs
use iced::mouse; use iced::widget::canvas::{self, Canvas, Event, Geometry}; use iced::widget::{column, row, slider, text}; use iced::{Center, Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme}; use rand::Rng; use std::fmt::Debug; fn main() -> iced::Result { iced::application( SierpinskiEmulator::default, SierpinskiEmulator::update, SierpinskiEmulator::view, ) .run() } #[derive(Debug, Default)] struct SierpinskiEmulator { graph: SierpinskiGraph, } #[derive(Debug, Clone)] pub enum Message { IterationSet(i32), PointAdded(Point), PointRemoved, } impl SierpinskiEmulator { fn update(&mut self, message: Message) { match message { Message::IterationSet(cur_iter) => { self.graph.iteration = cur_iter; } Message::PointAdded(point) => { self.graph.fix_points.push(point); self.graph.random_points.clear(); } Message::PointRemoved => { self.graph.fix_points.pop(); self.graph.random_points.clear(); } } self.graph.redraw(); } fn view(&self) -> Element<'_, Message> { column![ Canvas::new(&self.graph).width(Fill).height(Fill), row![ text!("Iteration: {:?}", self.graph.iteration), slider(0..=10000, self.graph.iteration, Message::IterationSet) ] .padding(10) .spacing(20), ] .align_x(Center) .into() } } #[derive(Default, Debug)] struct SierpinskiGraph { iteration: i32, fix_points: Vec<Point>, random_points: Vec<Point>, cache: canvas::Cache, } impl canvas::Program<Message> for SierpinskiGraph { type State = (); fn update( &self, _state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<canvas::Action<Message>> { let cursor_position = cursor.position_in(bounds)?; match event { Event::Mouse(mouse::Event::ButtonPressed(button)) => match button { mouse::Button::Left => Some(canvas::Action::publish(Message::PointAdded( cursor_position, ))), mouse::Button::Right => Some(canvas::Action::publish(Message::PointRemoved)), _ => None, }, _ => None, } .map(canvas::Action::and_capture) } fn draw( &self, _state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { let geom = self.cache.draw(renderer, bounds.size(), |frame| { frame.stroke( &canvas::Path::rectangle(Point::ORIGIN, frame.size()), canvas::Stroke::default(), ); if self.fix_points.is_empty() { return; } let mut last = None; for _ in 0..self.iteration { let p = self.gen_rand_point(last); let path = canvas::Path::rectangle(p, Size::new(1_f32, 1_f32)); frame.stroke(&path, canvas::Stroke::default()); last = Some(p); } self.fix_points.iter().for_each(|p| { let path = canvas::Path::circle(*p, 5.0); frame.fill(&path, Color::from_rgb8(0x12, 0x93, 0xD8)); }); }); vec![geom] } } impl SierpinskiGraph { fn redraw(&mut self) { self.cache.clear(); } fn gen_rand_point(&self, last: Option<Point>) -> Point { let dest_point_idx = rand::thread_rng().gen_range(0..self.fix_points.len()); let dest_point = self.fix_points[dest_point_idx]; let cur_point = last.or_else(|| Some(self.fix_points[0])).unwrap(); Point::new( (dest_point.x + cur_point.x) / 2_f32, (dest_point.y + cur_point.y) / 2_f32, ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/download_progress/src/download.rs
examples/download_progress/src/download.rs
use iced::futures::StreamExt; use iced::task::{Straw, sipper}; use std::sync::Arc; pub fn download(url: impl AsRef<str>) -> impl Straw<(), Progress, Error> { sipper(async move |mut progress| { let response = reqwest::get(url.as_ref()).await?; let total = response.content_length().ok_or(Error::NoContentLength)?; let _ = progress.send(Progress { percent: 0.0 }).await; let mut byte_stream = response.bytes_stream(); let mut downloaded = 0; while let Some(next_bytes) = byte_stream.next().await { let bytes = next_bytes?; downloaded += bytes.len(); let _ = progress .send(Progress { percent: 100.0 * downloaded as f32 / total as f32, }) .await; } Ok(()) }) } #[derive(Debug, Clone)] pub struct Progress { pub percent: f32, } #[derive(Debug, Clone)] pub enum Error { RequestFailed(Arc<reqwest::Error>), NoContentLength, } impl From<reqwest::Error> for Error { fn from(error: reqwest::Error) -> Self { Error::RequestFailed(Arc::new(error)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/download_progress/src/main.rs
examples/download_progress/src/main.rs
mod download; use download::download; use iced::task; use iced::widget::{Column, button, center, column, progress_bar, text}; use iced::{Center, Element, Function, Right, Task}; pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view).run() } #[derive(Debug)] struct Example { downloads: Vec<Download>, last_id: usize, } #[derive(Debug, Clone)] pub enum Message { Add, Download(usize), DownloadUpdated(usize, Update), } impl Example { fn new() -> Self { Self { downloads: vec![Download::new(0)], last_id: 0, } } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Add => { self.last_id += 1; self.downloads.push(Download::new(self.last_id)); Task::none() } Message::Download(index) => { let Some(download) = self.downloads.get_mut(index) else { return Task::none(); }; let task = download.start(); task.map(Message::DownloadUpdated.with(index)) } Message::DownloadUpdated(id, update) => { if let Some(download) = self.downloads.iter_mut().find(|download| download.id == id) { download.update(update); } Task::none() } } } fn view(&self) -> Element<'_, Message> { let downloads = Column::with_children(self.downloads.iter().map(Download::view)) .push( button("Add another download") .on_press(Message::Add) .padding(10), ) .spacing(20) .align_x(Right); center(downloads).padding(20).into() } } impl Default for Example { fn default() -> Self { Self::new() } } #[derive(Debug)] struct Download { id: usize, state: State, } #[derive(Debug, Clone)] pub enum Update { Downloading(download::Progress), Finished(Result<(), download::Error>), } #[derive(Debug)] enum State { Idle, Downloading { progress: f32, _task: task::Handle }, Finished, Errored, } impl Download { pub fn new(id: usize) -> Self { Download { id, state: State::Idle, } } pub fn start(&mut self) -> Task<Update> { match self.state { State::Idle | State::Finished | State::Errored => { let (task, handle) = Task::sip( download( "https://huggingface.co/\ mattshumer/Reflection-Llama-3.1-70B/\ resolve/main/model-00001-of-00162.safetensors", ), Update::Downloading, Update::Finished, ) .abortable(); self.state = State::Downloading { progress: 0.0, _task: handle.abort_on_drop(), }; task } State::Downloading { .. } => Task::none(), } } pub fn update(&mut self, update: Update) { if let State::Downloading { progress, .. } = &mut self.state { match update { Update::Downloading(new_progress) => { *progress = new_progress.percent; } Update::Finished(result) => { self.state = if result.is_ok() { State::Finished } else { State::Errored }; } } } } pub fn view(&self) -> Element<'_, Message> { let current_progress = match &self.state { State::Idle => 0.0, State::Downloading { progress, .. } => *progress, State::Finished => 100.0, State::Errored => 0.0, }; let progress_bar = progress_bar(0.0..=100.0, current_progress); let control: Element<_> = match &self.state { State::Idle => button("Start the download!") .on_press(Message::Download(self.id)) .into(), State::Finished => column!["Download finished!", button("Start again")] .spacing(10) .align_x(Center) .into(), State::Downloading { .. } => text!("Downloading... {current_progress:.2}%").into(), State::Errored => column![ "Something went wrong :(", button("Try again").on_press(Message::Download(self.id)), ] .spacing(10) .align_x(Center) .into(), }; Column::new() .spacing(10) .padding(10) .align_x(Center) .push(progress_bar) .push(control) .into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/arc/src/main.rs
examples/arc/src/main.rs
use std::{f32::consts::PI, time::Instant}; use iced::mouse; use iced::widget::canvas::{self, Cache, Canvas, Geometry, Path, Stroke, stroke}; use iced::window; use iced::{Element, Fill, Point, Rectangle, Renderer, Subscription, Theme}; pub fn main() -> iced::Result { iced::application(Arc::new, Arc::update, Arc::view) .subscription(Arc::subscription) .theme(Theme::Dark) .run() } struct Arc { start: Instant, cache: Cache, } #[derive(Debug, Clone, Copy)] enum Message { Tick, } impl Arc { fn new() -> Self { Arc { start: Instant::now(), cache: Cache::default(), } } fn update(&mut self, _: Message) { self.cache.clear(); } fn view(&self) -> Element<'_, Message> { Canvas::new(self).width(Fill).height(Fill).into() } fn subscription(&self) -> Subscription<Message> { window::frames().map(|_| Message::Tick) } } impl<Message> canvas::Program<Message> for Arc { type State = (); fn draw( &self, _state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { let geometry = self.cache.draw(renderer, bounds.size(), |frame| { let palette = theme.palette(); let center = frame.center(); let radius = frame.width().min(frame.height()) / 5.0; let start = Point::new(center.x, center.y - radius); let angle = (self.start.elapsed().as_millis() % 10_000) as f32 / 10_000.0 * 2.0 * PI; let end = Point::new( center.x + radius * angle.cos(), center.y + radius * angle.sin(), ); let circles = Path::new(|b| { b.circle(start, 10.0); b.move_to(end); b.circle(end, 10.0); }); frame.fill(&circles, palette.text); let path = Path::new(|b| { b.move_to(start); b.arc_to(center, end, 50.0); b.line_to(end); }); frame.stroke( &path, Stroke { style: stroke::Style::Solid(palette.text), width: 10.0, ..Stroke::default() }, ); }); vec![geometry] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/stopwatch/src/main.rs
examples/stopwatch/src/main.rs
use iced::keyboard; use iced::time::{self, Duration, Instant, milliseconds}; use iced::widget::{button, center, column, row, text}; use iced::{Center, Element, Subscription}; pub fn main() -> iced::Result { iced::application(Stopwatch::default, Stopwatch::update, Stopwatch::view) .subscription(Stopwatch::subscription) .run() } #[derive(Default)] struct Stopwatch { duration: Duration, state: State, } #[derive(Default)] enum State { #[default] Idle, Ticking { last_tick: Instant, }, } #[derive(Debug, Clone)] enum Message { Toggle, Reset, Tick(Instant), } impl Stopwatch { fn update(&mut self, message: Message) { match message { Message::Toggle => match self.state { State::Idle => { self.state = State::Ticking { last_tick: Instant::now(), }; } State::Ticking { .. } => { self.state = State::Idle; } }, Message::Tick(now) => { if let State::Ticking { last_tick } = &mut self.state { self.duration += now - *last_tick; *last_tick = now; } } Message::Reset => { self.duration = Duration::default(); } } } fn subscription(&self) -> Subscription<Message> { let tick = match self.state { State::Idle => Subscription::none(), State::Ticking { .. } => time::every(milliseconds(10)).map(Message::Tick), }; fn handle_hotkey(event: keyboard::Event) -> Option<Message> { use keyboard::key; let keyboard::Event::KeyPressed { modified_key, .. } = event else { return None; }; match modified_key.as_ref() { keyboard::Key::Named(key::Named::Space) => Some(Message::Toggle), keyboard::Key::Character("r") => Some(Message::Reset), _ => None, } } Subscription::batch(vec![tick, keyboard::listen().filter_map(handle_hotkey)]) } fn view(&self) -> Element<'_, Message> { const MINUTE: u64 = 60; const HOUR: u64 = 60 * MINUTE; let seconds = self.duration.as_secs(); let duration = text!( "{:0>2}:{:0>2}:{:0>2}.{:0>2}", seconds / HOUR, (seconds % HOUR) / MINUTE, seconds % MINUTE, self.duration.subsec_millis() / 10, ) .size(40); let button = |label| button(text(label).align_x(Center)).padding(10).width(80); let toggle_button = { let label = match self.state { State::Idle => "Start", State::Ticking { .. } => "Stop", }; button(label).on_press(Message::Toggle) }; let reset_button = button("Reset") .style(button::danger) .on_press(Message::Reset); let controls = row![toggle_button, reset_button].spacing(20); let content = column![duration, controls].align_x(Center).spacing(20); center(content).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/text/src/main.rs
examples/text/src/main.rs
use iced::event; use iced::widget::{center, column, pick_list, right, stack, text}; use iced::window; use iced::{Element, Event, Subscription, Task}; pub fn main() -> iced::Result { iced::application(Text::new, Text::update, Text::view) .subscription(Text::subscription) .run() } struct Text { scale_factor: f32, font: Font, } #[derive(Debug, Clone, Copy)] enum Message { WindowRescaled(f32), FontChanged(Font), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Font { SansSerif, Serif, Monospace, } impl Text { fn new() -> (Self, Task<Message>) { ( Self { font: Font::SansSerif, scale_factor: 1.0, }, window::latest() .and_then(window::scale_factor) .map(Message::WindowRescaled), ) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::WindowRescaled(scale_factor) => { self.scale_factor = scale_factor; Task::none() } Message::FontChanged(font) => { self.font = font; Task::none() } } } fn subscription(&self) -> Subscription<Message> { event::listen_with(|event, _, _| { let Event::Window(window::Event::Rescaled(scale_factor)) = event else { return None; }; Some(Message::WindowRescaled(scale_factor)) }) } fn view(&self) -> Element<'_, Message> { let sizes = 5..=32; let font_selector = pick_list( [Font::SansSerif, Font::Serif, Font::Monospace], Some(self.font), Message::FontChanged, ); stack![ center( column(sizes.map(|physical_size| { let size = physical_size as f32 / self.scale_factor; text!( "The quick brown fox jumps over the \ lazy dog ({physical_size}px)" ) .font(match self.font { Font::SansSerif => iced::Font::DEFAULT, Font::Serif => iced::Font { family: iced::font::Family::Serif, ..iced::Font::DEFAULT }, Font::Monospace => iced::Font::MONOSPACE, }) .size(size) .into() })) .spacing(10) ), right(font_selector).padding(10) ] .into() } } impl std::fmt::Display for Font { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Font::SansSerif => "Sans Serif", Font::Serif => "Serif", Font::Monospace => "Monospace", }) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/changelog/src/icon.rs
examples/changelog/src/icon.rs
use iced::widget::{text, Text}; use iced::Font; pub const FONT_BYTES: &[u8] = include_bytes!("../fonts/changelog-icons.ttf"); const FONT: Font = Font::with_name("changelog-icons"); pub fn copy() -> Text<'static> { text('\u{e800}').font(FONT) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/changelog/src/changelog.rs
examples/changelog/src/changelog.rs
use jiff::Timestamp; use serde::Deserialize; use tokio::fs; use tokio::process; use std::collections::{BTreeMap, BTreeSet}; use std::env; use std::fmt; use std::io; use std::sync::Arc; #[derive(Debug, Clone)] pub struct Changelog { ids: Vec<u64>, added: Vec<String>, changed: Vec<String>, fixed: Vec<String>, removed: Vec<String>, authors: Vec<String>, contributions: BTreeMap<String, usize>, } impl Changelog { pub fn new() -> Self { Self { ids: Vec::new(), added: Vec::new(), changed: Vec::new(), fixed: Vec::new(), removed: Vec::new(), authors: Vec::new(), contributions: BTreeMap::new(), } } pub async fn list() -> Result<(Self, Vec<Contribution>), Error> { let mut changelog = Self::new(); { let markdown = fs::read_to_string("CHANGELOG.md").await?; if let Some(unreleased) = markdown.split("\n## ").nth(1) { let sections = unreleased.split("\n\n"); for section in sections { if section.starts_with("Many thanks to...") { for author in section.lines().skip(1) { let author = author.trim_start_matches("- @"); if author.is_empty() { continue; } changelog.authors.push(author.to_owned()); } continue; } let Some((_, rest)) = section.split_once("### ") else { continue; }; let Some((name, rest)) = rest.split_once("\n") else { continue; }; let category = match name { "Added" => Category::Added, "Fixed" => Category::Fixed, "Changed" => Category::Changed, "Removed" => Category::Removed, _ => continue, }; for entry in rest.lines() { let Some((_, id)) = entry.split_once("[#") else { continue; }; let Some((id, _)) = id.split_once(']') else { continue; }; let Ok(id): Result<u64, _> = id.parse() else { continue; }; changelog.ids.push(id); let target = match category { Category::Added => &mut changelog.added, Category::Changed => &mut changelog.changed, Category::Fixed => &mut changelog.fixed, Category::Removed => &mut changelog.removed, }; target.push(entry.to_owned()); } } } } let mut candidates = Contribution::list().await?; for candidate in &candidates { *changelog .contributions .entry(candidate.author.clone()) .or_default() += 1; } for author in &changelog.authors { if !changelog.contributions.contains_key(author) { changelog.contributions.insert(author.clone(), 1); } } for reviewed_entry in changelog.entries() { candidates.retain(|candidate| candidate.id != reviewed_entry); } Ok((changelog, candidates)) } pub async fn save(self) -> Result<(), Error> { let markdown = fs::read_to_string("CHANGELOG.md").await?; let Some((header, rest)) = markdown.split_once("\n## ") else { return Err(Error::InvalidFormat); }; let Some((_unreleased, rest)) = rest.split_once("\n## ") else { return Err(Error::InvalidFormat); }; let unreleased = format!("\n## [Unreleased]\n{self}"); let rest = format!("\n## {rest}"); let changelog = [header, &unreleased, &rest].concat(); fs::write("CHANGELOG.md", changelog).await?; Ok(()) } pub fn len(&self) -> usize { self.ids.len() } pub fn entries(&self) -> impl Iterator<Item = u64> + '_ { self.ids.iter().copied() } pub fn push(&mut self, entry: Entry) { self.ids.push(entry.id); let item = format!( "- {title}. [#{id}](https://github.com/iced-rs/iced/pull/{id})", title = entry.title, id = entry.id ); let target = match entry.category { Category::Added => &mut self.added, Category::Changed => &mut self.changed, Category::Fixed => &mut self.fixed, Category::Removed => &mut self.removed, }; target.push(item); let _ = self.contributions.entry(entry.author.clone()).or_default(); if entry.author != "hecrj" && !self.authors.contains(&entry.author) { self.authors.push(entry.author); } self.authors.sort_by(|a, b| { self.contributions .get(a) .copied() .unwrap_or_default() .cmp(&self.contributions.get(b).copied().unwrap_or_default()) .reverse() .then(a.to_lowercase().cmp(&b.to_lowercase())) }); } } impl fmt::Display for Changelog { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn section(category: Category, entries: &[String]) -> String { if entries.is_empty() { return String::new(); } format!("### {category}\n{list}\n", list = entries.join("\n")) } fn thank_you<'a>(authors: impl IntoIterator<Item = &'a str>) -> String { let mut list = String::new(); for author in authors { list.push_str(&format!("- @{author}\n")); } format!("Many thanks to...\n{list}") } let changelog = [ section(Category::Added, &self.added), section(Category::Changed, &self.changed), section(Category::Fixed, &self.fixed), section(Category::Removed, &self.removed), thank_you(self.authors.iter().map(String::as_str)), ] .into_iter() .filter(|section| !section.is_empty()) .collect::<Vec<String>>() .join("\n"); f.write_str(&changelog) } } #[derive(Debug, Clone)] pub struct Entry { pub id: u64, pub title: String, pub category: Category, pub author: String, } impl Entry { pub fn new(title: &str, category: Category, pull_request: &PullRequest) -> Option<Self> { let title = title.strip_suffix(".").unwrap_or(title); if title.is_empty() { return None; }; Some(Self { id: pull_request.id, title: title.to_owned(), category, author: pull_request.author.clone(), }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Category { Added, Changed, Fixed, Removed, } impl Category { pub const ALL: &'static [Self] = &[Self::Added, Self::Changed, Self::Fixed, Self::Removed]; pub fn guess(label: &str) -> Option<Self> { Some(match label { "feature" | "addition" => Self::Added, "change" => Self::Changed, "bug" | "fix" => Self::Fixed, _ => None?, }) } } impl fmt::Display for Category { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Category::Added => "Added", Category::Changed => "Changed", Category::Fixed => "Fixed", Category::Removed => "Removed", }) } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Contribution { pub id: u64, pub author: String, } impl Contribution { pub async fn list() -> Result<Vec<Contribution>, Error> { let output = process::Command::new("git") .args([ "log", "--oneline", "--grep", "#[0-9]*", "origin/latest..HEAD", ]) .output() .await?; let log = String::from_utf8_lossy(&output.stdout); let mut contributions: Vec<_> = log .lines() .filter(|title| !title.is_empty()) .filter_map(|title| { let (_, pull_request) = title.split_once('#')?; let (pull_request, _) = pull_request.split_once([')', ' '])?; let (author, _) = title.split_once('/').unwrap_or_default(); let (_, author) = author.rsplit_once(' ').unwrap_or_default(); Some(Contribution { id: pull_request.parse().ok()?, author: author.to_owned(), }) }) .collect(); let mut unique = BTreeSet::from_iter(contributions.clone()); contributions.retain_mut(|contribution| unique.remove(contribution)); Ok(contributions) } } #[derive(Debug, Clone)] pub struct PullRequest { pub id: u64, pub title: String, pub description: Option<String>, pub labels: Vec<String>, pub author: String, pub created_at: Timestamp, } impl PullRequest { pub async fn fetch(contribution: Contribution) -> Result<Self, Error> { let request = reqwest::Client::new() .request( reqwest::Method::GET, format!( "https://api.github.com/repos/iced-rs/iced/pulls/{}", contribution.id ), ) .header("User-Agent", "iced changelog generator") .header( "Authorization", format!( "Bearer {}", env::var("GITHUB_TOKEN").map_err(|_| Error::GitHubTokenNotFound)? ), ); #[derive(Deserialize)] struct Schema { title: String, body: Option<String>, user: User, labels: Vec<Label>, created_at: String, } #[derive(Deserialize)] struct User { login: String, } #[derive(Deserialize)] struct Label { name: String, } let schema: Schema = request.send().await?.json().await?; Ok(Self { id: contribution.id, title: schema.title, description: schema.body.map(|body| body.replace("\r", "")), labels: schema.labels.into_iter().map(|label| label.name).collect(), author: schema.user.login, created_at: schema.created_at.parse()?, }) } } #[derive(Debug, Clone, thiserror::Error)] pub enum Error { #[error("io operation failed: {0}")] IOFailed(Arc<io::Error>), #[error("http request failed: {0}")] RequestFailed(Arc<reqwest::Error>), #[error("no GITHUB_TOKEN variable was set")] GitHubTokenNotFound, #[error("the changelog format is not valid")] InvalidFormat, #[error("date could not be parsed: {0}")] InvalidDate(#[from] jiff::Error), } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Error::IOFailed(Arc::new(error)) } } impl From<reqwest::Error> for Error { fn from(error: reqwest::Error) -> Self { Error::RequestFailed(Arc::new(error)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/changelog/src/main.rs
examples/changelog/src/main.rs
mod changelog; use crate::changelog::Changelog; use iced::font; use iced::widget::{ button, center, column, container, markdown, pick_list, progress_bar, rich_text, row, scrollable, span, stack, text, text_input, }; use iced::{Center, Element, Fill, FillPortion, Font, Task, Theme}; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(Generator::new, Generator::update, Generator::view) .theme(Generator::theme) .run() } enum Generator { Loading, Reviewing { changelog: Changelog, pending: Vec<changelog::Contribution>, state: State, preview: Vec<markdown::Item>, timezone: jiff::tz::TimeZone, }, Done, } enum State { Loading(changelog::Contribution), Loaded { pull_request: changelog::PullRequest, description: Vec<markdown::Item>, title: String, category: changelog::Category, }, } #[derive(Debug, Clone)] enum Message { ChangelogListed(Result<(Changelog, Vec<changelog::Contribution>), changelog::Error>), PullRequestFetched(Result<changelog::PullRequest, changelog::Error>), LinkClicked(markdown::Uri), TitleChanged(String), CategorySelected(changelog::Category), Next, OpenPullRequest(u64), ChangelogSaved(Result<(), changelog::Error>), Quit, } impl Generator { fn new() -> (Self, Task<Message>) { ( Self::Loading, Task::perform(Changelog::list(), Message::ChangelogListed), ) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::ChangelogListed(Ok((changelog, mut pending))) => { if let Some(contribution) = pending.pop() { let preview = markdown::parse(&changelog.to_string()).collect(); *self = Self::Reviewing { changelog, pending, state: State::Loading(contribution.clone()), preview, timezone: jiff::tz::TimeZone::system(), }; Task::perform( changelog::PullRequest::fetch(contribution), Message::PullRequestFetched, ) } else { *self = Self::Done; Task::none() } } Message::PullRequestFetched(Ok(pull_request)) => { let Self::Reviewing { state, .. } = self else { return Task::none(); }; let description = markdown::parse( pull_request .description .as_deref() .unwrap_or("*No description provided*"), ) .collect(); *state = State::Loaded { title: pull_request.title.clone(), category: pull_request .labels .iter() .map(String::as_str) .filter_map(changelog::Category::guess) .next() .unwrap_or(changelog::Category::Added), pull_request, description, }; Task::none() } Message::LinkClicked(url) => { let _ = webbrowser::open(url.as_str()); Task::none() } Message::TitleChanged(new_title) => { let Self::Reviewing { state, .. } = self else { return Task::none(); }; let State::Loaded { title, .. } = state else { return Task::none(); }; *title = new_title; Task::none() } Message::CategorySelected(new_category) => { let Self::Reviewing { state, .. } = self else { return Task::none(); }; let State::Loaded { category, .. } = state else { return Task::none(); }; *category = new_category; Task::none() } Message::Next => { let Self::Reviewing { changelog, pending, state, preview, .. } = self else { return Task::none(); }; let State::Loaded { title, category, pull_request, .. } = state else { return Task::none(); }; if let Some(entry) = changelog::Entry::new(title, *category, pull_request) { changelog.push(entry); let save = Task::perform(changelog.clone().save(), Message::ChangelogSaved); *preview = markdown::parse(&changelog.to_string()).collect(); if let Some(contribution) = pending.pop() { *state = State::Loading(contribution.clone()); Task::batch([ save, Task::perform( changelog::PullRequest::fetch(contribution), Message::PullRequestFetched, ), ]) } else { *self = Self::Done; save } } else { Task::none() } } Message::OpenPullRequest(id) => { let _ = webbrowser::open(&format!("https://github.com/iced-rs/iced/pull/{id}")); Task::none() } Message::ChangelogSaved(Ok(())) => Task::none(), Message::ChangelogListed(Err(error)) | Message::PullRequestFetched(Err(error)) | Message::ChangelogSaved(Err(error)) => { log::error!("{error}"); Task::none() } Message::Quit => iced::exit(), } } fn view(&self) -> Element<'_, Message> { match self { Self::Loading => center("Loading...").into(), Self::Done => center( column![ text("Changelog is up-to-date! 🎉").shaping(text::Shaping::Advanced), button("Quit").on_press(Message::Quit), ] .spacing(10) .align_x(Center), ) .into(), Self::Reviewing { changelog, pending, state, preview, timezone, } => { let progress = { let total = pending.len() + changelog.len(); let percent = 100.0 * changelog.len() as f32 / total as f32; let bar = progress_bar(0.0..=100.0, percent).style(progress_bar::secondary); let label = text!( "{amount_reviewed} / {total} ({percent:.0}%)", amount_reviewed = changelog.len() ) .font(Font::MONOSPACE) .size(12); stack![bar, center(label)] }; let form: Element<_> = match state { State::Loading(contribution) => text!("Loading #{}...", contribution.id).into(), State::Loaded { pull_request, description, title, category, } => { let details = { let title = rich_text![ span(&pull_request.title).size(24).link(pull_request.id), "\n", span(format!(" by {}", pull_request.author)).font(Font { style: font::Style::Italic, ..Font::default() }), ] .on_link_click(Message::OpenPullRequest) .font(Font::MONOSPACE); let description = markdown(description, self.theme()).map(Message::LinkClicked); let labels = row(pull_request.labels.iter().map(|label| { container(text(label).size(10).font(Font::MONOSPACE)) .padding(5) .style(container::rounded_box) .into() })) .spacing(10) .wrap(); let created_at = text( timezone .to_datetime(pull_request.created_at) .strftime("%B %d, %Y at %I:%M%p") .to_string(), ) .size(12); column![ title, row![labels, created_at].align_y(Center).spacing(10), scrollable(description).spacing(10).width(Fill).height(Fill) ] .spacing(10) }; let title = text_input("Type a changelog entry title...", title) .on_input(Message::TitleChanged) .on_submit(Message::Next); let category = pick_list( changelog::Category::ALL, Some(category), Message::CategorySelected, ); let next = button("Next →") .on_press(Message::Next) .style(button::success); column![details, row![title, category, next].spacing(10)] .spacing(10) .into() } }; let preview = if preview.is_empty() { center( container(text("The changelog is empty... so far!").size(12)) .padding(10) .style(container::rounded_box), ) } else { container( scrollable( markdown( preview, markdown::Settings::with_text_size(12, self.theme()), ) .map(Message::LinkClicked), ) .width(Fill) .spacing(10), ) .width(Fill) .padding(10) .style(container::rounded_box) }; let review = column![container(form).height(Fill), progress] .spacing(10) .width(FillPortion(2)); row![review, preview].spacing(10).padding(10).into() } } } fn theme(&self) -> Theme { Theme::CatppuccinMocha } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/bezier_tool/src/main.rs
examples/bezier_tool/src/main.rs
//! This example showcases an interactive `Canvas` for drawing Bézier curves. use iced::widget::{button, container, hover, right, space}; use iced::{Element, Theme}; pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view) .theme(Theme::CatppuccinMocha) .run() } #[derive(Default)] struct Example { bezier: bezier::State, curves: Vec<bezier::Curve>, } #[derive(Debug, Clone, Copy)] enum Message { AddCurve(bezier::Curve), Clear, } impl Example { fn update(&mut self, message: Message) { match message { Message::AddCurve(curve) => { self.curves.push(curve); self.bezier.request_redraw(); } Message::Clear => { self.bezier = bezier::State::default(); self.curves.clear(); } } } fn view(&self) -> Element<'_, Message> { container(hover( self.bezier.view(&self.curves).map(Message::AddCurve), if self.curves.is_empty() { container(space::horizontal()) } else { right( button("Clear") .style(button::danger) .on_press(Message::Clear), ) .padding(10) }, )) .padding(20) .into() } } mod bezier { use iced::mouse; use iced::widget::canvas::{self, Canvas, Event, Frame, Geometry, Path, Stroke}; use iced::{Element, Fill, Point, Rectangle, Renderer, Theme}; #[derive(Default)] pub struct State { cache: canvas::Cache, } impl State { pub fn view<'a>(&'a self, curves: &'a [Curve]) -> Element<'a, Curve> { Canvas::new(Bezier { state: self, curves, }) .width(Fill) .height(Fill) .into() } pub fn request_redraw(&mut self) { self.cache.clear(); } } struct Bezier<'a> { state: &'a State, curves: &'a [Curve], } impl canvas::Program<Curve> for Bezier<'_> { type State = Option<Pending>; fn update( &self, state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<canvas::Action<Curve>> { let cursor_position = cursor.position_in(bounds)?; match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => Some( match *state { None => { *state = Some(Pending::One { from: cursor_position, }); canvas::Action::request_redraw() } Some(Pending::One { from }) => { *state = Some(Pending::Two { from, to: cursor_position, }); canvas::Action::request_redraw() } Some(Pending::Two { from, to }) => { *state = None; canvas::Action::publish(Curve { from, to, control: cursor_position, }) } } .and_capture(), ), Event::Mouse(mouse::Event::CursorMoved { .. }) if state.is_some() => { Some(canvas::Action::request_redraw()) } _ => None, } } fn draw( &self, state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec<Geometry> { let content = self.state.cache.draw(renderer, bounds.size(), |frame| { Curve::draw_all(self.curves, frame, theme); frame.stroke( &Path::rectangle(Point::ORIGIN, frame.size()), Stroke::default() .with_width(2.0) .with_color(theme.palette().text), ); }); if let Some(pending) = state { vec![content, pending.draw(renderer, theme, bounds, cursor)] } else { vec![content] } } fn mouse_interaction( &self, _state: &Self::State, bounds: Rectangle, cursor: mouse::Cursor, ) -> mouse::Interaction { if cursor.is_over(bounds) { mouse::Interaction::Crosshair } else { mouse::Interaction::default() } } } #[derive(Debug, Clone, Copy)] pub struct Curve { from: Point, to: Point, control: Point, } impl Curve { fn draw_all(curves: &[Curve], frame: &mut Frame, theme: &Theme) { let curves = Path::new(|p| { for curve in curves { p.move_to(curve.from); p.quadratic_curve_to(curve.control, curve.to); } }); frame.stroke( &curves, Stroke::default() .with_width(2.0) .with_color(theme.palette().text), ); } } #[derive(Debug, Clone, Copy)] enum Pending { One { from: Point }, Two { from: Point, to: Point }, } impl Pending { fn draw( &self, renderer: &Renderer, theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Geometry { let mut frame = Frame::new(renderer, bounds.size()); if let Some(cursor_position) = cursor.position_in(bounds) { match *self { Pending::One { from } => { let line = Path::line(from, cursor_position); frame.stroke( &line, Stroke::default() .with_width(2.0) .with_color(theme.palette().text), ); } Pending::Two { from, to } => { let curve = Curve { from, to, control: cursor_position, }; Curve::draw_all(&[curve], &mut frame, theme); } }; } frame.into_geometry() } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/loading_spinners/src/easing.rs
examples/loading_spinners/src/easing.rs
use iced::Point; use lyon_algorithms::measure::PathMeasurements; use lyon_algorithms::path::{Path, builder::NoAttributes, path::BuilderImpl}; use std::sync::LazyLock; pub static EMPHASIZED: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.05, 0.0], [0.133333, 0.06], [0.166666, 0.4]) .cubic_bezier_to([0.208333, 0.82], [0.25, 1.0], [1.0, 1.0]) .build() }); pub static EMPHASIZED_DECELERATE: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.05, 0.7], [0.1, 1.0], [1.0, 1.0]) .build() }); pub static EMPHASIZED_ACCELERATE: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.3, 0.0], [0.8, 0.15], [1.0, 1.0]) .build() }); pub static STANDARD: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.2, 0.0], [0.0, 1.0], [1.0, 1.0]) .build() }); pub static STANDARD_DECELERATE: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.0, 0.0], [0.0, 1.0], [1.0, 1.0]) .build() }); pub static STANDARD_ACCELERATE: LazyLock<Easing> = LazyLock::new(|| { Easing::builder() .cubic_bezier_to([0.3, 0.0], [1.0, 1.0], [1.0, 1.0]) .build() }); pub struct Easing { path: Path, measurements: PathMeasurements, } impl Easing { pub fn builder() -> Builder { Builder::new() } pub fn y_at_x(&self, x: f32) -> f32 { let mut sampler = self .measurements .create_sampler(&self.path, lyon_algorithms::measure::SampleType::Normalized); let sample = sampler.sample(x); sample.position().y } } pub struct Builder(NoAttributes<BuilderImpl>); impl Builder { pub fn new() -> Self { let mut builder = Path::builder(); builder.begin(lyon_algorithms::geom::point(0.0, 0.0)); Self(builder) } /// Adds a line segment. Points must be between 0,0 and 1,1 pub fn line_to(mut self, to: impl Into<Point>) -> Self { self.0.line_to(Self::point(to)); self } /// Adds a quadratic bézier curve. Points must be between 0,0 and 1,1 pub fn quadratic_bezier_to(mut self, ctrl: impl Into<Point>, to: impl Into<Point>) -> Self { self.0 .quadratic_bezier_to(Self::point(ctrl), Self::point(to)); self } /// Adds a cubic bézier curve. Points must be between 0,0 and 1,1 pub fn cubic_bezier_to( mut self, ctrl1: impl Into<Point>, ctrl2: impl Into<Point>, to: impl Into<Point>, ) -> Self { self.0 .cubic_bezier_to(Self::point(ctrl1), Self::point(ctrl2), Self::point(to)); self } pub fn build(mut self) -> Easing { self.0.line_to(lyon_algorithms::geom::point(1.0, 1.0)); self.0.end(false); let path = self.0.build(); let measurements = PathMeasurements::from_path(&path, 0.0); Easing { path, measurements } } fn point(p: impl Into<Point>) -> lyon_algorithms::geom::Point<f32> { let p: Point = p.into(); lyon_algorithms::geom::point(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0)) } } impl Default for Builder { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/loading_spinners/src/circular.rs
examples/loading_spinners/src/circular.rs
//! Show a circular progress indicator. use iced::advanced::layout; use iced::advanced::renderer; use iced::advanced::widget::tree::{self, Tree}; use iced::advanced::{self, Clipboard, Layout, Shell, Widget}; use iced::mouse; use iced::time::Instant; use iced::widget::canvas; use iced::window; use iced::{Background, Color, Element, Event, Length, Radians, Rectangle, Renderer, Size, Vector}; use super::easing::{self, Easing}; use std::f32::consts::PI; use std::time::Duration; const MIN_ANGLE: Radians = Radians(PI / 8.0); const WRAP_ANGLE: Radians = Radians(2.0 * PI - PI / 4.0); const BASE_ROTATION_SPEED: u32 = u32::MAX / 80; pub struct Circular<'a, Theme> where Theme: StyleSheet, { size: f32, bar_height: f32, style: <Theme as StyleSheet>::Style, easing: &'a Easing, cycle_duration: Duration, rotation_duration: Duration, } impl<'a, Theme> Circular<'a, Theme> where Theme: StyleSheet, { /// Creates a new [`Circular`] with the given content. pub fn new() -> Self { Circular { size: 40.0, bar_height: 4.0, style: <Theme as StyleSheet>::Style::default(), easing: &easing::STANDARD, cycle_duration: Duration::from_millis(600), rotation_duration: Duration::from_secs(2), } } /// Sets the size of the [`Circular`]. pub fn size(mut self, size: f32) -> Self { self.size = size; self } /// Sets the bar height of the [`Circular`]. pub fn bar_height(mut self, bar_height: f32) -> Self { self.bar_height = bar_height; self } /// Sets the style variant of this [`Circular`]. pub fn style(mut self, style: <Theme as StyleSheet>::Style) -> Self { self.style = style; self } /// Sets the easing of this [`Circular`]. pub fn easing(mut self, easing: &'a Easing) -> Self { self.easing = easing; self } /// Sets the cycle duration of this [`Circular`]. pub fn cycle_duration(mut self, duration: Duration) -> Self { self.cycle_duration = duration / 2; self } /// Sets the base rotation duration of this [`Circular`]. This is the duration that a full /// rotation would take if the cycle rotation were set to 0.0 (no expanding or contracting) pub fn rotation_duration(mut self, duration: Duration) -> Self { self.rotation_duration = duration; self } } impl<Theme> Default for Circular<'_, Theme> where Theme: StyleSheet, { fn default() -> Self { Self::new() } } #[derive(Clone, Copy)] enum Animation { Expanding { start: Instant, progress: f32, rotation: u32, last: Instant, }, Contracting { start: Instant, progress: f32, rotation: u32, last: Instant, }, } impl Default for Animation { fn default() -> Self { Self::Expanding { start: Instant::now(), progress: 0.0, rotation: 0, last: Instant::now(), } } } impl Animation { fn next(&self, additional_rotation: u32, now: Instant) -> Self { match self { Self::Expanding { rotation, .. } => Self::Contracting { start: now, progress: 0.0, rotation: rotation.wrapping_add(additional_rotation), last: now, }, Self::Contracting { rotation, .. } => Self::Expanding { start: now, progress: 0.0, rotation: rotation.wrapping_add(BASE_ROTATION_SPEED.wrapping_add( (f64::from(WRAP_ANGLE / (2.0 * Radians::PI)) * u32::MAX as f64) as u32, )), last: now, }, } } fn start(&self) -> Instant { match self { Self::Expanding { start, .. } | Self::Contracting { start, .. } => *start, } } fn last(&self) -> Instant { match self { Self::Expanding { last, .. } | Self::Contracting { last, .. } => *last, } } fn timed_transition( &self, cycle_duration: Duration, rotation_duration: Duration, now: Instant, ) -> Self { let elapsed = now.duration_since(self.start()); let additional_rotation = ((now - self.last()).as_secs_f32() / rotation_duration.as_secs_f32() * (u32::MAX) as f32) as u32; match elapsed { elapsed if elapsed > cycle_duration => self.next(additional_rotation, now), _ => self.with_elapsed(cycle_duration, additional_rotation, elapsed, now), } } fn with_elapsed( &self, cycle_duration: Duration, additional_rotation: u32, elapsed: Duration, now: Instant, ) -> Self { let progress = elapsed.as_secs_f32() / cycle_duration.as_secs_f32(); match self { Self::Expanding { start, rotation, .. } => Self::Expanding { start: *start, progress, rotation: rotation.wrapping_add(additional_rotation), last: now, }, Self::Contracting { start, rotation, .. } => Self::Contracting { start: *start, progress, rotation: rotation.wrapping_add(additional_rotation), last: now, }, } } fn rotation(&self) -> f32 { match self { Self::Expanding { rotation, .. } | Self::Contracting { rotation, .. } => { *rotation as f32 / u32::MAX as f32 } } } } #[derive(Default)] struct State { animation: Animation, cache: canvas::Cache, } impl<'a, Message, Theme> Widget<Message, Theme, Renderer> for Circular<'a, Theme> where Message: 'a + Clone, Theme: StyleSheet, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::default()) } fn size(&self) -> Size<Length> { Size { width: Length::Fixed(self.size), height: Length::Fixed(self.size), } } fn layout( &mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { layout::atomic(limits, self.size, self.size) } 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, ) { let state = tree.state.downcast_mut::<State>(); if let Event::Window(window::Event::RedrawRequested(now)) = event { state.animation = state .animation .timed_transition(self.cycle_duration, self.rotation_duration, *now); state.cache.clear(); shell.request_redraw(); } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { use advanced::Renderer as _; let state = tree.state.downcast_ref::<State>(); let bounds = layout.bounds(); let custom_style = <Theme as StyleSheet>::appearance(theme, &self.style); let geometry = state.cache.draw(renderer, bounds.size(), |frame| { let track_radius = frame.width() / 2.0 - self.bar_height; let track_path = canvas::Path::circle(frame.center(), track_radius); frame.stroke( &track_path, canvas::Stroke::default() .with_color(custom_style.track_color) .with_width(self.bar_height), ); let mut builder = canvas::path::Builder::new(); let start = Radians(state.animation.rotation() * 2.0 * PI); match state.animation { Animation::Expanding { progress, .. } => { builder.arc(canvas::path::Arc { center: frame.center(), radius: track_radius, start_angle: start, end_angle: start + MIN_ANGLE + WRAP_ANGLE * (self.easing.y_at_x(progress)), }); } Animation::Contracting { progress, .. } => { builder.arc(canvas::path::Arc { center: frame.center(), radius: track_radius, start_angle: start + WRAP_ANGLE * (self.easing.y_at_x(progress)), end_angle: start + MIN_ANGLE + WRAP_ANGLE, }); } } let bar_path = builder.build(); frame.stroke( &bar_path, canvas::Stroke::default() .with_color(custom_style.bar_color) .with_width(self.bar_height), ); }); renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { use iced::advanced::graphics::geometry::Renderer as _; renderer.draw_geometry(geometry); }); } } impl<'a, Message, Theme> From<Circular<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Theme: StyleSheet + 'a, { fn from(circular: Circular<'a, Theme>) -> Self { Self::new(circular) } } #[derive(Debug, Clone, Copy)] pub struct Appearance { /// The [`Background`] of the progress indicator. pub background: Option<Background>, /// The track [`Color`] of the progress indicator. pub track_color: Color, /// The bar [`Color`] of the progress indicator. pub bar_color: Color, } impl std::default::Default for Appearance { fn default() -> Self { Self { background: None, track_color: Color::TRANSPARENT, bar_color: Color::BLACK, } } } /// A set of rules that dictate the style of an indicator. pub trait StyleSheet { /// The supported style of the [`StyleSheet`]. type Style: Default; /// Produces the active [`Appearance`] of a indicator. fn appearance(&self, style: &Self::Style) -> Appearance; } impl StyleSheet for iced::Theme { type Style = (); fn appearance(&self, _style: &Self::Style) -> Appearance { let palette = self.extended_palette(); Appearance { background: None, track_color: palette.background.weak.color, bar_color: palette.primary.base.color, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/loading_spinners/src/linear.rs
examples/loading_spinners/src/linear.rs
//! Show a linear progress indicator. use iced::advanced::layout; use iced::advanced::renderer::{self, Quad}; use iced::advanced::widget::tree::{self, Tree}; use iced::advanced::{self, Clipboard, Layout, Shell, Widget}; use iced::mouse; use iced::time::Instant; use iced::window; use iced::{Background, Color, Element, Event, Length, Rectangle, Size}; use super::easing::{self, Easing}; use std::time::Duration; pub struct Linear<'a, Theme> where Theme: StyleSheet, { width: Length, height: Length, style: Theme::Style, easing: &'a Easing, cycle_duration: Duration, } impl<'a, Theme> Linear<'a, Theme> where Theme: StyleSheet, { /// Creates a new [`Linear`] with the given content. pub fn new() -> Self { Linear { width: Length::Fixed(100.0), height: Length::Fixed(4.0), style: Theme::Style::default(), easing: &easing::STANDARD, cycle_duration: Duration::from_millis(600), } } /// Sets the width of the [`Linear`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Linear`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the style variant of this [`Linear`]. pub fn style(mut self, style: impl Into<Theme::Style>) -> Self { self.style = style.into(); self } /// Sets the motion easing of this [`Linear`]. pub fn easing(mut self, easing: &'a Easing) -> Self { self.easing = easing; self } /// Sets the cycle duration of this [`Linear`]. pub fn cycle_duration(mut self, duration: Duration) -> Self { self.cycle_duration = duration / 2; self } } impl<Theme> Default for Linear<'_, Theme> where Theme: StyleSheet, { fn default() -> Self { Self::new() } } #[derive(Clone, Copy)] enum State { Expanding { start: Instant, progress: f32 }, Contracting { start: Instant, progress: f32 }, } impl Default for State { fn default() -> Self { Self::Expanding { start: Instant::now(), progress: 0.0, } } } impl State { fn next(&self, now: Instant) -> Self { match self { Self::Expanding { .. } => Self::Contracting { start: now, progress: 0.0, }, Self::Contracting { .. } => Self::Expanding { start: now, progress: 0.0, }, } } fn start(&self) -> Instant { match self { Self::Expanding { start, .. } | Self::Contracting { start, .. } => *start, } } fn timed_transition(&self, cycle_duration: Duration, now: Instant) -> Self { let elapsed = now.duration_since(self.start()); match elapsed { elapsed if elapsed > cycle_duration => self.next(now), _ => self.with_elapsed(cycle_duration, elapsed), } } fn with_elapsed(&self, cycle_duration: Duration, elapsed: Duration) -> Self { let progress = elapsed.as_secs_f32() / cycle_duration.as_secs_f32(); match self { Self::Expanding { start, .. } => Self::Expanding { start: *start, progress, }, Self::Contracting { start, .. } => Self::Contracting { start: *start, progress, }, } } } impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Linear<'a, Theme> where Message: Clone + 'a, Theme: StyleSheet + 'a, Renderer: advanced::Renderer + 'a, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::default()) } fn size(&self) -> Size<Length> { Size { width: self.width, height: self.height, } } fn layout( &mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { layout::atomic(limits, self.width, self.height) } 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, ) { let state = tree.state.downcast_mut::<State>(); if let Event::Window(window::Event::RedrawRequested(now)) = event { *state = state.timed_transition(self.cycle_duration, *now); shell.request_redraw(); } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { let bounds = layout.bounds(); let custom_style = theme.appearance(&self.style); let state = tree.state.downcast_ref::<State>(); renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height, }, ..renderer::Quad::default() }, Background::Color(custom_style.track_color), ); match state { State::Expanding { progress, .. } => renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x, y: bounds.y, width: self.easing.y_at_x(*progress) * bounds.width, height: bounds.height, }, ..renderer::Quad::default() }, Background::Color(custom_style.bar_color), ), State::Contracting { progress, .. } => renderer.fill_quad( Quad { bounds: Rectangle { x: bounds.x + self.easing.y_at_x(*progress) * bounds.width, y: bounds.y, width: (1.0 - self.easing.y_at_x(*progress)) * bounds.width, height: bounds.height, }, ..renderer::Quad::default() }, Background::Color(custom_style.bar_color), ), } } } impl<'a, Message, Theme, Renderer> From<Linear<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Theme: StyleSheet + 'a, Renderer: iced::advanced::Renderer + 'a, { fn from(linear: Linear<'a, Theme>) -> Self { Self::new(linear) } } #[derive(Debug, Clone, Copy)] pub struct Appearance { /// The track [`Color`] of the progress indicator. pub track_color: Color, /// The bar [`Color`] of the progress indicator. pub bar_color: Color, } impl Default for Appearance { fn default() -> Self { Self { track_color: Color::TRANSPARENT, bar_color: Color::BLACK, } } } /// A set of rules that dictate the style of an indicator. pub trait StyleSheet { /// The supported style of the [`StyleSheet`]. type Style: Default; /// Produces the active [`Appearance`] of a indicator. fn appearance(&self, style: &Self::Style) -> Appearance; } impl StyleSheet for iced::Theme { type Style = (); fn appearance(&self, _style: &Self::Style) -> Appearance { let palette = self.extended_palette(); Appearance { track_color: palette.background.weak.color, bar_color: palette.primary.base.color, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/loading_spinners/src/main.rs
examples/loading_spinners/src/main.rs
use iced::widget::{center, column, row, slider, text}; use iced::{Center, Element}; use std::time::Duration; mod circular; mod easing; mod linear; use circular::Circular; use linear::Linear; pub fn main() -> iced::Result { iced::application( LoadingSpinners::default, LoadingSpinners::update, LoadingSpinners::view, ) .run() } struct LoadingSpinners { cycle_duration: f32, } #[derive(Debug, Clone, Copy)] enum Message { CycleDurationChanged(f32), } impl LoadingSpinners { fn update(&mut self, message: Message) { match message { Message::CycleDurationChanged(duration) => { self.cycle_duration = duration; } } } fn view(&self) -> Element<'_, Message> { let column = [ &easing::EMPHASIZED, &easing::EMPHASIZED_DECELERATE, &easing::EMPHASIZED_ACCELERATE, &easing::STANDARD, &easing::STANDARD_DECELERATE, &easing::STANDARD_ACCELERATE, ] .iter() .zip([ "Emphasized:", "Emphasized Decelerate:", "Emphasized Accelerate:", "Standard:", "Standard Decelerate:", "Standard Accelerate:", ]) .fold(column![], |column, (easing, label)| { column.push( row![ text(label).width(250), Linear::new() .easing(easing) .cycle_duration(Duration::from_secs_f32(self.cycle_duration)), Circular::new() .easing(easing) .cycle_duration(Duration::from_secs_f32(self.cycle_duration)) ] .align_y(Center) .spacing(20.0), ) }) .spacing(20); center( column.push( row![ text("Cycle duration:"), slider(1.0..=1000.0, self.cycle_duration * 100.0, |x| { Message::CycleDurationChanged(x / 100.0) }) .width(200.0), text!("{:.2}s", self.cycle_duration), ] .align_y(Center) .spacing(20.0), ), ) .into() } } impl Default for LoadingSpinners { fn default() -> Self { Self { cycle_duration: 2.0, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/game_of_life/src/preset.rs
examples/game_of_life/src/preset.rs
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Preset { Custom, #[default] Xkcd, Glider, SmallExploder, Exploder, TenCellRow, LightweightSpaceship, Tumbler, GliderGun, Acorn, } pub static ALL: &[Preset] = &[ Preset::Custom, Preset::Xkcd, Preset::Glider, Preset::SmallExploder, Preset::Exploder, Preset::TenCellRow, Preset::LightweightSpaceship, Preset::Tumbler, Preset::GliderGun, Preset::Acorn, ]; impl Preset { pub fn life(self) -> Vec<(isize, isize)> { #[rustfmt::skip] let cells = match self { Preset::Custom => vec![], Preset::Xkcd => vec![ " xxx ", " x x ", " x x ", " x ", "x xxx ", " x x x ", " x x", " x x ", " x x ", ], Preset::Glider => vec![ " x ", " x", "xxx" ], Preset::SmallExploder => vec![ " x ", "xxx", "x x", " x ", ], Preset::Exploder => vec![ "x x x", "x x", "x x", "x x", "x x x", ], Preset::TenCellRow => vec![ "xxxxxxxxxx", ], Preset::LightweightSpaceship => vec![ " xxxxx", "x x", " x", "x x ", ], Preset::Tumbler => vec![ " xx xx ", " xx xx ", " x x ", "x x x x", "x x x x", "xx xx", ], Preset::GliderGun => vec![ " x ", " x x ", " xx xx xx", " x x xx xx", "xx x x xx ", "xx x x xx x x ", " x x x ", " x x ", " xx ", ], Preset::Acorn => vec![ " x ", " x ", "xx xxx", ], }; let start_row = -(cells.len() as isize / 2); cells .into_iter() .enumerate() .flat_map(|(i, cells)| { let start_column = -(cells.len() as isize / 2); cells .chars() .enumerate() .filter(|(_, c)| !c.is_whitespace()) .map(move |(j, _)| (start_row + i as isize, start_column + j as isize)) }) .collect() } } impl std::fmt::Display for Preset { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Preset::Custom => "Custom", Preset::Xkcd => "xkcd #2293", Preset::Glider => "Glider", Preset::SmallExploder => "Small Exploder", Preset::Exploder => "Exploder", Preset::TenCellRow => "10 Cell Row", Preset::LightweightSpaceship => "Lightweight spaceship", Preset::Tumbler => "Tumbler", Preset::GliderGun => "Gosper Glider Gun", Preset::Acorn => "Acorn", } ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/game_of_life/src/main.rs
examples/game_of_life/src/main.rs
//! This example showcases an interactive version of the Game of Life, invented //! by John Conway. It leverages a `Canvas` together with other widgets. mod preset; use grid::Grid; use preset::Preset; use iced::time::{self, milliseconds}; use iced::widget::{button, checkbox, column, container, pick_list, row, slider, text}; use iced::{Center, Element, Fill, Function, Subscription, Task, Theme}; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(GameOfLife::default, GameOfLife::update, GameOfLife::view) .subscription(GameOfLife::subscription) .theme(Theme::Dark) .centered() .run() } struct GameOfLife { grid: Grid, is_playing: bool, queued_ticks: usize, speed: usize, next_speed: Option<usize>, version: usize, } #[derive(Debug, Clone)] enum Message { Grid(usize, grid::Message), Tick, TogglePlayback, ToggleGrid(bool), Next, Clear, SpeedChanged(f32), PresetPicked(Preset), } impl GameOfLife { fn new() -> Self { Self { grid: Grid::default(), is_playing: false, queued_ticks: 0, speed: 5, next_speed: None, version: 0, } } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Grid(version, message) => { if version == self.version { self.grid.update(message); } } Message::Tick | Message::Next => { self.queued_ticks = (self.queued_ticks + 1).min(self.speed); if let Some(task) = self.grid.tick(self.queued_ticks) { if let Some(speed) = self.next_speed.take() { self.speed = speed; } self.queued_ticks = 0; let version = self.version; return Task::perform(task, Message::Grid.with(version)); } } Message::TogglePlayback => { self.is_playing = !self.is_playing; } Message::ToggleGrid(show_grid_lines) => { self.grid.toggle_lines(show_grid_lines); } Message::Clear => { self.grid.clear(); self.version += 1; } Message::SpeedChanged(speed) => { if self.is_playing { self.next_speed = Some(speed.round() as usize); } else { self.speed = speed.round() as usize; } } Message::PresetPicked(new_preset) => { self.grid = Grid::from_preset(new_preset); self.version += 1; } } Task::none() } fn subscription(&self) -> Subscription<Message> { if self.is_playing { time::every(milliseconds(1000 / self.speed as u64)).map(|_| Message::Tick) } else { Subscription::none() } } fn view(&self) -> Element<'_, Message> { let version = self.version; let selected_speed = self.next_speed.unwrap_or(self.speed); let controls = view_controls( self.is_playing, self.grid.are_lines_visible(), selected_speed, self.grid.preset(), ); let content = column![self.grid.view().map(Message::Grid.with(version)), controls,].height(Fill); container(content).width(Fill).height(Fill).into() } } impl Default for GameOfLife { fn default() -> Self { Self::new() } } fn view_controls<'a>( is_playing: bool, is_grid_enabled: bool, speed: usize, preset: Preset, ) -> Element<'a, Message> { let playback_controls = row![ button(if is_playing { "Pause" } else { "Play" }).on_press(Message::TogglePlayback), button("Next") .on_press(Message::Next) .style(button::secondary), ] .spacing(10); let speed_controls = row![ slider(1.0..=1000.0, speed as f32, Message::SpeedChanged), text!("x{speed}").size(16), ] .align_y(Center) .spacing(10); row![ playback_controls, speed_controls, checkbox(is_grid_enabled) .label("Grid") .on_toggle(Message::ToggleGrid), row![ pick_list(preset::ALL, Some(preset), Message::PresetPicked), button("Clear") .on_press(Message::Clear) .style(button::danger) ] .spacing(10) ] .padding(10) .spacing(20) .align_y(Center) .into() } mod grid { use crate::Preset; use iced::alignment; use iced::mouse; use iced::time::{Duration, Instant}; use iced::touch; use iced::widget::canvas; use iced::widget::canvas::{Cache, Canvas, Event, Frame, Geometry, Path, Text}; use iced::widget::text; use iced::{Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme, Vector}; use rustc_hash::{FxHashMap, FxHashSet}; use std::ops::RangeInclusive; pub struct Grid { state: State, preset: Preset, life_cache: Cache, grid_cache: Cache, translation: Vector, scaling: f32, show_lines: bool, last_tick_duration: Duration, last_queued_ticks: usize, } #[derive(Debug, Clone)] pub enum Message { Populate(Cell), Unpopulate(Cell), Translated(Vector), Scaled(f32, Option<Vector>), Ticked { result: Result<Life, TickError>, tick_duration: Duration, }, } #[derive(Debug, Clone)] pub enum TickError { JoinFailed, } impl Default for Grid { fn default() -> Self { Self::from_preset(Preset::default()) } } impl Grid { const MIN_SCALING: f32 = 0.1; const MAX_SCALING: f32 = 2.0; pub fn from_preset(preset: Preset) -> Self { Self { state: State::with_life( preset .life() .into_iter() .map(|(i, j)| Cell { i, j }) .collect(), ), preset, life_cache: Cache::default(), grid_cache: Cache::default(), translation: Vector::default(), scaling: 1.0, show_lines: true, last_tick_duration: Duration::default(), last_queued_ticks: 0, } } pub fn tick(&mut self, amount: usize) -> Option<impl Future<Output = Message> + use<>> { let tick = self.state.tick(amount)?; self.last_queued_ticks = amount; Some(async move { let start = Instant::now(); let result = tick.await; let tick_duration = start.elapsed() / amount as u32; Message::Ticked { result, tick_duration, } }) } pub fn update(&mut self, message: Message) { match message { Message::Populate(cell) => { self.state.populate(cell); self.life_cache.clear(); self.preset = Preset::Custom; } Message::Unpopulate(cell) => { self.state.unpopulate(&cell); self.life_cache.clear(); self.preset = Preset::Custom; } Message::Translated(translation) => { self.translation = translation; self.life_cache.clear(); self.grid_cache.clear(); } Message::Scaled(scaling, translation) => { self.scaling = scaling; if let Some(translation) = translation { self.translation = translation; } self.life_cache.clear(); self.grid_cache.clear(); } Message::Ticked { result: Ok(life), tick_duration, } => { self.state.update(life); self.life_cache.clear(); self.last_tick_duration = tick_duration; } Message::Ticked { result: Err(error), .. } => { dbg!(error); } } } pub fn view(&self) -> Element<'_, Message> { Canvas::new(self).width(Fill).height(Fill).into() } pub fn clear(&mut self) { self.state = State::default(); self.preset = Preset::Custom; self.life_cache.clear(); } pub fn preset(&self) -> Preset { self.preset } pub fn toggle_lines(&mut self, enabled: bool) { self.show_lines = enabled; } pub fn are_lines_visible(&self) -> bool { self.show_lines } fn visible_region(&self, size: Size) -> Region { let width = size.width / self.scaling; let height = size.height / self.scaling; Region { x: -self.translation.x - width / 2.0, y: -self.translation.y - height / 2.0, width, height, } } fn project(&self, position: Point, size: Size) -> Point { let region = self.visible_region(size); Point::new( position.x / self.scaling + region.x, position.y / self.scaling + region.y, ) } } impl canvas::Program<Message> for Grid { type State = Interaction; fn update( &self, interaction: &mut Interaction, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<canvas::Action<Message>> { if let Event::Mouse(mouse::Event::ButtonReleased(_)) = event { *interaction = Interaction::None; } let cursor_position = cursor.position_in(bounds)?; let cell = Cell::at(self.project(cursor_position, bounds.size())); let is_populated = self.state.contains(&cell); let (populate, unpopulate) = if is_populated { (None, Some(Message::Unpopulate(cell))) } else { (Some(Message::Populate(cell)), None) }; match event { Event::Touch(touch::Event::FingerMoved { .. }) => { let message = { *interaction = if is_populated { Interaction::Erasing } else { Interaction::Drawing }; populate.or(unpopulate) }; Some( message .map(canvas::Action::publish) .unwrap_or(canvas::Action::request_redraw()) .and_capture(), ) } Event::Mouse(mouse_event) => match mouse_event { mouse::Event::ButtonPressed(button) => { let message = match button { mouse::Button::Left => { *interaction = if is_populated { Interaction::Erasing } else { Interaction::Drawing }; populate.or(unpopulate) } mouse::Button::Right => { *interaction = Interaction::Panning { translation: self.translation, start: cursor_position, }; None } _ => None, }; Some( message .map(canvas::Action::publish) .unwrap_or(canvas::Action::request_redraw()) .and_capture(), ) } mouse::Event::CursorMoved { .. } => { let message = match *interaction { Interaction::Drawing => populate, Interaction::Erasing => unpopulate, Interaction::Panning { translation, start } => { Some(Message::Translated( translation + (cursor_position - start) * (1.0 / self.scaling), )) } Interaction::None => None, }; let action = message .map(canvas::Action::publish) .unwrap_or(canvas::Action::request_redraw()); Some(match interaction { Interaction::None => action, _ => action.and_capture(), }) } mouse::Event::WheelScrolled { delta } => match *delta { mouse::ScrollDelta::Lines { y, .. } | mouse::ScrollDelta::Pixels { y, .. } => { if y < 0.0 && self.scaling > Self::MIN_SCALING || y > 0.0 && self.scaling < Self::MAX_SCALING { let old_scaling = self.scaling; let scaling = (self.scaling * (1.0 + y / 30.0)) .clamp(Self::MIN_SCALING, Self::MAX_SCALING); let translation = if let Some(cursor_to_center) = cursor.position_from(bounds.center()) { let factor = scaling - old_scaling; Some( self.translation - Vector::new( cursor_to_center.x * factor / (old_scaling * old_scaling), cursor_to_center.y * factor / (old_scaling * old_scaling), ), ) } else { None }; Some( canvas::Action::publish(Message::Scaled(scaling, translation)) .and_capture(), ) } else { Some(canvas::Action::capture()) } } }, _ => None, }, _ => None, } } fn draw( &self, _interaction: &Interaction, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec<Geometry> { let center = Vector::new(bounds.width / 2.0, bounds.height / 2.0); let life = self.life_cache.draw(renderer, bounds.size(), |frame| { let background = Path::rectangle(Point::ORIGIN, frame.size()); frame.fill(&background, Color::from_rgb8(0x40, 0x44, 0x4B)); frame.with_save(|frame| { frame.translate(center); frame.scale(self.scaling); frame.translate(self.translation); frame.scale(Cell::SIZE); let region = self.visible_region(frame.size()); for cell in region.cull(self.state.cells()) { frame.fill_rectangle( Point::new(cell.j as f32, cell.i as f32), Size::UNIT, Color::WHITE, ); } }); }); let overlay = { let mut frame = Frame::new(renderer, bounds.size()); let hovered_cell = cursor .position_in(bounds) .map(|position| Cell::at(self.project(position, frame.size()))); if let Some(cell) = hovered_cell { frame.with_save(|frame| { frame.translate(center); frame.scale(self.scaling); frame.translate(self.translation); frame.scale(Cell::SIZE); frame.fill_rectangle( Point::new(cell.j as f32, cell.i as f32), Size::UNIT, Color { a: 0.5, ..Color::BLACK }, ); }); } let text = Text { color: Color::WHITE, size: 14.0.into(), position: Point::new(frame.width(), frame.height()), align_x: text::Alignment::Right, align_y: alignment::Vertical::Bottom, ..Text::default() }; if let Some(cell) = hovered_cell { frame.fill_text(Text { content: format!("({}, {})", cell.j, cell.i), position: text.position - Vector::new(0.0, 16.0), ..text }); } let cell_count = self.state.cell_count(); frame.fill_text(Text { content: format!( "{cell_count} cell{} @ {:?} ({})", if cell_count == 1 { "" } else { "s" }, self.last_tick_duration, self.last_queued_ticks ), ..text }); frame.into_geometry() }; if self.scaling >= 0.2 && self.show_lines { let grid = self.grid_cache.draw(renderer, bounds.size(), |frame| { frame.translate(center); frame.scale(self.scaling); frame.translate(self.translation); frame.scale(Cell::SIZE); let region = self.visible_region(frame.size()); let rows = region.rows(); let columns = region.columns(); let (total_rows, total_columns) = (rows.clone().count(), columns.clone().count()); let width = 2.0 / Cell::SIZE as f32; let color = Color::from_rgb8(70, 74, 83); frame.translate(Vector::new(-width / 2.0, -width / 2.0)); for row in region.rows() { frame.fill_rectangle( Point::new(*columns.start() as f32, row as f32), Size::new(total_columns as f32, width), color, ); } for column in region.columns() { frame.fill_rectangle( Point::new(column as f32, *rows.start() as f32), Size::new(width, total_rows as f32), color, ); } }); vec![life, grid, overlay] } else { vec![life, overlay] } } fn mouse_interaction( &self, interaction: &Interaction, bounds: Rectangle, cursor: mouse::Cursor, ) -> mouse::Interaction { match interaction { Interaction::Drawing => mouse::Interaction::Crosshair, Interaction::Erasing => mouse::Interaction::Crosshair, Interaction::Panning { .. } => mouse::Interaction::Grabbing, Interaction::None if cursor.is_over(bounds) => mouse::Interaction::Crosshair, Interaction::None => mouse::Interaction::default(), } } } #[derive(Default)] struct State { life: Life, births: FxHashSet<Cell>, is_ticking: bool, } impl State { pub fn with_life(life: Life) -> Self { Self { life, ..Self::default() } } fn cell_count(&self) -> usize { self.life.len() + self.births.len() } fn contains(&self, cell: &Cell) -> bool { self.life.contains(cell) || self.births.contains(cell) } fn cells(&self) -> impl Iterator<Item = &Cell> { self.life.iter().chain(self.births.iter()) } fn populate(&mut self, cell: Cell) { if self.is_ticking { self.births.insert(cell); } else { self.life.populate(cell); } } fn unpopulate(&mut self, cell: &Cell) { if self.is_ticking { let _ = self.births.remove(cell); } else { self.life.unpopulate(cell); } } fn update(&mut self, mut life: Life) { self.births.drain().for_each(|cell| life.populate(cell)); self.life = life; self.is_ticking = false; } fn tick( &mut self, amount: usize, ) -> Option<impl Future<Output = Result<Life, TickError>> + use<>> { if self.is_ticking { return None; } self.is_ticking = true; let mut life = self.life.clone(); Some(async move { tokio::task::spawn_blocking(move || { for _ in 0..amount { life.tick(); } life }) .await .map_err(|_| TickError::JoinFailed) }) } } #[derive(Clone, Default)] pub struct Life { cells: FxHashSet<Cell>, } impl Life { fn len(&self) -> usize { self.cells.len() } fn contains(&self, cell: &Cell) -> bool { self.cells.contains(cell) } fn populate(&mut self, cell: Cell) { self.cells.insert(cell); } fn unpopulate(&mut self, cell: &Cell) { let _ = self.cells.remove(cell); } fn tick(&mut self) { let mut adjacent_life = FxHashMap::default(); for cell in &self.cells { let _ = adjacent_life.entry(*cell).or_insert(0); for neighbor in Cell::neighbors(*cell) { let amount = adjacent_life.entry(neighbor).or_insert(0); *amount += 1; } } for (cell, amount) in &adjacent_life { match amount { 2 => {} 3 => { let _ = self.cells.insert(*cell); } _ => { let _ = self.cells.remove(cell); } } } } pub fn iter(&self) -> impl Iterator<Item = &Cell> { self.cells.iter() } } impl std::iter::FromIterator<Cell> for Life { fn from_iter<I: IntoIterator<Item = Cell>>(iter: I) -> Self { Life { cells: iter.into_iter().collect(), } } } impl std::fmt::Debug for Life { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Life") .field("cells", &self.cells.len()) .finish() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Cell { i: isize, j: isize, } impl Cell { const SIZE: u16 = 20; fn at(position: Point) -> Cell { let i = (position.y / Cell::SIZE as f32).ceil() as isize; let j = (position.x / Cell::SIZE as f32).ceil() as isize; Cell { i: i.saturating_sub(1), j: j.saturating_sub(1), } } fn cluster(cell: Cell) -> impl Iterator<Item = Cell> { use itertools::Itertools; let rows = cell.i.saturating_sub(1)..=cell.i.saturating_add(1); let columns = cell.j.saturating_sub(1)..=cell.j.saturating_add(1); rows.cartesian_product(columns).map(|(i, j)| Cell { i, j }) } fn neighbors(cell: Cell) -> impl Iterator<Item = Cell> { Cell::cluster(cell).filter(move |candidate| *candidate != cell) } } pub struct Region { x: f32, y: f32, width: f32, height: f32, } impl Region { fn rows(&self) -> RangeInclusive<isize> { let first_row = (self.y / Cell::SIZE as f32).floor() as isize; let visible_rows = (self.height / Cell::SIZE as f32).ceil() as isize; first_row..=first_row + visible_rows } fn columns(&self) -> RangeInclusive<isize> { let first_column = (self.x / Cell::SIZE as f32).floor() as isize; let visible_columns = (self.width / Cell::SIZE as f32).ceil() as isize; first_column..=first_column + visible_columns } fn cull<'a>( &self, cells: impl Iterator<Item = &'a Cell>, ) -> impl Iterator<Item = &'a Cell> { let rows = self.rows(); let columns = self.columns(); cells.filter(move |cell| rows.contains(&cell.i) && columns.contains(&cell.j)) } } #[derive(Default)] pub enum Interaction { #[default] None, Drawing, Erasing, Panning { translation: Vector, start: Point, }, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/screenshot/src/main.rs
examples/screenshot/src/main.rs
use iced::keyboard; use iced::widget::{button, center_y, column, container, image, row, text, text_input}; use iced::window; use iced::window::screenshot::{self, Screenshot}; use iced::{Center, ContentFit, Element, Fill, FillPortion, Rectangle, Subscription, Task}; use ::image as img; use ::image::ColorType; fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(Example::default, Example::update, Example::view) .subscription(Example::subscription) .run() } #[derive(Default)] struct Example { screenshot: Option<(Screenshot, image::Handle)>, saved_png_path: Option<Result<String, PngError>>, png_saving: bool, crop_error: Option<screenshot::CropError>, x_input_value: Option<u32>, y_input_value: Option<u32>, width_input_value: Option<u32>, height_input_value: Option<u32>, } #[derive(Clone, Debug)] enum Message { Crop, Screenshot, Screenshotted(Screenshot), Png, PngSaved(Result<String, PngError>), XInputChanged(Option<u32>), YInputChanged(Option<u32>), WidthInputChanged(Option<u32>), HeightInputChanged(Option<u32>), } impl Example { fn update(&mut self, message: Message) -> Task<Message> { match message { Message::Screenshot => { return window::latest() .and_then(window::screenshot) .map(Message::Screenshotted); } Message::Screenshotted(screenshot) => { self.screenshot = Some(( screenshot.clone(), image::Handle::from_rgba( screenshot.size.width, screenshot.size.height, screenshot.rgba, ), )); } Message::Png => { if let Some((screenshot, _handle)) = &self.screenshot { self.png_saving = true; return Task::perform(save_to_png(screenshot.clone()), Message::PngSaved); } } Message::PngSaved(res) => { self.png_saving = false; self.saved_png_path = Some(res); } Message::XInputChanged(new_value) => { self.x_input_value = new_value; } Message::YInputChanged(new_value) => { self.y_input_value = new_value; } Message::WidthInputChanged(new_value) => { self.width_input_value = new_value; } Message::HeightInputChanged(new_value) => { self.height_input_value = new_value; } Message::Crop => { if let Some((screenshot, _handle)) = &self.screenshot { let cropped = screenshot.crop(Rectangle::<u32> { x: self.x_input_value.unwrap_or(0), y: self.y_input_value.unwrap_or(0), width: self.width_input_value.unwrap_or(0), height: self.height_input_value.unwrap_or(0), }); match cropped { Ok(screenshot) => { self.screenshot = Some(( screenshot.clone(), image::Handle::from_rgba( screenshot.size.width, screenshot.size.height, screenshot.rgba, ), )); self.crop_error = None; } Err(crop_error) => { self.crop_error = Some(crop_error); } } } } } Task::none() } fn view(&self) -> Element<'_, Message> { let image: Element<Message> = if let Some((_screenshot, handle)) = &self.screenshot { image(handle) .content_fit(ContentFit::Contain) .width(Fill) .height(Fill) .into() } else { text("Press the button to take a screenshot!").into() }; let image = center_y(image) .height(FillPortion(2)) .padding(10) .style(container::rounded_box); let crop_origin_controls = row![ text("X:").width(30), numeric_input("0", self.x_input_value).map(Message::XInputChanged), text("Y:").width(30), numeric_input("0", self.y_input_value).map(Message::YInputChanged) ] .spacing(10) .align_y(Center); let crop_dimension_controls = row![ text("W:").width(30), numeric_input("0", self.width_input_value).map(Message::WidthInputChanged), text("H:").width(30), numeric_input("0", self.height_input_value).map(Message::HeightInputChanged) ] .spacing(10) .align_y(Center); let crop_controls = column![ crop_origin_controls, crop_dimension_controls, self.crop_error .as_ref() .map(|error| text!("Crop error! \n{error}")), ] .spacing(10) .align_x(Center); let controls = { let save_result = self .saved_png_path .as_ref() .map(|png_result| match png_result { Ok(path) => format!("Png saved as: {path:?}!"), Err(PngError(error)) => { format!("Png could not be saved due to:\n{error}") } }); column![ column![ button(centered_text("Screenshot!")) .padding([10, 20]) .width(Fill) .on_press(Message::Screenshot), if !self.png_saving { button(centered_text("Save as png")) .on_press_maybe(self.screenshot.is_some().then(|| Message::Png)) } else { button(centered_text("Saving...")).style(button::secondary) } .style(button::secondary) .padding([10, 20]) .width(Fill) ] .spacing(10), column![ crop_controls, button(centered_text("Crop")) .on_press(Message::Crop) .style(button::danger) .padding([10, 20]) .width(Fill), ] .spacing(10) .align_x(Center), save_result.map(text) ] .spacing(40) }; let side_content = center_y(controls); let content = row![side_content, image] .spacing(10) .width(Fill) .height(Fill) .align_y(Center); container(content).padding(10).into() } fn subscription(&self) -> Subscription<Message> { use keyboard::key; keyboard::listen().filter_map(|event| { if let keyboard::Event::KeyPressed { modified_key: keyboard::Key::Named(key::Named::F5), .. } = event { Some(Message::Screenshot) } else { None } }) } } async fn save_to_png(screenshot: Screenshot) -> Result<String, PngError> { let path = "screenshot.png".to_string(); tokio::task::spawn_blocking(move || { img::save_buffer( &path, &screenshot.rgba, screenshot.size.width, screenshot.size.height, ColorType::Rgba8, ) .map(|_| path) .map_err(|error| PngError(error.to_string())) }) .await .expect("Blocking task to finish") } #[derive(Clone, Debug)] struct PngError(String); fn numeric_input(placeholder: &str, value: Option<u32>) -> Element<'_, Option<u32>> { text_input( placeholder, &value.as_ref().map(ToString::to_string).unwrap_or_default(), ) .on_input(move |text| { if text.is_empty() { None } else if let Ok(new_value) = text.parse() { Some(new_value) } else { value } }) .width(40) .into() } fn centered_text(content: &str) -> Element<'_, Message> { text(content).width(Fill).align_x(Center).into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/the_matrix/src/main.rs
examples/the_matrix/src/main.rs
use iced::mouse; use iced::time::{self, milliseconds}; use iced::widget::canvas; use iced::{Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme}; use std::cell::RefCell; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(TheMatrix::default, TheMatrix::update, TheMatrix::view) .subscription(TheMatrix::subscription) .run() } #[derive(Default)] struct TheMatrix { tick: usize, } #[derive(Debug, Clone, Copy)] enum Message { Tick, } impl TheMatrix { fn update(&mut self, message: Message) { match message { Message::Tick => { self.tick += 1; } } } fn view(&self) -> Element<'_, Message> { canvas(self).width(Fill).height(Fill).into() } fn subscription(&self) -> Subscription<Message> { time::every(milliseconds(50)).map(|_| Message::Tick) } } impl<Message> canvas::Program<Message> for TheMatrix { type State = RefCell<Vec<canvas::Cache>>; fn draw( &self, state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<canvas::Geometry> { use rand::Rng; use rand::distributions::Distribution; const CELL_SIZE: f32 = 10.0; let mut caches = state.borrow_mut(); if caches.is_empty() { let group = canvas::Group::unique(); caches.resize_with(30, || canvas::Cache::with_group(group)); } vec![ caches[self.tick % caches.len()].draw(renderer, bounds.size(), |frame| { frame.fill_rectangle(Point::ORIGIN, frame.size(), Color::BLACK); let mut rng = rand::thread_rng(); let rows = (frame.height() / CELL_SIZE).ceil() as usize; let columns = (frame.width() / CELL_SIZE).ceil() as usize; for row in 0..rows { for column in 0..columns { let position = Point::new(column as f32 * CELL_SIZE, row as f32 * CELL_SIZE); let alphas = [0.05, 0.1, 0.2, 0.5]; let weights = [10, 4, 2, 1]; let distribution = rand::distributions::WeightedIndex::new(weights) .expect("Create distribution"); frame.fill_text(canvas::Text { content: rng.gen_range('!'..'z').to_string(), position, color: Color { a: alphas[distribution.sample(&mut rng)], g: 1.0, ..Color::BLACK }, size: CELL_SIZE.into(), font: Font::MONOSPACE, ..canvas::Text::default() }); } } }), ] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/clock/src/main.rs
examples/clock/src/main.rs
use iced::alignment; use iced::mouse; use iced::time::{self, milliseconds}; use iced::widget::canvas::{Cache, Geometry, LineCap, Path, Stroke, stroke}; use iced::widget::{canvas, container, text}; use iced::{ Degrees, Element, Fill, Font, Point, Radians, Rectangle, Renderer, Size, Subscription, Theme, Vector, }; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(Clock::new, Clock::update, Clock::view) .subscription(Clock::subscription) .theme(Clock::theme) .run() } struct Clock { now: chrono::DateTime<chrono::Local>, clock: Cache, } #[derive(Debug, Clone, Copy)] enum Message { Tick(chrono::DateTime<chrono::Local>), } impl Clock { fn new() -> Self { Self { now: chrono::offset::Local::now(), clock: Cache::default(), } } fn update(&mut self, message: Message) { match message { Message::Tick(local_time) => { let now = local_time; if now != self.now { self.now = now; self.clock.clear(); } } } } fn view(&self) -> Element<'_, Message> { let canvas = canvas(self as &Self).width(Fill).height(Fill); container(canvas).padding(20).into() } fn subscription(&self) -> Subscription<Message> { time::every(milliseconds(500)).map(|_| Message::Tick(chrono::offset::Local::now())) } fn theme(&self) -> Theme { Theme::ALL[(self.now.timestamp() as usize / 10) % Theme::ALL.len()].clone() } } impl<Message> canvas::Program<Message> for Clock { type State = (); fn draw( &self, _state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, ) -> Vec<Geometry> { use chrono::Timelike; let clock = self.clock.draw(renderer, bounds.size(), |frame| { let palette = theme.extended_palette(); let center = frame.center(); let radius = frame.width().min(frame.height()) / 2.0; let background = Path::circle(center, radius); frame.fill(&background, palette.secondary.strong.color); let short_hand = Path::line(Point::ORIGIN, Point::new(0.0, -0.5 * radius)); let long_hand = Path::line(Point::ORIGIN, Point::new(0.0, -0.8 * radius)); let width = radius / 100.0; let thin_stroke = || -> Stroke { Stroke { width, style: stroke::Style::Solid(palette.secondary.strong.text), line_cap: LineCap::Round, ..Stroke::default() } }; let wide_stroke = || -> Stroke { Stroke { width: width * 3.0, style: stroke::Style::Solid(palette.secondary.strong.text), line_cap: LineCap::Round, ..Stroke::default() } }; frame.translate(Vector::new(center.x, center.y)); let minutes_portion = Radians::from(hand_rotation(self.now.minute(), 60)) / 12.0; let hour_hand_angle = Radians::from(hand_rotation(self.now.hour(), 12)) + minutes_portion; frame.with_save(|frame| { frame.rotate(hour_hand_angle); frame.stroke(&short_hand, wide_stroke()); }); frame.with_save(|frame| { frame.rotate(hand_rotation(self.now.minute(), 60)); frame.stroke(&long_hand, wide_stroke()); }); frame.with_save(|frame| { let rotation = hand_rotation(self.now.second(), 60); frame.rotate(rotation); frame.stroke(&long_hand, thin_stroke()); let rotate_factor = if rotation < 180.0 { 1.0 } else { -1.0 }; frame.rotate(Degrees(-90.0 * rotate_factor)); frame.fill_text(canvas::Text { content: theme.to_string(), size: (radius / 15.0).into(), position: Point::new((0.78 * radius) * rotate_factor, -width * 2.0), color: palette.secondary.strong.text, align_x: if rotate_factor > 0.0 { text::Alignment::Right } else { text::Alignment::Left }, align_y: alignment::Vertical::Bottom, font: Font::MONOSPACE, ..canvas::Text::default() }); }); // Draw clock numbers for hour in 1..=12 { let angle = Radians::from(hand_rotation(hour, 12)) - Radians::from(Degrees(90.0)); let x = radius * angle.0.cos(); let y = radius * angle.0.sin(); frame.fill_text(canvas::Text { content: format!("{hour}"), size: (radius / 5.0).into(), position: Point::new(x * 0.82, y * 0.82), color: palette.secondary.strong.text, align_x: text::Alignment::Center, align_y: alignment::Vertical::Center, font: Font::MONOSPACE, ..canvas::Text::default() }); } // Draw ticks for tick in 0..60 { let angle = hand_rotation(tick, 60); let width = if tick % 5 == 0 { 3.0 } else { 1.0 }; frame.with_save(|frame| { frame.rotate(angle); frame.fill( &Path::rectangle(Point::new(0.0, radius - 15.0), Size::new(width, 7.0)), palette.secondary.strong.text, ); }); } }); vec![clock] } } fn hand_rotation(n: u32, total: u32) -> Degrees { let turns = n as f32 / total as f32; Degrees(360.0 * turns) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/table/src/main.rs
examples/table/src/main.rs
use iced::font; use iced::time::{Duration, hours, minutes}; use iced::widget::{ center_x, center_y, column, container, row, scrollable, slider, table, text, tooltip, }; use iced::{Center, Element, Fill, Font, Right, Theme}; pub fn main() -> iced::Result { iced::application(Table::new, Table::update, Table::view) .theme(Theme::CatppuccinMocha) .run() } struct Table { events: Vec<Event>, padding: (f32, f32), separator: (f32, f32), } #[derive(Debug, Clone)] enum Message { PaddingChanged(f32, f32), SeparatorChanged(f32, f32), } impl Table { fn new() -> Self { Self { events: Event::list(), padding: (10.0, 5.0), separator: (1.0, 1.0), } } fn update(&mut self, message: Message) { match message { Message::PaddingChanged(x, y) => self.padding = (x, y), Message::SeparatorChanged(x, y) => self.separator = (x, y), } } fn view(&self) -> Element<'_, Message> { let table = { let bold = |header| { text(header).font(Font { weight: font::Weight::Bold, ..Font::DEFAULT }) }; let columns = [ table::column(bold("Name"), |event: &Event| text(&event.name)), table::column(bold("Time"), |event: &Event| { let minutes = event.duration.as_secs() / 60; text!("{minutes} min").style(if minutes > 90 { text::warning } else { text::default }) }) .align_x(Right) .align_y(Center), table::column(bold("Price"), |event: &Event| { if event.price > 0.0 { text!("${:.2}", event.price).style(if event.price > 100.0 { text::warning } else { text::default }) } else { text("Free").style(text::success).width(Fill).center() } }) .align_x(Right) .align_y(Center), table::column(bold("Rating"), |event: &Event| { text!("{:.2}", event.rating).style(if event.rating > 4.7 { text::success } else if event.rating < 2.0 { text::danger } else { text::default }) }) .align_x(Right) .align_y(Center), ]; table(columns, &self.events) .padding_x(self.padding.0) .padding_y(self.padding.1) .separator_x(self.separator.0) .separator_y(self.separator.1) }; let controls = { let labeled_slider = |label, range: std::ops::RangeInclusive<f32>, (x, y), on_change: fn(f32, f32) -> Message| { row![ text(label).font(Font::MONOSPACE).size(14).width(100), tooltip( slider(range.clone(), x, move |x| on_change(x, y)), text!("{x:.0}px").font(Font::MONOSPACE).size(10), tooltip::Position::Left ), tooltip( slider(range, y, move |y| on_change(x, y)), text!("{y:.0}px").font(Font::MONOSPACE).size(10), tooltip::Position::Right ), ] .spacing(10) .align_y(Center) }; column![ labeled_slider("Padding", 0.0..=30.0, self.padding, Message::PaddingChanged), labeled_slider( "Separator", 0.0..=5.0, self.separator, Message::SeparatorChanged ) ] .spacing(10) .width(400) }; column![ center_y(scrollable(center_x(table)).spacing(10)).padding(10), center_x(controls).padding(10).style(container::dark) ] .into() } } struct Event { name: String, duration: Duration, price: f32, rating: f32, } impl Event { fn list() -> Vec<Self> { vec![ Event { name: "Get lost in a hacker bookstore".to_owned(), duration: hours(2), price: 0.0, rating: 4.9, }, Event { name: "Buy vintage synth at Noisebridge flea market".to_owned(), duration: hours(1), price: 150.0, rating: 4.8, }, Event { name: "Eat a questionable hot dog at 2AM".to_owned(), duration: minutes(20), price: 5.0, rating: 1.7, }, Event { name: "Ride the MUNI for the story".to_owned(), duration: minutes(60), price: 3.0, rating: 4.1, }, Event { name: "Scream into the void from Twin Peaks".to_owned(), duration: minutes(40), price: 0.0, rating: 4.9, }, Event { name: "Buy overpriced coffee and feel things".to_owned(), duration: minutes(25), price: 6.5, rating: 4.5, }, Event { name: "Attend an underground robot poetry slam".to_owned(), duration: hours(1), price: 12.0, rating: 4.8, }, Event { name: "Browse cursed tech at a retro computer fair".to_owned(), duration: hours(2), price: 10.0, rating: 4.7, }, Event { name: "Try to order at a secret ramen place with no sign".to_owned(), duration: minutes(50), price: 14.0, rating: 4.6, }, Event { name: "Join a spontaneous rooftop drone rave".to_owned(), duration: hours(3), price: 0.0, rating: 4.9, }, Event { name: "Sketch a stranger at Dolores Park".to_owned(), duration: minutes(45), price: 0.0, rating: 4.4, }, Event { name: "Visit the Museum of Obsolete APIs".to_owned(), duration: hours(1), price: 9.99, rating: 4.2, }, Event { name: "Chase the last working payphone".to_owned(), duration: minutes(35), price: 0.25, rating: 4.0, }, Event { name: "Trade zines with a punk on BART".to_owned(), duration: minutes(30), price: 3.5, rating: 4.7, }, Event { name: "Get a tattoo of the Git logo".to_owned(), duration: hours(1), price: 200.0, rating: 4.6, }, ] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/progress_bar/src/main.rs
examples/progress_bar/src/main.rs
use iced::Element; use iced::widget::{ center, center_x, checkbox, column, progress_bar, row, slider, vertical_slider, }; pub fn main() -> iced::Result { iced::run(Progress::update, Progress::view) } #[derive(Default)] struct Progress { value: f32, is_vertical: bool, } #[derive(Debug, Clone, Copy)] enum Message { SliderChanged(f32), ToggleVertical(bool), } impl Progress { fn update(&mut self, message: Message) { match message { Message::SliderChanged(x) => self.value = x, Message::ToggleVertical(is_vertical) => self.is_vertical = is_vertical, } } fn view(&self) -> Element<'_, Message> { let bar = progress_bar(0.0..=100.0, self.value); column![ if self.is_vertical { center( row![ bar.vertical(), vertical_slider(0.0..=100.0, self.value, Message::SliderChanged).step(0.01) ] .spacing(20), ) } else { center( column![ bar, slider(0.0..=100.0, self.value, Message::SliderChanged).step(0.01) ] .spacing(20), ) }, center_x( checkbox(self.is_vertical) .label("Vertical") .on_toggle(Message::ToggleVertical) ), ] .spacing(20) .padding(20) .into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/svg/src/main.rs
examples/svg/src/main.rs
use iced::widget::{center, center_x, checkbox, column, svg}; use iced::{Element, Fill, color}; pub fn main() -> iced::Result { iced::run(Tiger::update, Tiger::view) } #[derive(Debug, Default)] struct Tiger { apply_color_filter: bool, } #[derive(Debug, Clone, Copy)] pub enum Message { ToggleColorFilter(bool), } impl Tiger { fn update(&mut self, message: Message) { match message { Message::ToggleColorFilter(apply_color_filter) => { self.apply_color_filter = apply_color_filter; } } } fn view(&self) -> Element<'_, Message> { let svg = svg(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/tiger.svg")) .width(Fill) .height(Fill) .style(|_theme, _status| svg::Style { color: if self.apply_color_filter { Some(color!(0x0000ff)) } else { None }, }); let apply_color_filter = checkbox(self.apply_color_filter) .label("Apply a color filter") .on_toggle(Message::ToggleColorFilter); center(column![svg, center_x(apply_color_filter)].spacing(20)) .padding(20) .into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/todos/src/main.rs
examples/todos/src/main.rs
use iced::keyboard; use iced::widget::{ self, Text, button, center, center_x, checkbox, column, keyed_column, operation, row, scrollable, text, text_input, }; use iced::window; use iced::{ Application, Center, Element, Fill, Font, Function, Preset, Program, Subscription, Task as Command, Theme, }; use serde::{Deserialize, Serialize}; use uuid::Uuid; pub fn main() -> iced::Result { #[cfg(not(target_arch = "wasm32"))] tracing_subscriber::fmt::init(); application().run() } fn application() -> Application<impl Program<Message = Message, Theme = Theme>> { iced::application(Todos::new, Todos::update, Todos::view) .subscription(Todos::subscription) .title(Todos::title) .font(Todos::ICON_FONT) .window_size((500.0, 800.0)) .presets(presets()) } #[derive(Debug)] enum Todos { Loading, Loaded(State), } #[derive(Debug, Default)] struct State { input_value: String, filter: Filter, tasks: Vec<Task>, dirty: bool, saving: bool, } #[derive(Debug, Clone)] enum Message { Loaded(Result<SavedState, LoadError>), Saved(Result<(), SaveError>), InputChanged(String), CreateTask, FilterChanged(Filter), TaskMessage(usize, TaskMessage), TabPressed { shift: bool }, ToggleFullscreen(window::Mode), } impl Todos { const ICON_FONT: &'static [u8] = include_bytes!("../fonts/icons.ttf"); fn new() -> (Self, Command<Message>) { ( Self::Loading, Command::perform(SavedState::load(), Message::Loaded), ) } fn title(&self) -> String { let dirty = match self { Todos::Loading => false, Todos::Loaded(state) => state.dirty, }; format!("Todos{} - Iced", if dirty { "*" } else { "" }) } fn update(&mut self, message: Message) -> Command<Message> { match self { Todos::Loading => { match message { Message::Loaded(Ok(state)) => { *self = Todos::Loaded(State { input_value: state.input_value, filter: state.filter, tasks: state.tasks, ..State::default() }); } Message::Loaded(Err(_)) => { *self = Todos::Loaded(State::default()); } _ => {} } operation::focus("new-task") } Todos::Loaded(state) => { let mut saved = false; let command = match message { Message::InputChanged(value) => { state.input_value = value; Command::none() } Message::CreateTask => { if !state.input_value.is_empty() { state.tasks.push(Task::new(state.input_value.clone())); state.input_value.clear(); } Command::none() } Message::FilterChanged(filter) => { state.filter = filter; Command::none() } Message::TaskMessage(i, TaskMessage::Delete) => { state.tasks.remove(i); Command::none() } Message::TaskMessage(i, task_message) => { if let Some(task) = state.tasks.get_mut(i) { let should_focus = matches!(task_message, TaskMessage::Edit); task.update(task_message); if should_focus { let id = Task::text_input_id(i); Command::batch(vec![ operation::focus(id.clone()), operation::select_all(id), ]) } else { Command::none() } } else { Command::none() } } Message::Saved(_result) => { state.saving = false; saved = true; Command::none() } Message::TabPressed { shift } => { if shift { operation::focus_previous() } else { operation::focus_next() } } Message::ToggleFullscreen(mode) => { window::latest().and_then(move |window| window::set_mode(window, mode)) } Message::Loaded(_) => Command::none(), }; if !saved { state.dirty = true; } let save = if state.dirty && !state.saving { state.dirty = false; state.saving = true; Command::perform( SavedState { input_value: state.input_value.clone(), filter: state.filter, tasks: state.tasks.clone(), } .save(), Message::Saved, ) } else { Command::none() }; Command::batch(vec![command, save]) } } } fn view(&self) -> Element<'_, Message> { match self { Todos::Loading => loading_message(), Todos::Loaded(State { input_value, filter, tasks, .. }) => { let title = text("todos") .width(Fill) .size(100) .style(subtle) .align_x(Center); let input = text_input("What needs to be done?", input_value) .id("new-task") .on_input(Message::InputChanged) .on_submit(Message::CreateTask) .padding(15) .size(30) .align_x(Center); let controls = view_controls(tasks, *filter); let filtered_tasks = tasks.iter().filter(|task| filter.matches(task)); let tasks: Element<_> = if filtered_tasks.count() > 0 { keyed_column( tasks .iter() .enumerate() .filter(|(_, task)| filter.matches(task)) .map(|(i, task)| { (task.id, task.view(i).map(Message::TaskMessage.with(i))) }), ) .spacing(10) .into() } else { empty_message(match filter { Filter::All => "You have not created a task yet...", Filter::Active => "All your tasks are done! :D", Filter::Completed => "You have not completed a task yet...", }) }; let content = column![title, input, controls, tasks] .spacing(20) .max_width(800); scrollable(center_x(content).padding(40)).into() } } } fn subscription(&self) -> Subscription<Message> { use keyboard::key; keyboard::listen().filter_map(|event| match event { keyboard::Event::KeyPressed { key: keyboard::Key::Named(key), modifiers, .. } => match (key, modifiers) { (key::Named::Tab, _) => Some(Message::TabPressed { shift: modifiers.shift(), }), (key::Named::ArrowUp, keyboard::Modifiers::SHIFT) => { Some(Message::ToggleFullscreen(window::Mode::Fullscreen)) } (key::Named::ArrowDown, keyboard::Modifiers::SHIFT) => { Some(Message::ToggleFullscreen(window::Mode::Windowed)) } _ => None, }, _ => None, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] struct Task { #[serde(default = "Uuid::new_v4")] id: Uuid, description: String, completed: bool, #[serde(skip)] state: TaskState, } #[derive(Debug, Clone, Default)] pub enum TaskState { #[default] Idle, Editing, } #[derive(Debug, Clone)] pub enum TaskMessage { Completed(bool), Edit, DescriptionEdited(String), FinishEdition, Delete, } impl Task { fn text_input_id(i: usize) -> widget::Id { widget::Id::from(format!("task-{i}")) } fn new(description: String) -> Self { Task { id: Uuid::new_v4(), description, completed: false, state: TaskState::Idle, } } fn update(&mut self, message: TaskMessage) { match message { TaskMessage::Completed(completed) => { self.completed = completed; } TaskMessage::Edit => { self.state = TaskState::Editing; } TaskMessage::DescriptionEdited(new_description) => { self.description = new_description; } TaskMessage::FinishEdition => { if !self.description.is_empty() { self.state = TaskState::Idle; } } TaskMessage::Delete => {} } } fn view(&self, i: usize) -> Element<'_, TaskMessage> { match &self.state { TaskState::Idle => { let checkbox = checkbox(self.completed) .label(&self.description) .on_toggle(TaskMessage::Completed) .width(Fill) .size(17) .text_shaping(text::Shaping::Advanced); row![ checkbox, button(edit_icon()) .on_press(TaskMessage::Edit) .padding(10) .style(button::text), ] .spacing(20) .align_y(Center) .into() } TaskState::Editing => { let text_input = text_input("Describe your task...", &self.description) .id(Self::text_input_id(i)) .on_input(TaskMessage::DescriptionEdited) .on_submit(TaskMessage::FinishEdition) .padding(10); row![ text_input, button(row![delete_icon(), "Delete"].spacing(10).align_y(Center)) .on_press(TaskMessage::Delete) .padding(10) .style(button::danger) ] .spacing(20) .align_y(Center) .into() } } } } fn view_controls(tasks: &[Task], current_filter: Filter) -> Element<'_, Message> { let tasks_left = tasks.iter().filter(|task| !task.completed).count(); let filter_button = |label, filter, current_filter| { let label = text(label); let button = button(label).style(if filter == current_filter { button::primary } else { button::text }); button.on_press(Message::FilterChanged(filter)).padding(8) }; row![ text!( "{tasks_left} {} left", if tasks_left == 1 { "task" } else { "tasks" } ) .width(Fill), row![ filter_button("All", Filter::All, current_filter), filter_button("Active", Filter::Active, current_filter), filter_button("Completed", Filter::Completed, current_filter,), ] .spacing(10) ] .spacing(20) .align_y(Center) .into() } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum Filter { #[default] All, Active, Completed, } impl Filter { fn matches(self, task: &Task) -> bool { match self { Filter::All => true, Filter::Active => !task.completed, Filter::Completed => task.completed, } } } fn loading_message<'a>() -> Element<'a, Message> { center(text("Loading...").width(Fill).align_x(Center).size(50)).into() } fn empty_message(message: &str) -> Element<'_, Message> { center( text(message) .width(Fill) .size(25) .align_x(Center) .style(subtle), ) .height(200) .into() } // Fonts fn icon(unicode: char) -> Text<'static> { text(unicode.to_string()) .font(Font::with_name("Iced-Todos-Icons")) .width(20) .align_x(Center) .shaping(text::Shaping::Basic) } fn edit_icon() -> Text<'static> { icon('\u{F303}') } fn delete_icon() -> Text<'static> { icon('\u{F1F8}') } fn subtle(theme: &Theme) -> text::Style { text::Style { color: Some(theme.extended_palette().background.strongest.color), } } // Persistence #[derive(Debug, Clone, Serialize, Deserialize)] struct SavedState { input_value: String, filter: Filter, tasks: Vec<Task>, } #[derive(Debug, Clone)] enum LoadError { File, Format, } #[derive(Debug, Clone)] enum SaveError { Write, Format, } #[cfg(not(target_arch = "wasm32"))] impl SavedState { fn path() -> std::path::PathBuf { let mut path = if let Some(project_dirs) = directories::ProjectDirs::from("rs", "Iced", "Todos") { project_dirs.data_dir().into() } else { std::env::current_dir().unwrap_or_default() }; path.push("todos.json"); path } async fn load() -> Result<SavedState, LoadError> { let contents = tokio::fs::read_to_string(Self::path()) .await .map_err(|_| LoadError::File)?; serde_json::from_str(&contents).map_err(|_| LoadError::Format) } async fn save(self) -> Result<(), SaveError> { use iced::time::milliseconds; let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; let path = Self::path(); if let Some(dir) = path.parent() { tokio::fs::create_dir_all(dir) .await .map_err(|_| SaveError::Write)?; } { tokio::fs::write(path, json.as_bytes()) .await .map_err(|_| SaveError::Write)?; } // This is a simple way to save at most twice every second tokio::time::sleep(milliseconds(500)).await; Ok(()) } } #[cfg(target_arch = "wasm32")] impl SavedState { fn storage() -> Option<web_sys::Storage> { let window = web_sys::window()?; window.local_storage().ok()? } async fn load() -> Result<SavedState, LoadError> { let storage = Self::storage().ok_or(LoadError::File)?; let contents = storage .get_item("state") .map_err(|_| LoadError::File)? .ok_or(LoadError::File)?; serde_json::from_str(&contents).map_err(|_| LoadError::Format) } async fn save(self) -> Result<(), SaveError> { let storage = Self::storage().ok_or(SaveError::Write)?; let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; storage .set_item("state", &json) .map_err(|_| SaveError::Write)?; let _ = wasmtimer::tokio::sleep(std::time::Duration::from_secs(2)).await; Ok(()) } } fn presets() -> impl IntoIterator<Item = Preset<Todos, Message>> { [ Preset::new("Empty", || { (Todos::Loaded(State::default()), Command::none()) }), Preset::new("Carl Sagan", || { ( Todos::Loaded(State { input_value: "Make an apple pie".to_owned(), filter: Filter::All, tasks: vec![Task { id: Uuid::new_v4(), description: "Create the universe".to_owned(), completed: false, state: TaskState::Idle, }], dirty: false, saving: false, }), Command::none(), ) }), ] .into_iter() } #[cfg(test)] mod tests { use super::*; use iced::{Settings, Theme}; use iced_test::selector::id; use iced_test::{Error, Simulator}; fn simulator(todos: &Todos) -> Simulator<'_, Message> { Simulator::with_settings( Settings { fonts: vec![Todos::ICON_FONT.into()], ..Settings::default() }, todos.view(), ) } #[test] #[ignore] fn it_creates_a_new_task() -> Result<(), Error> { let (mut todos, _command) = Todos::new(); let _command = todos.update(Message::Loaded(Err(LoadError::File))); let mut ui = simulator(&todos); let _input = ui.click(id("new-task"))?; let _ = ui.typewrite("Create the universe"); let _ = ui.tap_key(keyboard::key::Named::Enter); for message in ui.into_messages() { let _command = todos.update(message); } let mut ui = simulator(&todos); let _ = ui.find("Create the universe")?; let snapshot = ui.snapshot(&Theme::Dark)?; assert!( snapshot.matches_hash("snapshots/creates_a_new_task")?, "snapshots should match!" ); Ok(()) } #[test] #[ignore] fn it_passes_the_ice_tests() -> Result<(), Error> { iced_test::run( application(), format!("{}/tests", env!("CARGO_MANIFEST_DIR")), ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/gradient/src/main.rs
examples/gradient/src/main.rs
use iced::gradient; use iced::theme; use iced::widget::{checkbox, column, container, row, slider, space, text}; use iced::{Center, Color, Element, Fill, Radians, Theme, color}; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); iced::application(Gradient::default, Gradient::update, Gradient::view) .style(Gradient::style) .transparent(true) .run() } #[derive(Debug, Clone, Copy)] struct Gradient { start: Color, end: Color, angle: Radians, transparent: bool, } #[derive(Debug, Clone, Copy)] enum Message { StartChanged(Color), EndChanged(Color), AngleChanged(Radians), TransparentToggled(bool), } impl Gradient { fn new() -> Self { Self { start: Color::WHITE, end: color!(0x0000ff), angle: Radians(0.0), transparent: false, } } fn update(&mut self, message: Message) { match message { Message::StartChanged(color) => self.start = color, Message::EndChanged(color) => self.end = color, Message::AngleChanged(angle) => self.angle = angle, Message::TransparentToggled(transparent) => { self.transparent = transparent; } } } fn view(&self) -> Element<'_, Message> { let Self { start, end, angle, transparent, } = *self; let gradient_box = container(space()) .style(move |_theme| { let gradient = gradient::Linear::new(angle) .add_stop(0.0, start) .add_stop(1.0, end); gradient.into() }) .width(Fill) .height(Fill); let angle_picker = row![ text("Angle").width(64), slider(Radians::RANGE, self.angle, Message::AngleChanged).step(0.01) ] .spacing(8) .padding(8) .align_y(Center); let transparency_toggle = iced::widget::Container::new( checkbox(transparent) .label("Transparent window") .on_toggle(Message::TransparentToggled), ) .padding(8); column![ color_picker("Start", self.start).map(Message::StartChanged), color_picker("End", self.end).map(Message::EndChanged), angle_picker, transparency_toggle, gradient_box, ] .into() } fn style(&self, theme: &Theme) -> theme::Style { if self.transparent { theme::Style { background_color: Color::TRANSPARENT, text_color: theme.palette().text, } } else { theme::default(theme) } } } impl Default for Gradient { fn default() -> Self { Self::new() } } fn color_picker(label: &str, color: Color) -> Element<'_, Color> { row![ text(label).width(64), slider(0.0..=1.0, color.r, move |r| { Color { r, ..color } }).step(0.01), slider(0.0..=1.0, color.g, move |g| { Color { g, ..color } }).step(0.01), slider(0.0..=1.0, color.b, move |b| { Color { b, ..color } }).step(0.01), slider(0.0..=1.0, color.a, move |a| { Color { a, ..color } }).step(0.01), ] .spacing(8) .padding(8) .align_y(Center) .into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/markdown/build.rs
examples/markdown/build.rs
pub fn main() { // println!("cargo::rerun-if-changed=fonts/markdown-icons.toml"); // iced_fontello::build("fonts/markdown-icons.toml") // .expect("Build icons font"); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/markdown/src/icon.rs
examples/markdown/src/icon.rs
// Generated automatically by iced_fontello at build time. // Do not edit manually. Source: ../fonts/markdown-icons.toml // dcd2f0c969d603e2ee9237a4b70fa86b1a6e84d86f4689046d8fdd10440b06b9 use iced::Font; use iced::widget::{Text, text}; pub const FONT: &[u8] = include_bytes!("../fonts/markdown-icons.ttf"); pub fn copy<'a>() -> Text<'a> { icon("\u{F0C5}") } fn icon(codepoint: &str) -> Text<'_> { text(codepoint).font(Font::with_name("markdown-icons")) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/markdown/src/main.rs
examples/markdown/src/main.rs
mod icon; use iced::animation; use iced::clipboard; use iced::highlighter; use iced::time::{self, Instant, milliseconds}; use iced::widget::{ button, center_x, container, hover, image, markdown, operation, right, row, scrollable, sensor, space, text_editor, toggler, }; use iced::window; use iced::{Animation, Element, Fill, Font, Function, Subscription, Task, Theme}; use std::collections::HashMap; use std::io; use std::sync::Arc; pub fn main() -> iced::Result { iced::application::timed( Markdown::new, Markdown::update, Markdown::subscription, Markdown::view, ) .font(icon::FONT) .theme(Markdown::theme) .run() } struct Markdown { content: markdown::Content, raw: text_editor::Content, images: HashMap<markdown::Uri, Image>, mode: Mode, theme: Theme, now: Instant, } enum Mode { Preview, Stream { pending: String }, } enum Image { Loading, Ready { handle: image::Handle, fade_in: Animation<bool>, }, #[allow(dead_code)] Errored(Error), } #[derive(Debug, Clone)] enum Message { Edit(text_editor::Action), Copy(String), LinkClicked(markdown::Uri), ImageShown(markdown::Uri), ImageDownloaded(markdown::Uri, Result<image::Handle, Error>), ToggleStream(bool), NextToken, Tick, } impl Markdown { fn new() -> (Self, Task<Message>) { const INITIAL_CONTENT: &str = include_str!("../overview.md"); ( Self { content: markdown::Content::parse(INITIAL_CONTENT), raw: text_editor::Content::with_text(INITIAL_CONTENT), images: HashMap::new(), mode: Mode::Preview, theme: Theme::TokyoNight, now: Instant::now(), }, operation::focus_next(), ) } fn update(&mut self, message: Message, now: Instant) -> Task<Message> { self.now = now; match message { Message::Edit(action) => { let is_edit = action.is_edit(); self.raw.perform(action); if is_edit { self.content = markdown::Content::parse(&self.raw.text()); self.mode = Mode::Preview; } Task::none() } Message::Copy(content) => clipboard::write(content), Message::LinkClicked(link) => { let _ = webbrowser::open(&link); Task::none() } Message::ImageShown(uri) => { if self.images.contains_key(&uri) { return Task::none(); } let _ = self.images.insert(uri.clone(), Image::Loading); Task::perform( download_image(uri.clone()), Message::ImageDownloaded.with(uri), ) } Message::ImageDownloaded(url, result) => { let _ = self.images.insert( url, result .map(|handle| Image::Ready { handle, fade_in: Animation::new(false) .quick() .easing(animation::Easing::EaseInOut) .go(true, self.now), }) .unwrap_or_else(Image::Errored), ); Task::none() } Message::ToggleStream(enable_stream) => { if enable_stream { self.content = markdown::Content::new(); self.mode = Mode::Stream { pending: self.raw.text(), }; operation::snap_to_end("preview") } else { self.mode = Mode::Preview; Task::none() } } Message::NextToken => { match &mut self.mode { Mode::Preview => {} Mode::Stream { pending } => { if pending.is_empty() { self.mode = Mode::Preview; } else { let mut tokens = pending.split(' '); if let Some(token) = tokens.next() { self.content.push_str(&format!("{token} ")); } *pending = tokens.collect::<Vec<_>>().join(" "); } } } Task::none() } Message::Tick => Task::none(), } } fn view(&self) -> Element<'_, Message> { let editor = text_editor(&self.raw) .placeholder("Type your Markdown here...") .on_action(Message::Edit) .height(Fill) .padding(10) .font(Font::MONOSPACE) .highlight("markdown", highlighter::Theme::Base16Ocean); let preview = markdown::view_with( self.content.items(), &self.theme, &CustomViewer { images: &self.images, now: self.now, }, ); row![ editor, hover( scrollable(preview) .spacing(10) .width(Fill) .height(Fill) .id("preview"), right( toggler(matches!(self.mode, Mode::Stream { .. })) .label("Stream") .on_toggle(Message::ToggleStream) ) .padding([0, 20]) ) ] .spacing(10) .padding(10) .into() } fn theme(&self) -> Theme { self.theme.clone() } fn subscription(&self) -> Subscription<Message> { let listen_stream = match self.mode { Mode::Preview => Subscription::none(), Mode::Stream { .. } => time::every(milliseconds(10)).map(|_| Message::NextToken), }; let animate = { let is_animating = self.images.values().any(|image| match image { Image::Ready { fade_in, .. } => fade_in.is_animating(self.now), _ => false, }); if is_animating { window::frames().map(|_| Message::Tick) } else { Subscription::none() } }; Subscription::batch([listen_stream, animate]) } } struct CustomViewer<'a> { images: &'a HashMap<markdown::Uri, Image>, now: Instant, } impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> { fn on_link_click(url: markdown::Uri) -> Message { Message::LinkClicked(url) } fn image( &self, _settings: markdown::Settings, url: &'a markdown::Uri, _title: &'a str, _alt: &markdown::Text, ) -> Element<'a, Message> { if let Some(Image::Ready { handle, fade_in }) = self.images.get(url) { center_x( image(handle) .opacity(fade_in.interpolate(0.0, 1.0, self.now)) .scale(fade_in.interpolate(1.2, 1.0, self.now)), ) .into() } else { sensor(space()) .key_ref(url.as_str()) .delay(milliseconds(500)) .on_show(|_size| Message::ImageShown(url.clone())) .into() } } fn code_block( &self, settings: markdown::Settings, _language: Option<&'a str>, code: &'a str, lines: &'a [markdown::Text], ) -> Element<'a, Message> { let code_block = markdown::code_block(settings, lines, Message::LinkClicked); let copy = button(icon::copy().size(12)) .padding(2) .on_press_with(|| Message::Copy(code.to_owned())) .style(button::text); hover( code_block, right(container(copy).style(container::dark)).padding(settings.spacing / 2), ) } } async fn download_image(uri: markdown::Uri) -> Result<image::Handle, Error> { use std::io; use tokio::task; use url::Url; let bytes = match Url::parse(&uri) { Ok(url) if url.scheme() == "http" || url.scheme() == "https" => { println!("Trying to download image: {url}"); let client = reqwest::Client::new(); client .get(url) .send() .await? .error_for_status()? .bytes() .await? } _ => { return Err(Error::IOFailed(Arc::new(io::Error::other(format!( "unsupported uri: {uri}" ))))); } }; let image = task::spawn_blocking(move || { Ok::<_, Error>( ::image::ImageReader::new(io::Cursor::new(bytes)) .with_guessed_format()? .decode()? .to_rgba8(), ) }) .await??; Ok(image::Handle::from_rgba( image.width(), image.height(), image.into_raw(), )) } #[derive(Debug, Clone)] pub enum Error { RequestFailed(Arc<reqwest::Error>), IOFailed(Arc<io::Error>), JoinFailed(Arc<tokio::task::JoinError>), ImageDecodingFailed(Arc<::image::ImageError>), } impl From<reqwest::Error> for Error { fn from(error: reqwest::Error) -> Self { Self::RequestFailed(Arc::new(error)) } } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Self::IOFailed(Arc::new(error)) } } impl From<tokio::task::JoinError> for Error { fn from(error: tokio::task::JoinError) -> Self { Self::JoinFailed(Arc::new(error)) } } impl From<::image::ImageError> for Error { fn from(error: ::image::ImageError) -> Self { Self::ImageDecodingFailed(Arc::new(error)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/websocket/src/echo.rs
examples/websocket/src/echo.rs
pub mod server; use iced::futures; use iced::task::{Never, Sipper, sipper}; use iced::widget::text; use futures::channel::mpsc; use futures::sink::SinkExt; use futures::stream::StreamExt; use async_tungstenite::tungstenite; use std::fmt; pub fn connect() -> impl Sipper<Never, Event> { sipper(async |mut output| { loop { const ECHO_SERVER: &str = "ws://127.0.0.1:3030"; let (mut websocket, mut input) = match async_tungstenite::tokio::connect_async(ECHO_SERVER).await { Ok((websocket, _)) => { let (sender, receiver) = mpsc::channel(100); output.send(Event::Connected(Connection(sender))).await; (websocket.fuse(), receiver) } Err(_) => { tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; continue; } }; loop { futures::select! { received = websocket.select_next_some() => { match received { Ok(tungstenite::Message::Text(message)) => { output.send(Event::MessageReceived(Message::User(message))).await; } Err(_) => { output.send(Event::Disconnected).await; break; } Ok(_) => {}, } } message = input.select_next_some() => { let result = websocket.send(tungstenite::Message::Text(message.to_string())).await; if result.is_err() { output.send(Event::Disconnected).await; } } } } } }) } #[derive(Debug, Clone)] pub enum Event { Connected(Connection), Disconnected, MessageReceived(Message), } #[derive(Debug, Clone)] pub struct Connection(mpsc::Sender<Message>); impl Connection { pub fn send(&mut self, message: Message) { self.0 .try_send(message) .expect("Send message to echo server"); } } #[derive(Debug, Clone)] pub enum Message { Connected, Disconnected, User(String), } impl Message { pub fn new(message: &str) -> Option<Self> { if message.is_empty() { None } else { Some(Self::User(message.to_string())) } } pub fn connected() -> Self { Message::Connected } pub fn disconnected() -> Self { Message::Disconnected } pub fn as_str(&self) -> &str { match self { Message::Connected => "Connected successfully!", Message::Disconnected => "Connection lost... Retrying...", Message::User(message) => message.as_str(), } } } impl fmt::Display for Message { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } impl<'a> text::IntoFragment<'a> for &'a Message { fn into_fragment(self) -> text::Fragment<'a> { text::Fragment::Borrowed(self.as_str()) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/websocket/src/main.rs
examples/websocket/src/main.rs
mod echo; use iced::widget::{button, center, column, operation, row, scrollable, text, text_input}; use iced::{Center, Element, Fill, Subscription, Task, color}; pub fn main() -> iced::Result { iced::application(WebSocket::new, WebSocket::update, WebSocket::view) .subscription(WebSocket::subscription) .run() } struct WebSocket { messages: Vec<echo::Message>, new_message: String, state: State, } #[derive(Debug, Clone)] enum Message { NewMessageChanged(String), Send(echo::Message), Echo(echo::Event), } impl WebSocket { fn new() -> (Self, Task<Message>) { ( Self { messages: Vec::new(), new_message: String::new(), state: State::Disconnected, }, Task::batch([ Task::future(echo::server::run()).discard(), operation::focus_next(), ]), ) } fn update(&mut self, message: Message) -> Task<Message> { match message { Message::NewMessageChanged(new_message) => { self.new_message = new_message; Task::none() } Message::Send(message) => match &mut self.state { State::Connected(connection) => { self.new_message.clear(); connection.send(message); Task::none() } State::Disconnected => Task::none(), }, Message::Echo(event) => match event { echo::Event::Connected(connection) => { self.state = State::Connected(connection); self.messages.push(echo::Message::connected()); Task::none() } echo::Event::Disconnected => { self.state = State::Disconnected; self.messages.push(echo::Message::disconnected()); Task::none() } echo::Event::MessageReceived(message) => { self.messages.push(message); operation::snap_to_end(MESSAGE_LOG) } }, } } fn subscription(&self) -> Subscription<Message> { Subscription::run(echo::connect).map(Message::Echo) } fn view(&self) -> Element<'_, Message> { let message_log: Element<_> = if self.messages.is_empty() { center(text("Your messages will appear here...").color(color!(0x888888))).into() } else { scrollable(column(self.messages.iter().map(text).map(Element::from)).spacing(10)) .id(MESSAGE_LOG) .height(Fill) .spacing(10) .into() }; let new_message_input = { let mut input = text_input("Type a message...", &self.new_message) .on_input(Message::NewMessageChanged) .padding(10); let mut button = button(text("Send").height(40).align_y(Center)).padding([0, 20]); if matches!(self.state, State::Connected(_)) && let Some(message) = echo::Message::new(&self.new_message) { input = input.on_submit(Message::Send(message.clone())); button = button.on_press(Message::Send(message)); } row![input, button].spacing(10).align_y(Center) }; column![message_log, new_message_input] .height(Fill) .padding(20) .spacing(10) .into() } } enum State { Disconnected, Connected(echo::Connection), } const MESSAGE_LOG: &str = "message_log";
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/examples/websocket/src/echo/server.rs
examples/websocket/src/echo/server.rs
use iced::futures; use futures::channel::mpsc; use futures::{SinkExt, StreamExt}; use warp::Filter; use warp::ws::WebSocket; // Basic WebSocket echo server adapted from: // https://github.com/seanmonstar/warp/blob/3ff2eaf41eb5ac9321620e5a6434d5b5ec6f313f/examples/websockets_chat.rs // // Copyright (c) 2018-2020 Sean McArthur // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. pub async fn run() { let routes = warp::path::end() .and(warp::ws()) .map(|ws: warp::ws::Ws| ws.on_upgrade(user_connected)); warp::serve(routes).run(([127, 0, 0, 1], 3030)).await; } async fn user_connected(ws: WebSocket) { let (mut user_ws_tx, mut user_ws_rx) = ws.split(); let (mut tx, mut rx) = mpsc::unbounded(); tokio::task::spawn(async move { while let Some(message) = rx.next().await { user_ws_tx.send(message).await.unwrap_or_else(|e| { eprintln!("websocket send error: {e}"); }); } }); while let Some(result) = user_ws_rx.next().await { let Ok(msg) = result else { break }; let _ = tx.send(msg).await; } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/futures/src/stream.rs
futures/src/stream.rs
//! Create asynchronous streams of data. use futures::channel::mpsc; use futures::stream::{self, Stream, StreamExt}; /// Creates a new [`Stream`] that produces the items sent from a [`Future`] /// to the [`mpsc::Sender`] provided to the closure. /// /// This is a more ergonomic [`stream::unfold`], which allows you to go /// from the "world of futures" to the "world of streams" by simply looping /// and publishing to an async channel from inside a [`Future`]. pub fn channel<T>(size: usize, f: impl AsyncFnOnce(mpsc::Sender<T>)) -> impl Stream<Item = T> { let (sender, receiver) = mpsc::channel(size); let runner = stream::once(f(sender)).filter_map(|_| async { None }); stream::select(receiver, runner) } /// Creates a new [`Stream`] that produces the items sent from a [`Future`] /// that can fail to the [`mpsc::Sender`] provided to the closure. pub fn try_channel<T, E>( size: usize, f: impl AsyncFnOnce(mpsc::Sender<T>) -> Result<(), E>, ) -> impl Stream<Item = Result<T, E>> { let (sender, receiver) = mpsc::channel(size); let runner = stream::once(f(sender)).filter_map(|result| async { match result { Ok(()) => None, Err(error) => Some(Err(error)), } }); stream::select(receiver.map(Ok), runner) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false