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/tester/src/lib.rs
tester/src/lib.rs
//! Record, edit, and run end-to-end tests for your iced applications. pub use iced_test as test; pub use iced_test::core; pub use iced_test::program; pub use iced_test::runtime; pub use iced_test::runtime::futures; pub use iced_widget as widget; mod icon; mod recorder; use recorder::recorder; use crate::core::Alignment::Center; use crate::core::Length::Fill; use crate::core::alignment::Horizontal::Right; use crate::core::border; use crate::core::mouse; use crate::core::theme; use crate::core::window; use crate::core::{Color, Element, Font, Settings, Size, Theme}; use crate::futures::futures::channel::mpsc; use crate::program::Program; use crate::runtime::task::{self, Task}; use crate::test::emulator; use crate::test::ice; use crate::test::instruction; use crate::test::{Emulator, Ice, Instruction}; use crate::widget::{ button, center, column, combo_box, container, pick_list, row, rule, scrollable, slider, space, stack, text, text_editor, themer, }; use std::ops::RangeInclusive; /// Attaches a [`Tester`] to the given [`Program`]. pub fn attach<P: Program + 'static>(program: P) -> Attach<P> { Attach { program } } /// A [`Program`] with a [`Tester`] attached to it. #[derive(Debug)] pub struct Attach<P> { /// The original [`Program`] attached to the [`Tester`]. pub program: P, } impl<P> Program for Attach<P> where P: Program + 'static, { type State = Tester<P>; type Message = Message<P>; type Theme = Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { let mut settings = self.program.settings(); settings.fonts.push(icon::FONT.into()); settings } fn window(&self) -> Option<window::Settings> { Some( self.program .window() .map(|window| window::Settings { size: window.size + Size::new(300.0, 80.0), ..window }) .unwrap_or_default(), ) } fn boot(&self) -> (Self::State, Task<Self::Message>) { (Tester::new(&self.program), Task::none()) } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { state.tick(&self.program, message.0).map(Message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { state.view(&self.program, window).map(Message) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Theme> { state .theme(&self.program, window) .as_ref() .and_then(theme::Base::palette) .map(|palette| Theme::custom("Tester", palette)) } } /// A tester decorates a [`Program`] definition and attaches a test recorder on top. /// /// It can be used to both record and play [`Ice`] tests. pub struct Tester<P: Program> { viewport: Size, mode: emulator::Mode, presets: combo_box::State<String>, preset: Option<String>, instructions: Vec<Instruction>, state: State<P>, edit: Option<text_editor::Content<P::Renderer>>, } enum State<P: Program> { Empty, Idle { state: P::State, }, Recording { emulator: Emulator<P>, }, Asserting { state: P::State, window: window::Id, last_interaction: Option<instruction::Interaction>, }, Playing { emulator: Emulator<P>, current: usize, outcome: Outcome, }, } enum Outcome { Running, Failed, Success, } /// The message of a [`Tester`]. pub struct Message<P: Program>(Tick<P>); #[derive(Debug, Clone)] enum Event { ViewportChanged(Size), ModeSelected(emulator::Mode), PresetSelected(String), Record, Stop, Play, Import, Export, Imported(Result<Ice, ice::ParseError>), Edit, Edited(text_editor::Action), Confirm, } enum Tick<P: Program> { Tester(Event), Program(P::Message), Emulator(emulator::Event<P>), Record(instruction::Interaction), Assert(instruction::Interaction), } impl<P: Program + 'static> Tester<P> { fn new(program: &P) -> Self { let (state, _) = program.boot(); let window = program.window().unwrap_or_default(); Self { mode: emulator::Mode::default(), viewport: window.size, presets: combo_box::State::new( program .presets() .iter() .map(program::Preset::name) .map(str::to_owned) .collect(), ), preset: None, instructions: Vec::new(), state: State::Idle { state }, edit: None, } } fn is_busy(&self) -> bool { matches!( self.state, State::Recording { .. } | State::Playing { outcome: Outcome::Running, .. } ) } fn update(&mut self, program: &P, event: Event) -> Task<Tick<P>> { match event { Event::ViewportChanged(viewport) => { self.viewport = viewport; Task::none() } Event::ModeSelected(mode) => { self.mode = mode; Task::none() } Event::PresetSelected(preset) => { self.preset = Some(preset); let (state, _) = self .preset(program) .map(program::Preset::boot) .unwrap_or_else(|| program.boot()); self.state = State::Idle { state }; Task::none() } Event::Record => { self.edit = None; self.instructions.clear(); let (sender, receiver) = mpsc::channel(1); let emulator = Emulator::with_preset( sender, program, self.mode, self.viewport, self.preset(program), ); self.state = State::Recording { emulator }; Task::run(receiver, Tick::Emulator) } Event::Stop => { let State::Recording { emulator } = std::mem::replace(&mut self.state, State::Empty) else { return Task::none(); }; while let Some(Instruction::Interact(instruction::Interaction::Mouse( instruction::Mouse::Move(_), ))) = self.instructions.last() { let _ = self.instructions.pop(); } let (state, window) = emulator.into_state(); self.state = State::Asserting { state, window, last_interaction: None, }; Task::none() } Event::Play => { self.confirm(); let (sender, receiver) = mpsc::channel(1); let emulator = Emulator::with_preset( sender, program, self.mode, self.viewport, self.preset(program), ); self.state = State::Playing { emulator, current: 0, outcome: Outcome::Running, }; Task::run(receiver, Tick::Emulator) } Event::Import => { use std::fs; let import = rfd::AsyncFileDialog::new() .add_filter("ice", &["ice"]) .pick_file(); Task::future(import) .and_then(|file| { task::blocking(move |mut sender| { let _ = sender.try_send(Ice::parse( &fs::read_to_string(file.path()).unwrap_or_default(), )); }) }) .map(Event::Imported) .map(Tick::Tester) } Event::Export => { use std::fs; use std::thread; self.confirm(); let ice = Ice { viewport: self.viewport, mode: self.mode, preset: self.preset.clone(), instructions: self.instructions.clone(), }; let export = rfd::AsyncFileDialog::new() .add_filter("ice", &["ice"]) .save_file(); Task::future(async move { let Some(file) = export.await else { return; }; let _ = thread::spawn(move || fs::write(file.path(), ice.to_string())); }) .discard() } Event::Imported(Ok(ice)) => { self.viewport = ice.viewport; self.mode = ice.mode; self.preset = ice.preset; self.instructions = ice.instructions; self.edit = None; let (state, _) = self .preset(program) .map(program::Preset::boot) .unwrap_or_else(|| program.boot()); self.state = State::Idle { state }; Task::none() } Event::Edit => { if self.is_busy() { return Task::none(); } self.edit = Some(text_editor::Content::with_text( &self .instructions .iter() .map(Instruction::to_string) .collect::<Vec<_>>() .join("\n"), )); Task::none() } Event::Edited(action) => { if let Some(edit) = &mut self.edit { edit.perform(action); } Task::none() } Event::Confirm => { self.confirm(); Task::none() } Event::Imported(Err(error)) => { log::error!("{error}"); Task::none() } } } fn confirm(&mut self) { let Some(edit) = &mut self.edit else { return; }; self.instructions = edit .lines() .filter(|line| !line.text.trim().is_empty()) .filter_map(|line| Instruction::parse(&line.text).ok()) .collect(); self.edit = None; } fn theme(&self, program: &P, window: window::Id) -> Option<P::Theme> { match &self.state { State::Empty => None, State::Idle { state } => program.theme(state, window), State::Recording { emulator } | State::Playing { emulator, .. } => { emulator.theme(program) } State::Asserting { state, window, .. } => program.theme(state, *window), } } fn preset<'a>(&self, program: &'a P) -> Option<&'a program::Preset<P::State, P::Message>> { self.preset.as_ref().and_then(|preset| { program .presets() .iter() .find(|candidate| candidate.name() == preset) }) } fn tick(&mut self, program: &P, tick: Tick<P>) -> Task<Tick<P>> { match tick { Tick::Tester(message) => self.update(program, message), Tick::Program(message) => { let State::Recording { emulator } = &mut self.state else { return Task::none(); }; emulator.update(program, message); Task::none() } Tick::Emulator(event) => { match &mut self.state { State::Recording { emulator } => { if let emulator::Event::Action(action) = event { emulator.perform(program, action); } } State::Playing { emulator, current, outcome, } => match event { emulator::Event::Action(action) => { emulator.perform(program, action); } emulator::Event::Failed(_instruction) => { *outcome = Outcome::Failed; } emulator::Event::Ready => { *current += 1; if let Some(instruction) = self.instructions.get(*current - 1).cloned() { emulator.run(program, instruction); } if *current >= self.instructions.len() { *outcome = Outcome::Success; } } }, State::Empty | State::Idle { .. } | State::Asserting { .. } => {} } Task::none() } Tick::Record(interaction) => { let mut interaction = Some(interaction); while let Some(new_interaction) = interaction.take() { if let Some(Instruction::Interact(last_interaction)) = self.instructions.pop() { let (merged_interaction, new_interaction) = last_interaction.merge(new_interaction); if let Some(new_interaction) = new_interaction { self.instructions .push(Instruction::Interact(merged_interaction)); self.instructions .push(Instruction::Interact(new_interaction)); } else { interaction = Some(merged_interaction); } } else { self.instructions .push(Instruction::Interact(new_interaction)); } } Task::none() } Tick::Assert(interaction) => { let State::Asserting { last_interaction, .. } = &mut self.state else { return Task::none(); }; *last_interaction = if let Some(last_interaction) = last_interaction.take() { let (merged, new) = last_interaction.merge(interaction); Some(new.unwrap_or(merged)) } else { Some(interaction) }; let Some(interaction) = last_interaction.take() else { return Task::none(); }; let instruction::Interaction::Mouse(instruction::Mouse::Click { button: mouse::Button::Left, target: Some(instruction::Target::Text(text)), }) = interaction else { *last_interaction = Some(interaction); return Task::none(); }; self.instructions .push(Instruction::Expect(instruction::Expectation::Text(text))); Task::none() } } } fn view<'a>( &'a self, program: &P, window: window::Id, ) -> Element<'a, Tick<P>, Theme, P::Renderer> { let status = { let (icon, label) = match &self.state { State::Empty | State::Idle { .. } => (text(""), "Idle"), State::Recording { .. } => (icon::record(), "Recording"), State::Asserting { .. } => (icon::lightbulb(), "Asserting"), State::Playing { outcome, .. } => match outcome { Outcome::Running => (icon::play(), "Playing"), Outcome::Failed => (icon::cancel(), "Failed"), Outcome::Success => (icon::check(), "Success"), }, }; container(row![icon.size(14), label].align_y(Center).spacing(8)).style( |theme: &Theme| { let palette = theme.extended_palette(); container::Style { text_color: Some(match &self.state { State::Empty | State::Idle { .. } => palette.background.strongest.color, State::Recording { .. } => palette.danger.base.color, State::Asserting { .. } => palette.warning.base.color, State::Playing { outcome, .. } => match outcome { Outcome::Running => theme.palette().primary, Outcome::Failed => theme.palette().danger, Outcome::Success => theme.extended_palette().success.strong.color, }, }), ..container::Style::default() } }, ) }; let view = match &self.state { State::Empty => Element::from(space()), State::Idle { state } => program.view(state, window).map(Tick::Program), State::Recording { emulator } => recorder(emulator.view(program).map(Tick::Program)) .on_record(Tick::Record) .into(), State::Asserting { state, window, .. } => { recorder(program.view(state, *window).map(Tick::Program)) .on_record(Tick::Assert) .into() } State::Playing { emulator, .. } => emulator.view(program).map(Tick::Program), }; let viewport = container( scrollable( container(themer(self.theme(program, window), view)) .width(self.viewport.width) .height(self.viewport.height), ) .direction(scrollable::Direction::Both { vertical: scrollable::Scrollbar::default(), horizontal: scrollable::Scrollbar::default(), }), ) .style(|theme: &Theme| { let palette = theme.extended_palette(); container::Style { border: border::width(2.0).color(match &self.state { State::Empty | State::Idle { .. } => palette.background.strongest.color, State::Recording { .. } => palette.danger.base.color, State::Asserting { .. } => palette.warning.weak.color, State::Playing { outcome, .. } => match outcome { Outcome::Running => palette.primary.base.color, Outcome::Failed => palette.danger.strong.color, Outcome::Success => palette.success.strong.color, }, }), ..container::Style::default() } }) .padding(10); row![ center(column![status, viewport].spacing(10).align_x(Right)).padding(10), rule::vertical(1).style(rule::weak), container(self.controls().map(Tick::Tester)) .width(250) .padding(10) .style(|theme| container::Style::default() .background(theme.extended_palette().background.weakest.color)), ] .into() } fn controls(&self) -> Element<'_, Event, Theme, P::Renderer> { let viewport = column![ labeled_slider( "Width", 100.0..=2000.0, self.viewport.width, |width| Event::ViewportChanged(Size { width, ..self.viewport }), |width| format!("{width:.0}"), ), labeled_slider( "Height", 100.0..=2000.0, self.viewport.height, |height| Event::ViewportChanged(Size { height, ..self.viewport }), |height| format!("{height:.0}"), ), ] .spacing(10); let preset = combo_box( &self.presets, "Default", self.preset.as_ref(), Event::PresetSelected, ) .size(14) .width(Fill); let mode = pick_list(emulator::Mode::ALL, Some(self.mode), Event::ModeSelected) .text_size(14) .width(Fill); let player = { let instructions = if let Some(edit) = &self.edit { text_editor(edit) .size(12) .height(Fill) .font(Font::MONOSPACE) .on_action(Event::Edited) .into() } else if self.instructions.is_empty() { Element::from(center( text("No instructions recorded yet!") .size(14) .font(Font::MONOSPACE) .width(Fill) .center(), )) } else { scrollable( column( self.instructions .iter() .enumerate() .map(|(i, instruction)| { text(instruction.to_string()) .wrapping(text::Wrapping::None) // TODO: Ellipsize? .size(10) .font(Font::MONOSPACE) .style(move |theme: &Theme| text::Style { color: match &self.state { State::Playing { current, outcome, .. } => { if *current == i + 1 { Some(match outcome { Outcome::Running => theme.palette().primary, Outcome::Failed => { theme .extended_palette() .danger .strong .color } Outcome::Success => { theme .extended_palette() .success .strong .color } }) } else if *current > i + 1 { Some( theme .extended_palette() .success .strong .color, ) } else { None } } _ => None, }, }) .into() }), ) .spacing(5), ) .width(Fill) .height(Fill) .spacing(5) .into() }; let control = |icon: text::Text<'static, _, _>| { button(icon.size(14).width(Fill).height(Fill).center()) }; let play = control(icon::play()).on_press_maybe( (!matches!(self.state, State::Recording { .. }) && !self.instructions.is_empty()) .then_some(Event::Play), ); let record = if let State::Recording { .. } = &self.state { control(icon::stop()) .on_press(Event::Stop) .style(button::success) } else { control(icon::record()) .on_press_maybe((!self.is_busy()).then_some(Event::Record)) .style(button::danger) }; let import = control(icon::folder()) .on_press_maybe((!self.is_busy()).then_some(Event::Import)) .style(button::secondary); let export = control(icon::floppy()) .on_press_maybe( (!matches!(self.state, State::Recording { .. }) && !self.instructions.is_empty()) .then_some(Event::Export), ) .style(button::success); let controls = row![import, export, play, record].height(30).spacing(10); column![instructions, controls].spacing(10).align_x(Center) }; let edit = if self.is_busy() { Element::from(space::horizontal()) } else if self.edit.is_none() { button(icon::pencil().size(14)) .padding(0) .on_press(Event::Edit) .style(button::text) .into() } else { button(icon::check().size(14)) .padding(0) .on_press(Event::Confirm) .style(button::text) .into() }; column![ labeled("Viewport", viewport), labeled("Mode", mode), labeled("Preset", preset), labeled_with("Instructions", edit, player) ] .spacing(10) .into() } } fn labeled<'a, Message, Renderer>( fragment: impl text::IntoFragment<'a>, content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Renderer: program::Renderer + 'a, { column![ text(fragment).size(14).font(Font::MONOSPACE), content.into() ] .spacing(5) .into() } fn labeled_with<'a, Message, Renderer>( fragment: impl text::IntoFragment<'a>, control: impl Into<Element<'a, Message, Theme, Renderer>>, content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Renderer: program::Renderer + 'a, { column![ row![ text(fragment).size(14).font(Font::MONOSPACE), space::horizontal(), control.into() ] .spacing(5) .align_y(Center), content.into() ] .spacing(5) .into() } fn labeled_slider<'a, Message, Renderer>( label: impl text::IntoFragment<'a>, range: RangeInclusive<f32>, current: f32, on_change: impl Fn(f32) -> Message + 'a, to_string: impl Fn(&f32) -> String, ) -> Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Renderer: core::text::Renderer + 'a, { stack![ container( slider(range, current, on_change) .step(10.0) .width(Fill) .height(24) .style(|theme: &core::Theme, status| { let palette = theme.extended_palette(); slider::Style { rail: slider::Rail { backgrounds: ( match status { slider::Status::Active | slider::Status::Dragged => { palette.background.strongest.color } slider::Status::Hovered => palette.background.stronger.color, } .into(), Color::TRANSPARENT.into(), ), width: 24.0, border: border::rounded(2), }, handle: slider::Handle { shape: slider::HandleShape::Circle { radius: 0.0 }, background: Color::TRANSPARENT.into(), border_width: 0.0, border_color: Color::TRANSPARENT, }, } }) ) .style(|theme| container::Style::default() .background(theme.extended_palette().background.weak.color) .border(border::rounded(2))), row![ text(label).size(14).style(|theme: &core::Theme| { text::Style { color: Some(theme.extended_palette().background.weak.text), } }), space::horizontal(), text(to_string(&current)).size(14) ] .padding([0, 10]) .height(Fill) .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/tester/src/recorder.rs
tester/src/recorder.rs
use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::theme; use crate::core::widget; use crate::core::widget::operation; use crate::core::widget::tree; use crate::core::{ self, Clipboard, Color, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget, }; use crate::test::Selector; use crate::test::instruction::{Interaction, Mouse, Target}; use crate::test::selector; pub fn recorder<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Recorder<'a, Message, Theme, Renderer> { Recorder::new(content) } pub struct Recorder<'a, Message, Theme, Renderer> { content: Element<'a, Message, Theme, Renderer>, on_record: Option<Box<dyn Fn(Interaction) -> Message + 'a>>, has_overlay: bool, } impl<'a, Message, Theme, Renderer> Recorder<'a, Message, Theme, Renderer> { pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { content: content.into(), on_record: None, has_overlay: false, } } pub fn on_record(mut self, on_record: impl Fn(Interaction) -> Message + 'a) -> Self { self.on_record = Some(Box::new(on_record)); self } } struct State { last_hovered: Option<Rectangle>, last_hovered_overlay: Option<Rectangle>, } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Recorder<'_, Message, Theme, Renderer> where Renderer: core::Renderer, Theme: theme::Base, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State { last_hovered: None, last_hovered_overlay: None, }) } fn children(&self) -> Vec<widget::Tree> { vec![widget::Tree::new(&self.content)] } fn diff(&self, tree: &mut tree::Tree) { tree.diff_children(std::slice::from_ref(&self.content)); } fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn size_hint(&self) -> Size<Length> { self.content.as_widget().size_hint() } fn update( &mut self, tree: &mut widget::Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { if shell.is_event_captured() { return; } if !self.has_overlay && let Some(on_record) = &self.on_record { let state = tree.state.downcast_mut::<State>(); record( event, cursor, shell, layout.bounds(), &mut state.last_hovered, on_record, |operation| { self.content.as_widget_mut().operate( &mut tree.children[0], layout, renderer, operation, ); }, ); } self.content.as_widget_mut().update( &mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.content .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) } fn draw( &self, tree: &widget::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, ); let state = tree.state.downcast_ref::<State>(); let Some(last_hovered) = &state.last_hovered else { return; }; renderer.with_layer(*viewport, |renderer| { renderer.fill_quad( renderer::Quad { bounds: *last_hovered, ..renderer::Quad::default() }, highlight(theme).scale_alpha(0.7), ); }); } fn mouse_interaction( &self, tree: &widget::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 operate( &mut self, tree: &mut widget::Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content .as_widget_mut() .operate(&mut tree.children[0], layout, renderer, operation); } fn overlay<'a>( &'a mut self, tree: &'a mut widget::Tree, layout: Layout<'a>, renderer: &Renderer, _viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { self.has_overlay = false; self.content .as_widget_mut() .overlay( &mut tree.children[0], layout, renderer, &layout.bounds(), translation, ) .map(|raw| { self.has_overlay = true; let state = tree.state.downcast_mut::<State>(); overlay::Element::new(Box::new(Overlay { raw, bounds: layout.bounds(), last_hovered: &mut state.last_hovered_overlay, on_record: self.on_record.as_deref(), })) }) } } impl<'a, Message, Theme, Renderer> From<Recorder<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: theme::Base + 'a, Renderer: core::Renderer + 'a, { fn from(recorder: Recorder<'a, Message, Theme, Renderer>) -> Self { Element::new(recorder) } } struct Overlay<'a, Message, Theme, Renderer> { raw: overlay::Element<'a, Message, Theme, Renderer>, bounds: Rectangle, last_hovered: &'a mut Option<Rectangle>, on_record: Option<&'a dyn Fn(Interaction) -> Message>, } impl<'a, Message, Theme, Renderer> core::Overlay<Message, Theme, Renderer> for Overlay<'a, Message, Theme, Renderer> where Renderer: core::Renderer + 'a, Theme: theme::Base + 'a, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { self.raw.as_overlay_mut().layout(renderer, bounds) } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { self.raw .as_overlay() .draw(renderer, theme, style, layout, cursor); let Some(last_hovered) = &self.last_hovered else { return; }; renderer.with_layer(self.bounds, |renderer| { renderer.fill_quad( renderer::Quad { bounds: *last_hovered, ..renderer::Quad::default() }, highlight(theme).scale_alpha(0.7), ); }); } fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.raw .as_overlay_mut() .operate(layout, renderer, operation); } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { if shell.is_event_captured() { return; } if let Some(on_event) = &self.on_record { record( event, cursor, shell, self.bounds, self.last_hovered, on_event, |operation| { self.raw .as_overlay_mut() .operate(layout, renderer, operation); }, ); } self.raw .as_overlay_mut() .update(event, layout, cursor, renderer, clipboard, shell); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.raw .as_overlay() .mouse_interaction(layout, cursor, renderer) } fn overlay<'b>( &'b mut self, layout: Layout<'b>, renderer: &Renderer, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.raw .as_overlay_mut() .overlay(layout, renderer) .map(|raw| { overlay::Element::new(Box::new(Overlay { raw, bounds: self.bounds, last_hovered: self.last_hovered, on_record: self.on_record, })) }) } fn index(&self) -> f32 { self.raw.as_overlay().index() } } fn record<Message>( event: &Event, cursor: mouse::Cursor, shell: &mut Shell<'_, Message>, bounds: Rectangle, last_hovered: &mut Option<Rectangle>, on_record: impl Fn(Interaction) -> Message, operate: impl FnMut(&mut dyn widget::Operation), ) { if let Event::Mouse(_) = event && !cursor.is_over(bounds) { return; } let interaction = if let Event::Mouse(mouse::Event::CursorMoved { position }) = event { Interaction::from_event(&Event::Mouse(mouse::Event::CursorMoved { position: *position - (bounds.position() - Point::ORIGIN), })) } else { Interaction::from_event(event) }; let Some(mut interaction) = interaction else { return; }; let Interaction::Mouse( Mouse::Move(target) | Mouse::Press { target: Some(target), .. } | Mouse::Release { target: Some(target), .. } | Mouse::Click { target: Some(target), .. }, ) = &mut interaction else { shell.publish(on_record(interaction)); return; }; let Target::Point(position) = *target else { shell.publish(on_record(interaction)); return; }; if let Some((content, visible_bounds)) = find_text(position + (bounds.position() - Point::ORIGIN), operate) { *target = Target::Text(content); *last_hovered = visible_bounds; } else { *last_hovered = None; } shell.publish(on_record(interaction)); } fn find_text( position: Point, mut operate: impl FnMut(&mut dyn widget::Operation), ) -> Option<(String, Option<Rectangle>)> { use widget::Operation; let mut by_position = position.find_all(); operate(&mut operation::black_box(&mut by_position)); let operation::Outcome::Some(targets) = by_position.finish() else { return None; }; let (content, visible_bounds) = targets.into_iter().rev().find_map(|target| { if let selector::Target::Text { content, visible_bounds, .. } | selector::Target::TextInput { content, visible_bounds, .. } = target { Some((content, visible_bounds)) } else { None } })?; let mut by_text = content.clone().find_all(); operate(&mut operation::black_box(&mut by_text)); let operation::Outcome::Some(texts) = by_text.finish() else { return None; }; if texts.len() > 1 { return None; } Some((content, visible_bounds)) } fn highlight(theme: &impl theme::Base) -> Color { theme .palette() .map(|palette| palette.primary) .unwrap_or(Color::from_rgb(0.0, 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/debug/src/lib.rs
debug/src/lib.rs
pub use iced_core as core; pub use iced_futures as futures; use crate::core::theme; use crate::core::window; use crate::futures::Subscription; pub use internal::Span; #[derive(Debug, Clone, Copy)] pub struct Metadata { pub name: &'static str, pub theme: Option<theme::Palette>, pub can_time_travel: bool, } #[derive(Debug, Clone, Copy)] pub enum Primitive { Quad, Triangle, Shader, Image, Text, } #[derive(Debug, Clone, Copy)] pub enum Command { RewindTo { message: usize }, GoLive, } pub fn enable() { internal::enable(); } pub fn disable() { internal::disable(); } pub fn init(metadata: Metadata) { internal::init(metadata); hot::init(); } pub fn quit() -> bool { internal::quit() } pub fn theme_changed(f: impl FnOnce() -> Option<theme::Palette>) { internal::theme_changed(f); } pub fn tasks_spawned(amount: usize) { internal::tasks_spawned(amount); } pub fn subscriptions_tracked(amount: usize) { internal::subscriptions_tracked(amount); } pub fn layers_rendered(amount: impl FnOnce() -> usize) { internal::layers_rendered(amount); } pub fn boot() -> Span { internal::boot() } pub fn update(message: &impl std::fmt::Debug) -> Span { internal::update(message) } pub fn view(window: window::Id) -> Span { internal::view(window) } pub fn layout(window: window::Id) -> Span { internal::layout(window) } pub fn interact(window: window::Id) -> Span { internal::interact(window) } pub fn draw(window: window::Id) -> Span { internal::draw(window) } pub fn prepare(primitive: Primitive) -> Span { internal::prepare(primitive) } pub fn render(primitive: Primitive) -> Span { internal::render(primitive) } pub fn present(window: window::Id) -> Span { internal::present(window) } pub fn time(name: impl Into<String>) -> Span { internal::time(name) } pub fn time_with<T>(name: impl Into<String>, f: impl FnOnce() -> T) -> T { let span = time(name); let result = f(); span.finish(); result } pub fn commands() -> Subscription<Command> { internal::commands() } pub fn hot<O>(f: impl FnOnce() -> O) -> O { hot::call(f) } pub fn on_hotpatch(f: impl Fn() + Send + Sync + 'static) { hot::on_hotpatch(f) } pub fn is_stale() -> bool { hot::is_stale() } #[cfg(all(feature = "enable", not(target_arch = "wasm32")))] mod internal { use crate::core::theme; use crate::core::time::Instant; use crate::core::window; use crate::futures::Subscription; use crate::futures::futures::Stream; use crate::{Command, Metadata, Primitive}; use iced_beacon as beacon; use beacon::client::{self, Client}; use beacon::span; use beacon::span::present; use std::sync::atomic::{self, AtomicBool, AtomicUsize}; use std::sync::{LazyLock, RwLock}; pub fn init(metadata: Metadata) { let name = metadata.name.split("::").next().unwrap_or(metadata.name); *METADATA.write().expect("Write application metadata") = client::Metadata { name, theme: metadata.theme, can_time_travel: metadata.can_time_travel, }; } pub fn quit() -> bool { if BEACON.is_connected() { BEACON.quit(); true } else { false } } pub fn theme_changed(f: impl FnOnce() -> Option<theme::Palette>) { let Some(palette) = f() else { return; }; if METADATA.read().expect("Read last palette").theme.as_ref() != Some(&palette) { log(client::Event::ThemeChanged(palette)); METADATA.write().expect("Write last palette").theme = Some(palette); } } pub fn tasks_spawned(amount: usize) { log(client::Event::CommandsSpawned(amount)); } pub fn subscriptions_tracked(amount: usize) { log(client::Event::SubscriptionsTracked(amount)); } pub fn layers_rendered(amount: impl FnOnce() -> usize) { log(client::Event::LayersRendered(amount())); } pub fn boot() -> Span { span(span::Stage::Boot) } pub fn update(message: &impl std::fmt::Debug) -> Span { let span = span(span::Stage::Update); let number = LAST_UPDATE.fetch_add(1, atomic::Ordering::Relaxed); let start = Instant::now(); let message = format!("{message:?}"); let elapsed = start.elapsed(); if elapsed.as_millis() >= 1 { log::warn!("Slow `Debug` implementation of `Message` (took {elapsed:?})!"); } let message = if message.len() > 49 { message .chars() .take(49) .chain("...".chars()) .collect::<String>() } else { message }; log(client::Event::MessageLogged { number, message }); span } pub fn view(window: window::Id) -> Span { span(span::Stage::View(window)) } pub fn layout(window: window::Id) -> Span { span(span::Stage::Layout(window)) } pub fn interact(window: window::Id) -> Span { span(span::Stage::Interact(window)) } pub fn draw(window: window::Id) -> Span { span(span::Stage::Draw(window)) } pub fn prepare(primitive: Primitive) -> Span { span(span::Stage::Prepare(to_primitive(primitive))) } pub fn render(primitive: Primitive) -> Span { span(span::Stage::Render(to_primitive(primitive))) } pub fn present(window: window::Id) -> Span { span(span::Stage::Present(window)) } pub fn time(name: impl Into<String>) -> Span { span(span::Stage::Custom(name.into())) } pub fn enable() { ENABLED.store(true, atomic::Ordering::Relaxed); } pub fn disable() { ENABLED.store(false, atomic::Ordering::Relaxed); } pub fn commands() -> Subscription<Command> { fn listen_for_commands() -> impl Stream<Item = Command> { use crate::futures::futures::stream; stream::unfold(BEACON.subscribe(), async move |mut receiver| { let command = match receiver.recv().await? { client::Command::RewindTo { message } => Command::RewindTo { message }, client::Command::GoLive => Command::GoLive, }; Some((command, receiver)) }) } Subscription::run(listen_for_commands) } fn span(span: span::Stage) -> Span { log(client::Event::SpanStarted(span.clone())); Span { span, start: Instant::now(), } } fn to_primitive(primitive: Primitive) -> present::Primitive { match primitive { Primitive::Quad => present::Primitive::Quad, Primitive::Triangle => present::Primitive::Triangle, Primitive::Shader => present::Primitive::Shader, Primitive::Text => present::Primitive::Text, Primitive::Image => present::Primitive::Image, } } fn log(event: client::Event) { if ENABLED.load(atomic::Ordering::Relaxed) { BEACON.log(event); } } #[derive(Debug)] pub struct Span { span: span::Stage, start: Instant, } impl Span { pub fn finish(self) { log(client::Event::SpanFinished(self.span, self.start.elapsed())); } } static BEACON: LazyLock<Client> = LazyLock::new(|| { let metadata = METADATA.read().expect("Read application metadata"); client::connect(metadata.clone()) }); static METADATA: RwLock<client::Metadata> = RwLock::new(client::Metadata { name: "", theme: None, can_time_travel: false, }); static LAST_UPDATE: AtomicUsize = AtomicUsize::new(0); static ENABLED: AtomicBool = AtomicBool::new(true); } #[cfg(any(not(feature = "enable"), target_arch = "wasm32"))] mod internal { use crate::core::theme; use crate::core::window; use crate::futures::Subscription; use crate::{Command, Metadata, Primitive}; pub fn enable() {} pub fn disable() {} pub fn init(_metadata: Metadata) {} pub fn quit() -> bool { false } pub fn theme_changed(_f: impl FnOnce() -> Option<theme::Palette>) {} pub fn tasks_spawned(_amount: usize) {} pub fn subscriptions_tracked(_amount: usize) {} pub fn layers_rendered(_amount: impl FnOnce() -> usize) {} pub fn boot() -> Span { Span } pub fn update(_message: &impl std::fmt::Debug) -> Span { Span } pub fn view(_window: window::Id) -> Span { Span } pub fn layout(_window: window::Id) -> Span { Span } pub fn interact(_window: window::Id) -> Span { Span } pub fn draw(_window: window::Id) -> Span { Span } pub fn prepare(_primitive: Primitive) -> Span { Span } pub fn render(_primitive: Primitive) -> Span { Span } pub fn present(_window: window::Id) -> Span { Span } pub fn time(_name: impl Into<String>) -> Span { Span } pub fn commands() -> Subscription<Command> { Subscription::none() } #[derive(Debug)] pub struct Span; impl Span { pub fn finish(self) {} } } #[cfg(all(feature = "hot", not(target_arch = "wasm32")))] mod hot { use std::collections::BTreeSet; use std::sync::atomic::{self, AtomicBool}; use std::sync::{Arc, Mutex, OnceLock}; static IS_STALE: AtomicBool = AtomicBool::new(false); static HOT_FUNCTIONS_PENDING: Mutex<BTreeSet<u64>> = Mutex::new(BTreeSet::new()); static HOT_FUNCTIONS: OnceLock<BTreeSet<u64>> = OnceLock::new(); pub fn init() { cargo_hot::connect(); cargo_hot::subsecond::register_handler(Arc::new(|| { if HOT_FUNCTIONS.get().is_none() { HOT_FUNCTIONS .set(std::mem::take( &mut HOT_FUNCTIONS_PENDING.lock().expect("Lock hot functions"), )) .expect("Set hot functions"); } IS_STALE.store(false, atomic::Ordering::Relaxed); })); } pub fn call<O>(f: impl FnOnce() -> O) -> O { let mut f = Some(f); // The `move` here is important. Hotpatching will not work // otherwise. let mut f = cargo_hot::subsecond::HotFn::current(move || { f.take().expect("Hot function is stale")() }); let address = f.ptr_address().0; if let Some(hot_functions) = HOT_FUNCTIONS.get() { if hot_functions.contains(&address) { IS_STALE.store(true, atomic::Ordering::Relaxed); } } else { let _ = HOT_FUNCTIONS_PENDING .lock() .expect("Lock hot functions") .insert(address); } f.call(()) } pub fn on_hotpatch(f: impl Fn() + Send + Sync + 'static) { cargo_hot::subsecond::register_handler(Arc::new(f)); } pub fn is_stale() -> bool { IS_STALE.load(atomic::Ordering::Relaxed) } } #[cfg(any(not(feature = "hot"), target_arch = "wasm32"))] mod hot { pub fn init() {} pub fn call<O>(f: impl FnOnce() -> O) -> O { f() } pub fn on_hotpatch(_f: impl Fn()) {} pub fn is_stale() -> bool { false } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/settings.rs
wgpu/src/settings.rs
//! Configure a renderer. use crate::core::{Font, Pixels}; use crate::graphics::{self, Antialiasing}; /// The settings of a [`Renderer`]. /// /// [`Renderer`]: crate::Renderer #[derive(Debug, Clone, Copy, PartialEq)] pub struct Settings { /// The present mode of the [`Renderer`]. /// /// [`Renderer`]: crate::Renderer pub present_mode: wgpu::PresentMode, /// The graphics backends to use. pub backends: wgpu::Backends, /// The default [`Font`] to use. pub default_font: Font, /// The default size of text. /// /// By default, it will be set to `16.0`. pub default_text_size: Pixels, /// The antialiasing strategy that will be used for triangle primitives. /// /// By default, it is `None`. pub antialiasing: Option<Antialiasing>, } impl Default for Settings { fn default() -> Settings { Settings { present_mode: wgpu::PresentMode::AutoVsync, backends: wgpu::Backends::all(), default_font: Font::default(), default_text_size: Pixels(16.0), antialiasing: None, } } } impl From<graphics::Settings> for Settings { fn from(settings: graphics::Settings) -> Self { Self { present_mode: if settings.vsync { wgpu::PresentMode::AutoVsync } else { wgpu::PresentMode::AutoNoVsync }, default_font: settings.default_font, default_text_size: settings.default_text_size, antialiasing: settings.antialiasing, ..Settings::default() } } } /// Obtains a [`wgpu::PresentMode`] from the current environment /// configuration, if set. /// /// The value returned by this function can be changed by setting /// the `ICED_PRESENT_MODE` env variable. The possible values are: /// /// - `vsync` → [`wgpu::PresentMode::AutoVsync`] /// - `no_vsync` → [`wgpu::PresentMode::AutoNoVsync`] /// - `immediate` → [`wgpu::PresentMode::Immediate`] /// - `fifo` → [`wgpu::PresentMode::Fifo`] /// - `fifo_relaxed` → [`wgpu::PresentMode::FifoRelaxed`] /// - `mailbox` → [`wgpu::PresentMode::Mailbox`] pub fn present_mode_from_env() -> Option<wgpu::PresentMode> { let present_mode = std::env::var("ICED_PRESENT_MODE").ok()?; match present_mode.to_lowercase().as_str() { "vsync" => Some(wgpu::PresentMode::AutoVsync), "no_vsync" => Some(wgpu::PresentMode::AutoNoVsync), "immediate" => Some(wgpu::PresentMode::Immediate), "fifo" => Some(wgpu::PresentMode::Fifo), "fifo_relaxed" => Some(wgpu::PresentMode::FifoRelaxed), "mailbox" => Some(wgpu::PresentMode::Mailbox), _ => None, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/engine.rs
wgpu/src/engine.rs
use crate::graphics::{Antialiasing, Shell}; use crate::primitive; use crate::quad; use crate::text; use crate::triangle; use std::sync::{Arc, RwLock}; #[derive(Clone)] pub struct Engine { pub(crate) device: wgpu::Device, pub(crate) queue: wgpu::Queue, pub(crate) format: wgpu::TextureFormat, pub(crate) quad_pipeline: quad::Pipeline, pub(crate) text_pipeline: text::Pipeline, pub(crate) triangle_pipeline: triangle::Pipeline, #[cfg(any(feature = "image", feature = "svg"))] pub(crate) image_pipeline: crate::image::Pipeline, pub(crate) primitive_storage: Arc<RwLock<primitive::Storage>>, _shell: Shell, } impl Engine { pub fn new( _adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, format: wgpu::TextureFormat, antialiasing: Option<Antialiasing>, // TODO: Initialize AA pipelines lazily shell: Shell, ) -> Self { Self { format, quad_pipeline: quad::Pipeline::new(&device, format), text_pipeline: text::Pipeline::new(&device, &queue, format), triangle_pipeline: triangle::Pipeline::new(&device, format, antialiasing), #[cfg(any(feature = "image", feature = "svg"))] image_pipeline: { let backend = _adapter.get_info().backend; crate::image::Pipeline::new(&device, format, backend) }, primitive_storage: Arc::new(RwLock::new(primitive::Storage::default())), device, queue, _shell: shell, } } #[cfg(any(feature = "image", feature = "svg"))] pub fn create_image_cache(&self) -> crate::image::Cache { self.image_pipeline .create_cache(&self.device, &self.queue, &self._shell) } pub fn trim(&mut self) { self.text_pipeline.trim(); self.primitive_storage .write() .expect("primitive storage should be writable") .trim(); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/lib.rs
wgpu/src/lib.rs
//! A [`wgpu`] renderer for [Iced]. //! //! ![The native path of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/native.png?raw=true) //! //! [`wgpu`] supports most modern graphics backends: Vulkan, Metal, DX11, and //! DX12 (OpenGL and WebGL are still WIP). Additionally, it will support the //! incoming [WebGPU API]. //! //! Currently, `iced_wgpu` supports the following primitives: //! - Text, which is rendered using [`glyphon`]. //! - Quads or rectangles, with rounded borders and a solid background color. //! - Clip areas, useful to implement scrollables or hide overflowing content. //! - Images and SVG, loaded from memory or the file system. //! - Meshes of triangles, useful to draw geometry freely. //! //! [Iced]: https://github.com/iced-rs/iced //! [`wgpu`]: https://github.com/gfx-rs/wgpu-rs //! [WebGPU API]: https://gpuweb.github.io/gpuweb/ //! [`glyphon`]: https://github.com/grovesNL/glyphon #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] #![allow(missing_docs)] pub mod layer; pub mod primitive; pub mod settings; pub mod window; #[cfg(feature = "geometry")] pub mod geometry; mod buffer; mod color; mod engine; mod quad; mod text; mod triangle; #[cfg(any(feature = "image", feature = "svg"))] #[path = "image/mod.rs"] mod image; #[cfg(not(any(feature = "image", feature = "svg")))] #[path = "image/null.rs"] mod image; use buffer::Buffer; use iced_debug as debug; pub use iced_graphics as graphics; pub use iced_graphics::core; pub use wgpu; pub use engine::Engine; pub use layer::Layer; pub use primitive::Primitive; pub use settings::Settings; #[cfg(feature = "geometry")] pub use geometry::Geometry; use crate::core::renderer; use crate::core::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation}; use crate::graphics::mesh; use crate::graphics::text::{Editor, Paragraph}; use crate::graphics::{Shell, Viewport}; /// A [`wgpu`] graphics renderer for [`iced`]. /// /// [`wgpu`]: https://github.com/gfx-rs/wgpu-rs /// [`iced`]: https://github.com/iced-rs/iced pub struct Renderer { engine: Engine, default_font: Font, default_text_size: Pixels, layers: layer::Stack, scale_factor: Option<f32>, quad: quad::State, triangle: triangle::State, text: text::State, text_viewport: text::Viewport, #[cfg(any(feature = "svg", feature = "image"))] image: image::State, // TODO: Centralize all the image feature handling #[cfg(any(feature = "svg", feature = "image"))] image_cache: std::cell::RefCell<image::Cache>, staging_belt: wgpu::util::StagingBelt, } impl Renderer { pub fn new(engine: Engine, default_font: Font, default_text_size: Pixels) -> Self { Self { default_font, default_text_size, layers: layer::Stack::new(), scale_factor: None, quad: quad::State::new(), triangle: triangle::State::new(&engine.device, &engine.triangle_pipeline), text: text::State::new(), text_viewport: engine.text_pipeline.create_viewport(&engine.device), #[cfg(any(feature = "svg", feature = "image"))] image: image::State::new(), #[cfg(any(feature = "svg", feature = "image"))] image_cache: std::cell::RefCell::new(engine.create_image_cache()), // TODO: Resize belt smartly (?) // It would be great if the `StagingBelt` API exposed methods // for introspection to detect when a resize may be worth it. staging_belt: wgpu::util::StagingBelt::new(buffer::MAX_WRITE_SIZE as u64), engine, } } fn draw( &mut self, clear_color: Option<Color>, target: &wgpu::TextureView, viewport: &Viewport, ) -> wgpu::CommandEncoder { let mut encoder = self.engine .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("iced_wgpu encoder"), }); self.prepare(&mut encoder, viewport); self.render(&mut encoder, target, clear_color, viewport); self.quad.trim(); self.triangle.trim(); self.text.trim(); // TODO: Provide window id (?) self.engine.trim(); #[cfg(any(feature = "svg", feature = "image"))] { self.image.trim(); self.image_cache.borrow_mut().trim(); } encoder } pub fn present( &mut self, clear_color: Option<Color>, _format: wgpu::TextureFormat, frame: &wgpu::TextureView, viewport: &Viewport, ) -> wgpu::SubmissionIndex { let encoder = self.draw(clear_color, frame, viewport); self.staging_belt.finish(); let submission = self.engine.queue.submit([encoder.finish()]); self.staging_belt.recall(); submission } /// Renders the current surface to an offscreen buffer. /// /// Returns RGBA bytes of the texture data. pub fn screenshot(&mut self, viewport: &Viewport, background_color: Color) -> Vec<u8> { #[derive(Clone, Copy, Debug)] struct BufferDimensions { width: u32, height: u32, unpadded_bytes_per_row: usize, padded_bytes_per_row: usize, } impl BufferDimensions { fn new(size: Size<u32>) -> Self { let unpadded_bytes_per_row = size.width as usize * 4; //slice of buffer per row; always RGBA let alignment = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; //256 let padded_bytes_per_row_padding = (alignment - unpadded_bytes_per_row % alignment) % alignment; let padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding; Self { width: size.width, height: size.height, unpadded_bytes_per_row, padded_bytes_per_row, } } } let dimensions = BufferDimensions::new(viewport.physical_size()); let texture_extent = wgpu::Extent3d { width: dimensions.width, height: dimensions.height, depth_or_array_layers: 1, }; let texture = self.engine.device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu.offscreen.source_texture"), size: texture_extent, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: self.engine.format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = self.draw(Some(background_color), &view, viewport); let texture = crate::color::convert( &self.engine.device, &mut encoder, texture, if graphics::color::GAMMA_CORRECTION { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }, ); let output_buffer = self.engine.device.create_buffer(&wgpu::BufferDescriptor { label: Some("iced_wgpu.offscreen.output_texture_buffer"), size: (dimensions.padded_bytes_per_row * dimensions.height as usize) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); encoder.copy_texture_to_buffer( texture.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &output_buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(dimensions.padded_bytes_per_row as u32), rows_per_image: None, }, }, texture_extent, ); self.staging_belt.finish(); let index = self.engine.queue.submit([encoder.finish()]); self.staging_belt.recall(); let slice = output_buffer.slice(..); slice.map_async(wgpu::MapMode::Read, |_| {}); let _ = self.engine.device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None, }); let mapped_buffer = slice.get_mapped_range(); mapped_buffer .chunks(dimensions.padded_bytes_per_row) .fold(vec![], |mut acc, row| { acc.extend(&row[..dimensions.unpadded_bytes_per_row]); acc }) } fn prepare(&mut self, encoder: &mut wgpu::CommandEncoder, viewport: &Viewport) { let scale_factor = viewport.scale_factor(); self.text_viewport .update(&self.engine.queue, viewport.physical_size()); let physical_bounds = Rectangle::<f32>::from(Rectangle::with_size(viewport.physical_size())); self.layers.merge(); for layer in self.layers.iter() { let clip_bounds = layer.bounds * scale_factor; if physical_bounds .intersection(&clip_bounds) .and_then(Rectangle::snap) .is_none() { continue; } if !layer.quads.is_empty() { let prepare_span = debug::prepare(debug::Primitive::Quad); self.quad.prepare( &self.engine.quad_pipeline, &self.engine.device, &mut self.staging_belt, encoder, &layer.quads, viewport.projection(), scale_factor, ); prepare_span.finish(); } if !layer.triangles.is_empty() { let prepare_span = debug::prepare(debug::Primitive::Triangle); self.triangle.prepare( &self.engine.triangle_pipeline, &self.engine.device, &mut self.staging_belt, encoder, &layer.triangles, Transformation::scale(scale_factor), viewport.physical_size(), ); prepare_span.finish(); } if !layer.primitives.is_empty() { let prepare_span = debug::prepare(debug::Primitive::Shader); let mut primitive_storage = self .engine .primitive_storage .write() .expect("Write primitive storage"); for instance in &layer.primitives { instance.primitive.prepare( &mut primitive_storage, &self.engine.device, &self.engine.queue, self.engine.format, &instance.bounds, viewport, ); } prepare_span.finish(); } #[cfg(any(feature = "svg", feature = "image"))] if !layer.images.is_empty() { let prepare_span = debug::prepare(debug::Primitive::Image); self.image.prepare( &self.engine.image_pipeline, &self.engine.device, &mut self.staging_belt, encoder, &mut self.image_cache.borrow_mut(), &layer.images, viewport.projection(), scale_factor, ); prepare_span.finish(); } if !layer.text.is_empty() { let prepare_span = debug::prepare(debug::Primitive::Text); self.text.prepare( &self.engine.text_pipeline, &self.engine.device, &self.engine.queue, &self.text_viewport, encoder, &layer.text, layer.bounds, Transformation::scale(scale_factor), ); prepare_span.finish(); } } } fn render( &mut self, encoder: &mut wgpu::CommandEncoder, frame: &wgpu::TextureView, clear_color: Option<Color>, viewport: &Viewport, ) { use std::mem::ManuallyDrop; let mut render_pass = ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: frame, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: match clear_color { Some(background_color) => wgpu::LoadOp::Clear({ let [r, g, b, a] = graphics::color::pack(background_color).components(); wgpu::Color { r: f64::from(r), g: f64::from(g), b: f64::from(b), a: f64::from(a), } }), None => wgpu::LoadOp::Load, }, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, })); let mut quad_layer = 0; let mut mesh_layer = 0; let mut text_layer = 0; #[cfg(any(feature = "svg", feature = "image"))] let mut image_layer = 0; let scale_factor = viewport.scale_factor(); let physical_bounds = Rectangle::<f32>::from(Rectangle::with_size(viewport.physical_size())); let scale = Transformation::scale(scale_factor); for layer in self.layers.iter() { let Some(physical_bounds) = physical_bounds.intersection(&(layer.bounds * scale_factor)) else { continue; }; let Some(scissor_rect) = physical_bounds.snap() else { continue; }; if !layer.quads.is_empty() { let render_span = debug::render(debug::Primitive::Quad); self.quad.render( &self.engine.quad_pipeline, quad_layer, scissor_rect, &layer.quads, &mut render_pass, ); render_span.finish(); quad_layer += 1; } if !layer.triangles.is_empty() { let _ = ManuallyDrop::into_inner(render_pass); let render_span = debug::render(debug::Primitive::Triangle); mesh_layer += self.triangle.render( &self.engine.triangle_pipeline, encoder, frame, mesh_layer, &layer.triangles, physical_bounds, scale, ); render_span.finish(); render_pass = ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: frame, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, })); } if !layer.primitives.is_empty() { let render_span = debug::render(debug::Primitive::Shader); let primitive_storage = self .engine .primitive_storage .read() .expect("Read primitive storage"); let mut need_render = Vec::new(); for instance in &layer.primitives { let bounds = instance.bounds * scale; if let Some(clip_bounds) = (instance.bounds * scale) .intersection(&physical_bounds) .and_then(Rectangle::snap) { render_pass.set_viewport( bounds.x, bounds.y, bounds.width, bounds.height, 0.0, 1.0, ); render_pass.set_scissor_rect( clip_bounds.x, clip_bounds.y, clip_bounds.width, clip_bounds.height, ); let drawn = instance .primitive .draw(&primitive_storage, &mut render_pass); if !drawn { need_render.push((instance, clip_bounds)); } } } render_pass.set_viewport( 0.0, 0.0, viewport.physical_width() as f32, viewport.physical_height() as f32, 0.0, 1.0, ); render_pass.set_scissor_rect( 0, 0, viewport.physical_width(), viewport.physical_height(), ); if !need_render.is_empty() { let _ = ManuallyDrop::into_inner(render_pass); for (instance, clip_bounds) in need_render { instance .primitive .render(&primitive_storage, encoder, frame, &clip_bounds); } render_pass = ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: frame, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, })); } render_span.finish(); } #[cfg(any(feature = "svg", feature = "image"))] if !layer.images.is_empty() { let render_span = debug::render(debug::Primitive::Image); self.image.render( &self.engine.image_pipeline, image_layer, scissor_rect, &mut render_pass, ); render_span.finish(); image_layer += 1; } if !layer.text.is_empty() { let render_span = debug::render(debug::Primitive::Text); text_layer += self.text.render( &self.engine.text_pipeline, &self.text_viewport, text_layer, &layer.text, scissor_rect, &mut render_pass, ); render_span.finish(); } } let _ = ManuallyDrop::into_inner(render_pass); debug::layers_rendered(|| { self.layers .iter() .filter(|layer| { !layer.is_empty() && physical_bounds .intersection(&(layer.bounds * scale_factor)) .is_some_and(|viewport| viewport.snap().is_some()) }) .count() }); } } impl core::Renderer for Renderer { fn start_layer(&mut self, bounds: Rectangle) { self.layers.push_clip(bounds); } fn end_layer(&mut self) { self.layers.pop_clip(); } fn start_transformation(&mut self, transformation: Transformation) { self.layers.push_transformation(transformation); } fn end_transformation(&mut self) { self.layers.pop_transformation(); } fn fill_quad(&mut self, quad: core::renderer::Quad, background: impl Into<Background>) { let (layer, transformation) = self.layers.current_mut(); layer.draw_quad(quad, background.into(), transformation); } fn allocate_image( &mut self, _handle: &core::image::Handle, _callback: impl FnOnce(Result<core::image::Allocation, core::image::Error>) + Send + 'static, ) { #[cfg(feature = "image")] self.image_cache .get_mut() .allocate_image(_handle, _callback); } fn hint(&mut self, scale_factor: f32) { self.scale_factor = Some(scale_factor); } fn scale_factor(&self) -> Option<f32> { Some(self.scale_factor? * self.layers.transformation().scale_factor()) } fn tick(&mut self) { #[cfg(feature = "image")] self.image_cache.get_mut().receive(); } fn reset(&mut self, new_bounds: Rectangle) { self.layers.reset(new_bounds); } } impl core::text::Renderer for Renderer { type Font = Font; type Paragraph = Paragraph; type Editor = Editor; const ICON_FONT: Font = Font::with_name("Iced-Icons"); const CHECKMARK_ICON: char = '\u{f00c}'; const ARROW_DOWN_ICON: char = '\u{e800}'; const ICED_LOGO: char = '\u{e801}'; const SCROLL_UP_ICON: char = '\u{e802}'; const SCROLL_DOWN_ICON: char = '\u{e803}'; const SCROLL_LEFT_ICON: char = '\u{e804}'; const SCROLL_RIGHT_ICON: char = '\u{e805}'; fn default_font(&self) -> Self::Font { self.default_font } fn default_size(&self) -> Pixels { self.default_text_size } fn fill_paragraph( &mut self, text: &Self::Paragraph, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_paragraph(text, position, color, clip_bounds, transformation); } fn fill_editor( &mut self, editor: &Self::Editor, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_editor(editor, position, color, clip_bounds, transformation); } fn fill_text( &mut self, text: core::Text, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_text(text, position, color, clip_bounds, transformation); } } impl graphics::text::Renderer for Renderer { fn fill_raw(&mut self, raw: graphics::text::Raw) { let (layer, transformation) = self.layers.current_mut(); layer.draw_text_raw(raw, transformation); } } #[cfg(feature = "image")] impl core::image::Renderer for Renderer { type Handle = core::image::Handle; fn load_image( &self, handle: &Self::Handle, ) -> Result<core::image::Allocation, core::image::Error> { self.image_cache .borrow_mut() .load_image(&self.engine.device, &self.engine.queue, handle) } fn measure_image(&self, handle: &Self::Handle) -> Option<core::Size<u32>> { self.image_cache.borrow_mut().measure_image(handle) } fn draw_image(&mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_raster(image, bounds, clip_bounds, transformation); } } #[cfg(feature = "svg")] impl core::svg::Renderer for Renderer { fn measure_svg(&self, handle: &core::svg::Handle) -> core::Size<u32> { self.image_cache.borrow_mut().measure_svg(handle) } fn draw_svg(&mut self, svg: core::Svg, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_svg(svg, bounds, clip_bounds, transformation); } } impl graphics::mesh::Renderer for Renderer { fn draw_mesh(&mut self, mesh: graphics::Mesh) { debug_assert!( !mesh.indices().is_empty(), "Mesh must not have empty indices" ); debug_assert!( mesh.indices().len().is_multiple_of(3), "Mesh indices length must be a multiple of 3" ); let (layer, transformation) = self.layers.current_mut(); layer.draw_mesh(mesh, transformation); } fn draw_mesh_cache(&mut self, cache: mesh::Cache) { let (layer, transformation) = self.layers.current_mut(); layer.draw_mesh_cache(cache, transformation); } } #[cfg(feature = "geometry")] impl graphics::geometry::Renderer for Renderer { type Geometry = Geometry; type Frame = geometry::Frame; fn new_frame(&self, bounds: Rectangle) -> Self::Frame { geometry::Frame::new(bounds) } fn draw_geometry(&mut self, geometry: Self::Geometry) { let (layer, transformation) = self.layers.current_mut(); match geometry { Geometry::Live { meshes, images, text, } => { layer.draw_mesh_group(meshes, transformation); for image in images { layer.draw_image(image, transformation); } layer.draw_text_group(text, transformation); } Geometry::Cached(cache) => { if let Some(meshes) = cache.meshes { layer.draw_mesh_cache(meshes, transformation); } if let Some(images) = cache.images { for image in images.iter().cloned() { layer.draw_image(image, transformation); } } if let Some(text) = cache.text { layer.draw_text_cache(text, transformation); } } } } } impl primitive::Renderer for Renderer { fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl Primitive) { let (layer, transformation) = self.layers.current_mut(); layer.draw_primitive(bounds, primitive, transformation); } } impl graphics::compositor::Default for crate::Renderer { type Compositor = window::Compositor; } impl renderer::Headless for Renderer { async fn new( default_font: Font, default_text_size: Pixels, backend: Option<&str>, ) -> Option<Self> { if backend.is_some_and(|backend| backend != "wgpu") { return None; } let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::PRIMARY), flags: wgpu::InstanceFlags::empty(), ..wgpu::InstanceDescriptor::default() }); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, force_fallback_adapter: false, compatible_surface: None, }) .await .ok()?; let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor { label: Some("iced_wgpu [headless]"), required_features: wgpu::Features::empty(), required_limits: wgpu::Limits { max_bind_groups: 2, ..wgpu::Limits::default() }, memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, experimental_features: wgpu::ExperimentalFeatures::disabled(), }) .await .ok()?; let engine = Engine::new( &adapter, device, queue, if graphics::color::GAMMA_CORRECTION { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }, Some(graphics::Antialiasing::MSAAx4), Shell::headless(), ); Some(Self::new(engine, default_font, default_text_size)) } fn name(&self) -> String { "wgpu".to_owned() } fn screenshot( &mut self, size: Size<u32>, scale_factor: f32, background_color: Color, ) -> Vec<u8> { self.screenshot( &Viewport::with_physical_size(size, scale_factor), background_color, ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/geometry.rs
wgpu/src/geometry.rs
//! Build and draw geometry. use crate::core::text::LineHeight; use crate::core::{self, Pixels, Point, Radians, Rectangle, Size, Svg, Transformation, Vector}; use crate::graphics::cache::{self, Cached}; use crate::graphics::color; use crate::graphics::geometry::fill::{self, Fill}; use crate::graphics::geometry::{self, LineCap, LineDash, LineJoin, Path, Stroke, Style}; use crate::graphics::gradient::{self, Gradient}; use crate::graphics::mesh::{self, Mesh}; use crate::graphics::{Image, Text}; use crate::text; use lyon::geom::euclid; use lyon::tessellation; use std::borrow::Cow; use std::sync::Arc; #[derive(Debug)] pub enum Geometry { Live { meshes: Vec<Mesh>, images: Vec<Image>, text: Vec<Text>, }, Cached(Cache), } #[derive(Debug, Clone, Default)] pub struct Cache { pub meshes: Option<mesh::Cache>, pub images: Option<Arc<[Image]>>, pub text: Option<text::Cache>, } impl Cached for Geometry { type Cache = Cache; fn load(cache: &Self::Cache) -> Self { Geometry::Cached(cache.clone()) } fn cache(self, group: cache::Group, previous: Option<Self::Cache>) -> Self::Cache { match self { Self::Live { meshes, images, text, } => { let images = if images.is_empty() { None } else { Some(Arc::from(images)) }; let meshes = Arc::from(meshes); if let Some(mut previous) = previous { if let Some(cache) = &mut previous.meshes { cache.update(meshes); } else { previous.meshes = if meshes.is_empty() { None } else { Some(mesh::Cache::new(meshes)) }; } if let Some(cache) = &mut previous.text { cache.update(text); } else { previous.text = text::Cache::new(group, text); } previous.images = images; previous } else { Cache { meshes: if meshes.is_empty() { None } else { Some(mesh::Cache::new(meshes)) }, images, text: text::Cache::new(group, text), } } } Self::Cached(cache) => cache, } } } /// A frame for drawing some geometry. pub struct Frame { clip_bounds: Rectangle, buffers: BufferStack, meshes: Vec<Mesh>, images: Vec<Image>, text: Vec<Text>, transforms: Transforms, fill_tessellator: tessellation::FillTessellator, stroke_tessellator: tessellation::StrokeTessellator, } impl Frame { /// Creates a new [`Frame`] with the given clip bounds. pub fn new(bounds: Rectangle) -> Frame { Frame { clip_bounds: bounds, buffers: BufferStack::new(), meshes: Vec::new(), images: Vec::new(), text: Vec::new(), transforms: Transforms { previous: Vec::new(), current: Transform(lyon::math::Transform::identity()), }, fill_tessellator: tessellation::FillTessellator::new(), stroke_tessellator: tessellation::StrokeTessellator::new(), } } } impl geometry::frame::Backend for Frame { type Geometry = Geometry; #[inline] fn width(&self) -> f32 { self.clip_bounds.width } #[inline] fn height(&self) -> f32 { self.clip_bounds.height } #[inline] fn size(&self) -> Size { self.clip_bounds.size() } #[inline] fn center(&self) -> Point { Point::new(self.clip_bounds.width / 2.0, self.clip_bounds.height / 2.0) } fn fill(&mut self, path: &Path, fill: impl Into<Fill>) { let Fill { style, rule } = fill.into(); let mut buffer = self .buffers .get_fill(&self.transforms.current.transform_style(style)); let options = tessellation::FillOptions::default().with_fill_rule(into_fill_rule(rule)); if self.transforms.current.is_identity() { self.fill_tessellator .tessellate_path(path.raw(), &options, buffer.as_mut()) } else { let path = path.transform(&self.transforms.current.0); self.fill_tessellator .tessellate_path(path.raw(), &options, buffer.as_mut()) } .expect("Tessellate path."); } fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into<Fill>) { let Fill { style, rule } = fill.into(); let mut buffer = self .buffers .get_fill(&self.transforms.current.transform_style(style)); let top_left = self .transforms .current .0 .transform_point(lyon::math::Point::new(top_left.x, top_left.y)); let size = self .transforms .current .0 .transform_vector(lyon::math::Vector::new(size.width, size.height)); let options = tessellation::FillOptions::default().with_fill_rule(into_fill_rule(rule)); self.fill_tessellator .tessellate_rectangle( &lyon::math::Box2D::new(top_left, top_left + size), &options, buffer.as_mut(), ) .expect("Fill rectangle"); } fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) { let stroke = stroke.into(); let mut buffer = self .buffers .get_stroke(&self.transforms.current.transform_style(stroke.style)); let mut options = tessellation::StrokeOptions::default(); options.line_width = stroke.width; options.start_cap = into_line_cap(stroke.line_cap); options.end_cap = into_line_cap(stroke.line_cap); options.line_join = into_line_join(stroke.line_join); let path = if stroke.line_dash.segments.is_empty() { Cow::Borrowed(path) } else { Cow::Owned(dashed(path, stroke.line_dash)) }; if self.transforms.current.is_identity() { self.stroke_tessellator .tessellate_path(path.raw(), &options, buffer.as_mut()) } else { let path = path.transform(&self.transforms.current.0); self.stroke_tessellator .tessellate_path(path.raw(), &options, buffer.as_mut()) } .expect("Stroke path"); } fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into<Stroke<'a>>) { let stroke = stroke.into(); let mut buffer = self .buffers .get_stroke(&self.transforms.current.transform_style(stroke.style)); let top_left = self .transforms .current .0 .transform_point(lyon::math::Point::new(top_left.x, top_left.y)); let size = self .transforms .current .0 .transform_vector(lyon::math::Vector::new(size.width, size.height)); let mut options = tessellation::StrokeOptions::default(); options.line_width = stroke.width; options.start_cap = into_line_cap(stroke.line_cap); options.end_cap = into_line_cap(stroke.line_cap); options.line_join = into_line_join(stroke.line_join); self.stroke_tessellator .tessellate_rectangle( &lyon::math::Box2D::new(top_left, top_left + size), &options, buffer.as_mut(), ) .expect("Stroke rectangle"); } fn stroke_text<'a>(&mut self, text: impl Into<geometry::Text>, stroke: impl Into<Stroke<'a>>) { let text = text.into(); let stroke = stroke.into(); text.draw_with(|glyph, _color| self.stroke(&glyph, stroke)); } fn fill_text(&mut self, text: impl Into<geometry::Text>) { let text = text.into(); let (scale_x, scale_y) = self.transforms.current.scale(); if self.transforms.current.is_scale_translation() && scale_x == scale_y && scale_x > 0.0 && scale_y > 0.0 { let (bounds, size, line_height) = if self.transforms.current.is_identity() { ( Rectangle::new(text.position, Size::new(text.max_width, f32::INFINITY)), text.size, text.line_height, ) } else { let position = self.transforms.current.transform_point(text.position); let size = Pixels(text.size.0 * scale_y); let line_height = match text.line_height { LineHeight::Absolute(size) => LineHeight::Absolute(Pixels(size.0 * scale_y)), LineHeight::Relative(factor) => LineHeight::Relative(factor), }; ( Rectangle::new(position, Size::new(text.max_width, f32::INFINITY)), size, line_height, ) }; self.text.push(Text::Cached { content: text.content, bounds, color: text.color, size, line_height: line_height.to_absolute(size), font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, clip_bounds: self.clip_bounds, }); } else { text.draw_with(|path, color| self.fill(&path, color)); } } #[inline] fn translate(&mut self, translation: Vector) { self.transforms.current.0 = self .transforms .current .0 .pre_translate(lyon::math::Vector::new(translation.x, translation.y)); } #[inline] fn rotate(&mut self, angle: impl Into<Radians>) { self.transforms.current.0 = self .transforms .current .0 .pre_rotate(lyon::math::Angle::radians(angle.into().0)); } #[inline] fn scale(&mut self, scale: impl Into<f32>) { let scale = scale.into(); self.scale_nonuniform(Vector { x: scale, y: scale }); } #[inline] fn scale_nonuniform(&mut self, scale: impl Into<Vector>) { let scale = scale.into(); self.transforms.current.0 = self.transforms.current.0.pre_scale(scale.x, scale.y); } fn push_transform(&mut self) { self.transforms.previous.push(self.transforms.current); } fn pop_transform(&mut self) { self.transforms.current = self.transforms.previous.pop().unwrap(); } fn draft(&mut self, clip_bounds: Rectangle) -> Frame { Frame::new(clip_bounds) } fn paste(&mut self, frame: Frame) { self.meshes.extend(frame.meshes); self.meshes .extend(frame.buffers.into_meshes(frame.clip_bounds)); self.images.extend(frame.images); self.text.extend(frame.text); } fn into_geometry(mut self) -> Self::Geometry { self.meshes .extend(self.buffers.into_meshes(self.clip_bounds)); Geometry::Live { meshes: self.meshes, images: self.images, text: self.text, } } fn draw_image(&mut self, bounds: Rectangle, image: impl Into<core::Image>) { let mut image = image.into(); let (bounds, external_rotation) = self.transforms.current.transform_rectangle(bounds); image.rotation += external_rotation; image.border_radius = image.border_radius * self.transforms.current.scale().0; self.images.push(Image::Raster { image, bounds, clip_bounds: self.clip_bounds, }); } fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) { let mut svg = svg.into(); let (bounds, external_rotation) = self.transforms.current.transform_rectangle(bounds); svg.rotation += external_rotation; self.images.push(Image::Vector { svg, bounds, clip_bounds: self.clip_bounds, }); } } enum Buffer { Solid(tessellation::VertexBuffers<mesh::SolidVertex2D, u32>), Gradient(tessellation::VertexBuffers<mesh::GradientVertex2D, u32>), } struct BufferStack { stack: Vec<Buffer>, } impl BufferStack { fn new() -> Self { Self { stack: Vec::new() } } fn get_mut(&mut self, style: &Style) -> &mut Buffer { match style { Style::Solid(_) => match self.stack.last() { Some(Buffer::Solid(_)) => {} _ => { self.stack .push(Buffer::Solid(tessellation::VertexBuffers::new())); } }, Style::Gradient(_) => match self.stack.last() { Some(Buffer::Gradient(_)) => {} _ => { self.stack .push(Buffer::Gradient(tessellation::VertexBuffers::new())); } }, } self.stack.last_mut().unwrap() } fn get_fill<'a>( &'a mut self, style: &Style, ) -> Box<dyn tessellation::FillGeometryBuilder + 'a> { match (style, self.get_mut(style)) { (Style::Solid(color), Buffer::Solid(buffer)) => { Box::new(tessellation::BuffersBuilder::new( buffer, TriangleVertex2DBuilder(color::pack(*color)), )) } (Style::Gradient(gradient), Buffer::Gradient(buffer)) => { Box::new(tessellation::BuffersBuilder::new( buffer, GradientVertex2DBuilder { gradient: gradient.pack(), }, )) } _ => unreachable!(), } } fn get_stroke<'a>( &'a mut self, style: &Style, ) -> Box<dyn tessellation::StrokeGeometryBuilder + 'a> { match (style, self.get_mut(style)) { (Style::Solid(color), Buffer::Solid(buffer)) => { Box::new(tessellation::BuffersBuilder::new( buffer, TriangleVertex2DBuilder(color::pack(*color)), )) } (Style::Gradient(gradient), Buffer::Gradient(buffer)) => { Box::new(tessellation::BuffersBuilder::new( buffer, GradientVertex2DBuilder { gradient: gradient.pack(), }, )) } _ => unreachable!(), } } fn into_meshes(self, clip_bounds: Rectangle) -> impl Iterator<Item = Mesh> { self.stack .into_iter() .filter_map(move |buffer| match buffer { Buffer::Solid(buffer) if !buffer.indices.is_empty() => Some(Mesh::Solid { buffers: mesh::Indexed { vertices: buffer.vertices, indices: buffer.indices, }, clip_bounds, transformation: Transformation::IDENTITY, }), Buffer::Gradient(buffer) if !buffer.indices.is_empty() => Some(Mesh::Gradient { buffers: mesh::Indexed { vertices: buffer.vertices, indices: buffer.indices, }, clip_bounds, transformation: Transformation::IDENTITY, }), _ => None, }) } } #[derive(Debug)] struct Transforms { previous: Vec<Transform>, current: Transform, } #[derive(Debug, Clone, Copy)] struct Transform(lyon::math::Transform); impl Transform { fn is_identity(&self) -> bool { self.0 == lyon::math::Transform::identity() } fn is_scale_translation(&self) -> bool { self.0.m12.abs() < 2.0 * f32::EPSILON && self.0.m21.abs() < 2.0 * f32::EPSILON } fn scale(&self) -> (f32, f32) { (self.0.m11, self.0.m22) } fn transform_point(&self, point: Point) -> Point { let transformed = self .0 .transform_point(euclid::Point2D::new(point.x, point.y)); Point { x: transformed.x, y: transformed.y, } } fn transform_style(&self, style: Style) -> Style { match style { Style::Solid(color) => Style::Solid(color), Style::Gradient(gradient) => Style::Gradient(self.transform_gradient(gradient)), } } fn transform_gradient(&self, mut gradient: Gradient) -> Gradient { match &mut gradient { Gradient::Linear(linear) => { linear.start = self.transform_point(linear.start); linear.end = self.transform_point(linear.end); } } gradient } fn transform_rectangle(&self, rectangle: Rectangle) -> (Rectangle, Radians) { let top_left = self.transform_point(rectangle.position()); let top_right = self.transform_point(rectangle.position() + Vector::new(rectangle.width, 0.0)); let bottom_left = self.transform_point(rectangle.position() + Vector::new(0.0, rectangle.height)); Rectangle::with_vertices(top_left, top_right, bottom_left) } } struct GradientVertex2DBuilder { gradient: gradient::Packed, } impl tessellation::FillVertexConstructor<mesh::GradientVertex2D> for GradientVertex2DBuilder { fn new_vertex(&mut self, vertex: tessellation::FillVertex<'_>) -> mesh::GradientVertex2D { let position = vertex.position(); mesh::GradientVertex2D { position: [position.x, position.y], gradient: self.gradient, } } } impl tessellation::StrokeVertexConstructor<mesh::GradientVertex2D> for GradientVertex2DBuilder { fn new_vertex(&mut self, vertex: tessellation::StrokeVertex<'_, '_>) -> mesh::GradientVertex2D { let position = vertex.position(); mesh::GradientVertex2D { position: [position.x, position.y], gradient: self.gradient, } } } struct TriangleVertex2DBuilder(color::Packed); impl tessellation::FillVertexConstructor<mesh::SolidVertex2D> for TriangleVertex2DBuilder { fn new_vertex(&mut self, vertex: tessellation::FillVertex<'_>) -> mesh::SolidVertex2D { let position = vertex.position(); mesh::SolidVertex2D { position: [position.x, position.y], color: self.0, } } } impl tessellation::StrokeVertexConstructor<mesh::SolidVertex2D> for TriangleVertex2DBuilder { fn new_vertex(&mut self, vertex: tessellation::StrokeVertex<'_, '_>) -> mesh::SolidVertex2D { let position = vertex.position(); mesh::SolidVertex2D { position: [position.x, position.y], color: self.0, } } } fn into_line_join(line_join: LineJoin) -> lyon::tessellation::LineJoin { match line_join { LineJoin::Miter => lyon::tessellation::LineJoin::Miter, LineJoin::Round => lyon::tessellation::LineJoin::Round, LineJoin::Bevel => lyon::tessellation::LineJoin::Bevel, } } fn into_line_cap(line_cap: LineCap) -> lyon::tessellation::LineCap { match line_cap { LineCap::Butt => lyon::tessellation::LineCap::Butt, LineCap::Square => lyon::tessellation::LineCap::Square, LineCap::Round => lyon::tessellation::LineCap::Round, } } fn into_fill_rule(rule: fill::Rule) -> lyon::tessellation::FillRule { match rule { fill::Rule::NonZero => lyon::tessellation::FillRule::NonZero, fill::Rule::EvenOdd => lyon::tessellation::FillRule::EvenOdd, } } pub(super) fn dashed(path: &Path, line_dash: LineDash<'_>) -> Path { use lyon::algorithms::walk::{RepeatedPattern, WalkerEvent, walk_along_path}; use lyon::path::iterator::PathIterator; Path::new(|builder| { let segments_odd = (line_dash.segments.len() % 2 == 1) .then(|| [line_dash.segments, line_dash.segments].concat()); let mut draw_line = false; walk_along_path( path.raw() .iter() .flattened(lyon::tessellation::StrokeOptions::DEFAULT_TOLERANCE), 0.0, lyon::tessellation::StrokeOptions::DEFAULT_TOLERANCE, &mut RepeatedPattern { callback: |event: WalkerEvent<'_>| { let point = Point { x: event.position.x, y: event.position.y, }; if draw_line { builder.line_to(point); } else { builder.move_to(point); } draw_line = !draw_line; true }, index: line_dash.offset, intervals: segments_odd.as_deref().unwrap_or(line_dash.segments), }, ); }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/layer.rs
wgpu/src/layer.rs
use crate::core::{self, Background, Color, Point, Rectangle, Svg, Transformation, renderer}; use crate::graphics; use crate::graphics::Mesh; use crate::graphics::color; use crate::graphics::layer; use crate::graphics::mesh; use crate::graphics::text::{Editor, Paragraph}; use crate::image::{self, Image}; use crate::primitive::{self, Primitive}; use crate::quad::{self, Quad}; use crate::text::{self, Text}; use crate::triangle; pub type Stack = layer::Stack<Layer>; #[derive(Debug)] pub struct Layer { pub bounds: Rectangle, pub quads: quad::Batch, pub triangles: triangle::Batch, pub primitives: primitive::Batch, pub images: image::Batch, pub text: text::Batch, pending_meshes: Vec<Mesh>, pending_text: Vec<Text>, } impl Layer { pub fn is_empty(&self) -> bool { self.quads.is_empty() && self.triangles.is_empty() && self.primitives.is_empty() && self.images.is_empty() && self.text.is_empty() && self.pending_meshes.is_empty() && self.pending_text.is_empty() } pub fn draw_quad( &mut self, quad: renderer::Quad, background: Background, transformation: Transformation, ) { let bounds = quad.bounds * transformation; let quad = Quad { position: [bounds.x, bounds.y], size: [bounds.width, bounds.height], border_color: color::pack(quad.border.color), border_radius: (quad.border.radius * transformation.scale_factor()).into(), border_width: quad.border.width * transformation.scale_factor(), shadow_color: color::pack(quad.shadow.color), shadow_offset: (quad.shadow.offset * transformation.scale_factor()).into(), shadow_blur_radius: quad.shadow.blur_radius * transformation.scale_factor(), snap: quad.snap as u32, }; self.quads.add(quad, &background); } pub fn draw_paragraph( &mut self, paragraph: &Paragraph, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let paragraph = Text::Paragraph { paragraph: paragraph.downgrade(), position, color, clip_bounds, transformation, }; self.pending_text.push(paragraph); } pub fn draw_editor( &mut self, editor: &Editor, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let editor = Text::Editor { editor: editor.downgrade(), position, color, clip_bounds, transformation, }; self.pending_text.push(editor); } pub fn draw_text( &mut self, text: crate::core::Text, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let text = Text::Cached { content: text.content, bounds: Rectangle::new(position, text.bounds) * transformation, color, size: text.size * transformation.scale_factor(), line_height: text.line_height.to_absolute(text.size) * transformation.scale_factor(), font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, clip_bounds: clip_bounds * transformation, }; self.pending_text.push(text); } pub fn draw_text_raw(&mut self, raw: graphics::text::Raw, transformation: Transformation) { let raw = Text::Raw { raw, transformation, }; self.pending_text.push(raw); } pub fn draw_image(&mut self, image: Image, transformation: Transformation) { match image { Image::Raster { image, bounds, clip_bounds, } => { self.draw_raster(image, bounds, clip_bounds, transformation); } Image::Vector { svg, bounds, clip_bounds, } => { self.draw_svg(svg, bounds, clip_bounds, transformation); } } } pub fn draw_raster( &mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle, transformation: Transformation, ) { let image = Image::Raster { image: core::Image { border_radius: image.border_radius * transformation.scale_factor(), ..image }, bounds: bounds * transformation, clip_bounds: clip_bounds * transformation, }; self.images.push(image); } pub fn draw_svg( &mut self, svg: Svg, bounds: Rectangle, clip_bounds: Rectangle, transformation: Transformation, ) { let svg = Image::Vector { svg, bounds: bounds * transformation, clip_bounds: clip_bounds * transformation, }; self.images.push(svg); } pub fn draw_mesh(&mut self, mut mesh: Mesh, transformation: Transformation) { match &mut mesh { Mesh::Solid { transformation: local_transformation, .. } | Mesh::Gradient { transformation: local_transformation, .. } => { *local_transformation = *local_transformation * transformation; } } self.pending_meshes.push(mesh); } pub fn draw_mesh_group(&mut self, meshes: Vec<Mesh>, transformation: Transformation) { self.flush_meshes(); self.triangles.push(triangle::Item::Group { meshes, transformation, }); } pub fn draw_mesh_cache(&mut self, cache: mesh::Cache, transformation: Transformation) { self.flush_meshes(); self.triangles.push(triangle::Item::Cached { cache, transformation, }); } pub fn draw_text_group(&mut self, text: Vec<Text>, transformation: Transformation) { self.flush_text(); self.text.push(text::Item::Group { text, transformation, }); } pub fn draw_text_cache(&mut self, cache: text::Cache, transformation: Transformation) { self.flush_text(); self.text.push(text::Item::Cached { cache, transformation, }); } pub fn draw_primitive( &mut self, bounds: Rectangle, primitive: impl Primitive, transformation: Transformation, ) { let bounds = bounds * transformation; self.primitives .push(primitive::Instance::new(bounds, primitive)); } fn flush_meshes(&mut self) { if !self.pending_meshes.is_empty() { self.triangles.push(triangle::Item::Group { transformation: Transformation::IDENTITY, meshes: self.pending_meshes.drain(..).collect(), }); } } fn flush_text(&mut self) { if !self.pending_text.is_empty() { self.text.push(text::Item::Group { transformation: Transformation::IDENTITY, text: self.pending_text.drain(..).collect(), }); } } } impl graphics::Layer for Layer { fn with_bounds(bounds: Rectangle) -> Self { Self { bounds, ..Self::default() } } fn bounds(&self) -> Rectangle { self.bounds } fn flush(&mut self) { self.flush_meshes(); self.flush_text(); } fn resize(&mut self, bounds: Rectangle) { self.bounds = bounds; } fn reset(&mut self) { self.bounds = Rectangle::INFINITE; self.quads.clear(); self.triangles.clear(); self.primitives.clear(); self.text.clear(); self.images.clear(); self.pending_meshes.clear(); self.pending_text.clear(); } fn start(&self) -> usize { if !self.quads.is_empty() { return 1; } if !self.triangles.is_empty() { return 2; } if !self.primitives.is_empty() { return 3; } if !self.images.is_empty() { return 4; } if !self.text.is_empty() { return 5; } usize::MAX } fn end(&self) -> usize { if !self.text.is_empty() { return 5; } if !self.images.is_empty() { return 4; } if !self.primitives.is_empty() { return 3; } if !self.triangles.is_empty() { return 2; } if !self.quads.is_empty() { return 1; } 0 } fn merge(&mut self, layer: &mut Self) { self.quads.append(&mut layer.quads); self.triangles.append(&mut layer.triangles); self.primitives.append(&mut layer.primitives); self.images.append(&mut layer.images); self.text.append(&mut layer.text); } } impl Default for Layer { fn default() -> Self { Self { bounds: Rectangle::INFINITE, quads: quad::Batch::default(), triangles: triangle::Batch::default(), primitives: primitive::Batch::default(), text: text::Batch::default(), images: image::Batch::default(), pending_meshes: Vec::new(), pending_text: Vec::new(), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/text.rs
wgpu/src/text.rs
use crate::core::alignment; use crate::core::text::Alignment; use crate::core::{Rectangle, Size, Transformation}; use crate::graphics::cache; use crate::graphics::color; use crate::graphics::text::cache::{self as text_cache, Cache as BufferCache}; use crate::graphics::text::{Editor, Paragraph, font_system, to_color}; use rustc_hash::FxHashMap; use std::collections::hash_map; use std::sync::atomic::{self, AtomicU64}; use std::sync::{self, Arc, RwLock}; pub use crate::graphics::Text; const COLOR_MODE: cryoglyph::ColorMode = if color::GAMMA_CORRECTION { cryoglyph::ColorMode::Accurate } else { cryoglyph::ColorMode::Web }; pub type Batch = Vec<Item>; #[derive(Debug)] pub enum Item { Group { transformation: Transformation, text: Vec<Text>, }, Cached { transformation: Transformation, cache: Cache, }, } #[derive(Debug, Clone)] pub struct Cache { id: Id, group: cache::Group, text: Arc<[Text]>, version: usize, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id(u64); impl Cache { pub fn new(group: cache::Group, text: Vec<Text>) -> Option<Self> { static NEXT_ID: AtomicU64 = AtomicU64::new(0); if text.is_empty() { return None; } Some(Self { id: Id(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)), group, text: Arc::from(text), version: 0, }) } pub fn update(&mut self, text: Vec<Text>) { if self.text.is_empty() && text.is_empty() { return; } self.text = Arc::from(text); self.version += 1; } } struct Upload { renderer: cryoglyph::TextRenderer, buffer_cache: BufferCache, transformation: Transformation, version: usize, group_version: usize, text: sync::Weak<[Text]>, _atlas: sync::Weak<()>, } #[derive(Default)] pub struct Storage { groups: FxHashMap<cache::Group, Group>, uploads: FxHashMap<Id, Upload>, } struct Group { atlas: cryoglyph::TextAtlas, version: usize, should_trim: bool, handle: Arc<()>, // Keeps track of active uploads } impl Storage { fn get(&self, cache: &Cache) -> Option<(&cryoglyph::TextAtlas, &Upload)> { if cache.text.is_empty() { return None; } self.groups .get(&cache.group) .map(|group| &group.atlas) .zip(self.uploads.get(&cache.id)) } fn prepare( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, viewport: &cryoglyph::Viewport, encoder: &mut wgpu::CommandEncoder, format: wgpu::TextureFormat, state: &cryoglyph::Cache, cache: &Cache, new_transformation: Transformation, bounds: Rectangle, ) { let group_count = self.groups.len(); let group = self.groups.entry(cache.group).or_insert_with(|| { log::debug!( "New text atlas: {:?} (total: {})", cache.group, group_count + 1 ); Group { atlas: cryoglyph::TextAtlas::with_color_mode( device, queue, state, format, COLOR_MODE, ), version: 0, should_trim: false, handle: Arc::new(()), } }); match self.uploads.entry(cache.id) { hash_map::Entry::Occupied(entry) => { let upload = entry.into_mut(); if upload.version != cache.version || upload.group_version != group.version || upload.transformation != new_transformation { if !cache.text.is_empty() { let _ = prepare( device, queue, viewport, encoder, &mut upload.renderer, &mut group.atlas, &mut upload.buffer_cache, &cache.text, bounds, new_transformation, ); } // Only trim if glyphs have changed group.should_trim = group.should_trim || upload.version != cache.version; upload.text = Arc::downgrade(&cache.text); upload.version = cache.version; upload.group_version = group.version; upload.transformation = new_transformation; upload.buffer_cache.trim(); } } hash_map::Entry::Vacant(entry) => { let mut renderer = cryoglyph::TextRenderer::new( &mut group.atlas, device, wgpu::MultisampleState::default(), None, ); let mut buffer_cache = BufferCache::new(); if !cache.text.is_empty() { let _ = prepare( device, queue, viewport, encoder, &mut renderer, &mut group.atlas, &mut buffer_cache, &cache.text, bounds, new_transformation, ); } let _ = entry.insert(Upload { renderer, buffer_cache, transformation: new_transformation, version: 0, group_version: group.version, text: Arc::downgrade(&cache.text), _atlas: Arc::downgrade(&group.handle), }); group.should_trim = cache.group.is_singleton(); log::debug!( "New text upload: {} (total: {})", cache.id.0, self.uploads.len() ); } } } pub fn trim(&mut self) { self.uploads .retain(|_id, upload| upload.text.strong_count() > 0); self.groups.retain(|id, group| { let active_uploads = Arc::weak_count(&group.handle); if active_uploads == 0 { log::debug!("Dropping text atlas: {id:?}"); return false; } if group.should_trim { log::trace!("Trimming text atlas: {id:?}"); group.atlas.trim(); group.should_trim = false; // We only need to worry about glyph fighting // when the atlas may be shared by multiple // uploads. if !id.is_singleton() { log::debug!( "Invalidating text atlas: {id:?} \ (uploads: {active_uploads})" ); group.version += 1; } } true }); } } pub struct Viewport(cryoglyph::Viewport); impl Viewport { pub fn update(&mut self, queue: &wgpu::Queue, resolution: Size<u32>) { self.0.update( queue, cryoglyph::Resolution { width: resolution.width, height: resolution.height, }, ); } } #[derive(Clone)] pub struct Pipeline { format: wgpu::TextureFormat, cache: cryoglyph::Cache, atlas: Arc<RwLock<cryoglyph::TextAtlas>>, } impl Pipeline { pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { let cache = cryoglyph::Cache::new(device); let atlas = cryoglyph::TextAtlas::with_color_mode(device, queue, &cache, format, COLOR_MODE); Pipeline { format, cache, atlas: Arc::new(RwLock::new(atlas)), } } pub fn create_viewport(&self, device: &wgpu::Device) -> Viewport { Viewport(cryoglyph::Viewport::new(device, &self.cache)) } pub fn trim(&self) { self.atlas.write().expect("Write text atlas").trim(); } } #[derive(Default)] pub struct State { renderers: Vec<cryoglyph::TextRenderer>, prepare_layer: usize, cache: BufferCache, storage: Storage, } impl State { pub fn new() -> Self { Self::default() } pub fn prepare( &mut self, pipeline: &Pipeline, device: &wgpu::Device, queue: &wgpu::Queue, viewport: &Viewport, encoder: &mut wgpu::CommandEncoder, batch: &Batch, layer_bounds: Rectangle, layer_transformation: Transformation, ) { let mut atlas = pipeline.atlas.write().expect("Write to text atlas"); for item in batch { match item { Item::Group { transformation, text, } => { if self.renderers.len() <= self.prepare_layer { self.renderers.push(cryoglyph::TextRenderer::new( &mut atlas, device, wgpu::MultisampleState::default(), None, )); } let renderer = &mut self.renderers[self.prepare_layer]; let result = prepare( device, queue, &viewport.0, encoder, renderer, &mut atlas, &mut self.cache, text, layer_bounds * layer_transformation, layer_transformation * *transformation, ); match result { Ok(()) => { self.prepare_layer += 1; } Err(cryoglyph::PrepareError::AtlasFull) => { // If the atlas cannot grow, then all bets are off. // Instead of panicking, we will just pray that the result // will be somewhat readable... } } } Item::Cached { transformation, cache, } => { self.storage.prepare( device, queue, &viewport.0, encoder, pipeline.format, &pipeline.cache, cache, layer_transformation * *transformation, layer_bounds * layer_transformation, ); } } } } pub fn render<'a>( &'a self, pipeline: &'a Pipeline, viewport: &'a Viewport, start: usize, batch: &'a Batch, bounds: Rectangle<u32>, render_pass: &mut wgpu::RenderPass<'a>, ) -> usize { let atlas = pipeline.atlas.read().expect("Read text atlas"); let mut layer_count = 0; render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); for item in batch { match item { Item::Group { .. } => { let renderer = &self.renderers[start + layer_count]; renderer .render(&atlas, &viewport.0, render_pass) .expect("Render text"); layer_count += 1; } Item::Cached { cache, .. } => { if let Some((atlas, upload)) = self.storage.get(cache) { upload .renderer .render(atlas, &viewport.0, render_pass) .expect("Render cached text"); } } } } layer_count } pub fn trim(&mut self) { self.cache.trim(); self.storage.trim(); self.prepare_layer = 0; } } fn prepare( device: &wgpu::Device, queue: &wgpu::Queue, viewport: &cryoglyph::Viewport, encoder: &mut wgpu::CommandEncoder, renderer: &mut cryoglyph::TextRenderer, atlas: &mut cryoglyph::TextAtlas, buffer_cache: &mut BufferCache, sections: &[Text], layer_bounds: Rectangle, layer_transformation: Transformation, ) -> Result<(), cryoglyph::PrepareError> { let mut font_system = font_system().write().expect("Write font system"); let font_system = font_system.raw(); enum Allocation { Paragraph(Paragraph), Editor(Editor), Cache(text_cache::KeyHash), Raw(Arc<cryoglyph::Buffer>), } let allocations: Vec<_> = sections .iter() .map(|section| match section { Text::Paragraph { paragraph, .. } => paragraph.upgrade().map(Allocation::Paragraph), Text::Editor { editor, .. } => editor.upgrade().map(Allocation::Editor), Text::Cached { content, bounds, size, line_height, font, shaping, align_x, .. } => { let (key, _) = buffer_cache.allocate( font_system, text_cache::Key { content, size: f32::from(*size), line_height: f32::from(*line_height), font: *font, align_x: *align_x, bounds: Size { width: bounds.width, height: bounds.height, }, shaping: *shaping, }, ); Some(Allocation::Cache(key)) } Text::Raw { raw, .. } => raw.buffer.upgrade().map(Allocation::Raw), }) .collect(); let text_areas = sections .iter() .zip(allocations.iter()) .filter_map(|(section, allocation)| { let (buffer, hint_factor, position, color, clip_bounds, transformation) = match section { Text::Paragraph { position, color, clip_bounds, transformation, .. } => { use crate::core::text::Paragraph as _; let Some(Allocation::Paragraph(paragraph)) = allocation else { return None; }; ( paragraph.buffer(), paragraph.hint_factor(), *position, *color, *clip_bounds, *transformation, ) } Text::Editor { position, color, clip_bounds, transformation, .. } => { use crate::core::text::Editor as _; let Some(Allocation::Editor(editor)) = allocation else { return None; }; ( editor.buffer(), editor.hint_factor(), *position, *color, *clip_bounds, *transformation, ) } Text::Cached { bounds, align_x, align_y, color, clip_bounds, .. } => { let Some(Allocation::Cache(key)) = allocation else { return None; }; let entry = buffer_cache.get(key).expect("Get cached buffer"); let mut position = bounds.position(); position.x = match align_x { Alignment::Default | Alignment::Left | Alignment::Justified => position.x, Alignment::Center => position.x - entry.min_bounds.width / 2.0, Alignment::Right => position.x - entry.min_bounds.width, }; position.y = match align_y { alignment::Vertical::Top => position.y, alignment::Vertical::Center => position.y - entry.min_bounds.height / 2.0, alignment::Vertical::Bottom => position.y - entry.min_bounds.height, }; ( &entry.buffer, None, position, *color, *clip_bounds, Transformation::IDENTITY, ) } Text::Raw { raw, transformation, } => { let Some(Allocation::Raw(buffer)) = allocation else { return None; }; ( buffer.as_ref(), None, raw.position, raw.color, raw.clip_bounds, *transformation, ) } }; let clip_bounds = layer_bounds .intersection(&(clip_bounds * transformation * layer_transformation))?; let mut position = position * transformation * layer_transformation; let mut scale = transformation.scale_factor() * layer_transformation.scale_factor(); if let Some(hint_factor) = hint_factor { let font_size = (buffer.metrics().font_size / hint_factor).round() as u32; position.x = position.x.round() // This is a hack! Empirically and cluelessly derived // It tries to nudge hinted text to improve rasterization + if font_size.is_multiple_of(2) { 0.25 } else if font_size.is_multiple_of(5) { -0.45 // Deliberately avoid 0.5 to circumvent erratic rounding due to floating precision errors } else { -0.25 }; scale /= hint_factor; } Some(cryoglyph::TextArea { buffer, left: position.x, top: position.y, scale, bounds: cryoglyph::TextBounds { left: clip_bounds.x.round() as i32, top: clip_bounds.y.round() as i32, right: (clip_bounds.x + clip_bounds.width).round() as i32, bottom: (clip_bounds.y + clip_bounds.height).round() as i32, }, default_color: to_color(color), }) }); renderer.prepare( device, queue, encoder, font_system, atlas, viewport, text_areas, &mut cryoglyph::SwashCache::new(), ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/primitive.rs
wgpu/src/primitive.rs
//! Draw custom primitives. use crate::core::{self, Rectangle}; use crate::graphics::Viewport; use crate::graphics::futures::{MaybeSend, MaybeSync}; use rustc_hash::FxHashMap; use std::any::{Any, TypeId}; use std::fmt::Debug; /// A batch of primitives. pub type Batch = Vec<Instance>; /// A set of methods which allows a [`Primitive`] to be rendered. pub trait Primitive: Debug + MaybeSend + MaybeSync + 'static { /// The shared renderer of this [`Primitive`]. /// /// Normally, this will contain a bunch of [`wgpu`] state; like /// a rendering pipeline, buffers, and textures. /// /// All instances of this [`Primitive`] type will share the same /// [`Renderer`]. type Pipeline: Pipeline + MaybeSend + MaybeSync; /// Processes the [`Primitive`], allowing for GPU buffer allocation. fn prepare( &self, pipeline: &mut Self::Pipeline, device: &wgpu::Device, queue: &wgpu::Queue, bounds: &Rectangle, viewport: &Viewport, ); /// Draws the [`Primitive`] in the given [`wgpu::RenderPass`]. /// /// When possible, this should be implemented over [`render`](Self::render) /// since reusing the existing render pass should be considerably more /// efficient than issuing a new one. /// /// The viewport and scissor rect of the render pass provided is set /// to the bounds and clip bounds of the [`Primitive`], respectively. /// /// If you have complex composition needs, then you can leverage /// [`render`](Self::render) by returning `false` here. /// /// By default, it does nothing and returns `false`. fn draw(&self, _pipeline: &Self::Pipeline, _render_pass: &mut wgpu::RenderPass<'_>) -> bool { false } /// Renders the [`Primitive`], using the given [`wgpu::CommandEncoder`]. /// /// This will only be called if [`draw`](Self::draw) returns `false`. /// /// By default, it does nothing. fn render( &self, _pipeline: &Self::Pipeline, _encoder: &mut wgpu::CommandEncoder, _target: &wgpu::TextureView, _clip_bounds: &Rectangle<u32>, ) { } } /// The pipeline of a graphics [`Primitive`]. pub trait Pipeline: Any + MaybeSend + MaybeSync { /// Creates the [`Pipeline`] of a [`Primitive`]. /// /// This will only be called once, when the first [`Primitive`] with this kind /// of [`Pipeline`] is encountered. fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self where Self: Sized; /// Trims any cached data in the [`Pipeline`]. /// /// This will normally be called at the end of a frame. fn trim(&mut self) {} } pub(crate) trait Stored: Debug + MaybeSend + MaybeSync + 'static { fn prepare( &self, storage: &mut Storage, device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, bounds: &Rectangle, viewport: &Viewport, ); fn draw(&self, storage: &Storage, render_pass: &mut wgpu::RenderPass<'_>) -> bool; fn render( &self, storage: &Storage, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, clip_bounds: &Rectangle<u32>, ); } #[derive(Debug)] struct BlackBox<P: Primitive> { primitive: P, } impl<P: Primitive> Stored for BlackBox<P> { fn prepare( &self, storage: &mut Storage, device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, bounds: &Rectangle, viewport: &Viewport, ) { if !storage.has::<P>() { storage.store::<P, _>(P::Pipeline::new(device, queue, format)); } let renderer = storage .get_mut::<P>() .expect("renderer should be initialized") .downcast_mut::<P::Pipeline>() .expect("renderer should have the proper type"); self.primitive .prepare(renderer, device, queue, bounds, viewport); } fn draw(&self, storage: &Storage, render_pass: &mut wgpu::RenderPass<'_>) -> bool { let renderer = storage .get::<P>() .expect("renderer should be initialized") .downcast_ref::<P::Pipeline>() .expect("renderer should have the proper type"); self.primitive.draw(renderer, render_pass) } fn render( &self, storage: &Storage, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, clip_bounds: &Rectangle<u32>, ) { let renderer = storage .get::<P>() .expect("renderer should be initialized") .downcast_ref::<P::Pipeline>() .expect("renderer should have the proper type"); self.primitive .render(renderer, encoder, target, clip_bounds); } } #[derive(Debug)] /// An instance of a specific [`Primitive`]. pub struct Instance { /// The bounds of the [`Instance`]. pub(crate) bounds: Rectangle, /// The [`Primitive`] to render. pub(crate) primitive: Box<dyn Stored>, } impl Instance { /// Creates a new [`Instance`] with the given [`Primitive`]. pub fn new(bounds: Rectangle, primitive: impl Primitive) -> Self { Instance { bounds, primitive: Box::new(BlackBox { primitive }), } } } /// A renderer than can draw custom primitives. pub trait Renderer: core::Renderer { /// Draws a custom primitive. fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl Primitive); } /// Stores custom, user-provided types. #[derive(Default)] pub struct Storage { pipelines: FxHashMap<TypeId, Box<dyn Pipeline>>, } impl Storage { /// Returns `true` if `Storage` contains a type `T`. pub fn has<T: 'static>(&self) -> bool { self.pipelines.contains_key(&TypeId::of::<T>()) } /// Inserts the data `T` in to [`Storage`]. pub fn store<T: 'static, P: Pipeline>(&mut self, pipeline: P) { let _ = self.pipelines.insert(TypeId::of::<T>(), Box::new(pipeline)); } /// Returns a reference to the data with type `T` if it exists in [`Storage`]. pub fn get<T: 'static>(&self) -> Option<&dyn Any> { self.pipelines .get(&TypeId::of::<T>()) .map(|pipeline| pipeline.as_ref() as &dyn Any) } /// Returns a mutable reference to the data with type `T` if it exists in [`Storage`]. pub fn get_mut<T: 'static>(&mut self) -> Option<&mut dyn Any> { self.pipelines .get_mut(&TypeId::of::<T>()) .map(|pipeline| pipeline.as_mut() as &mut dyn Any) } /// Trims the cache of all the pipelines in the [`Storage`]. pub fn trim(&mut self) { for pipeline in self.pipelines.values_mut() { pipeline.trim(); } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/window.rs
wgpu/src/window.rs
//! Display rendering results on windows. pub mod compositor; pub use compositor::Compositor; pub use wgpu::Surface;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/quad.rs
wgpu/src/quad.rs
mod gradient; mod solid; use gradient::Gradient; use solid::Solid; use crate::core::{Background, Rectangle, Transformation}; use crate::graphics; use crate::graphics::color; use bytemuck::{Pod, Zeroable}; use std::mem; const INITIAL_INSTANCES: usize = 2_000; /// The properties of a quad. #[derive(Clone, Copy, Debug, Pod, Zeroable)] #[repr(C)] pub struct Quad { /// The position of the [`Quad`]. pub position: [f32; 2], /// The size of the [`Quad`]. pub size: [f32; 2], /// The border color of the [`Quad`], in __linear RGB__. pub border_color: color::Packed, /// The border radii of the [`Quad`]. pub border_radius: [f32; 4], /// The border width of the [`Quad`]. pub border_width: f32, /// The shadow color of the [`Quad`]. pub shadow_color: color::Packed, /// The shadow offset of the [`Quad`]. pub shadow_offset: [f32; 2], /// The shadow blur radius of the [`Quad`]. pub shadow_blur_radius: f32, /// Whether the [`Quad`] should be snapped to the pixel grid. pub snap: u32, } #[derive(Debug, Clone)] pub struct Pipeline { solid: solid::Pipeline, gradient: gradient::Pipeline, constant_layout: wgpu::BindGroupLayout, } #[derive(Default)] pub struct State { layers: Vec<Layer>, prepare_layer: usize, } impl State { pub fn new() -> Self { Self::default() } pub fn prepare( &mut self, pipeline: &Pipeline, device: &wgpu::Device, belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, quads: &Batch, transformation: Transformation, scale: f32, ) { if self.layers.len() <= self.prepare_layer { self.layers .push(Layer::new(device, &pipeline.constant_layout)); } let layer = &mut self.layers[self.prepare_layer]; layer.prepare(device, encoder, belt, quads, transformation, scale); self.prepare_layer += 1; } pub fn render<'a>( &'a self, pipeline: &'a Pipeline, layer: usize, bounds: Rectangle<u32>, quads: &Batch, render_pass: &mut wgpu::RenderPass<'a>, ) { if let Some(layer) = self.layers.get(layer) { render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); let mut solid_offset = 0; let mut gradient_offset = 0; for (kind, count) in &quads.order { match kind { Kind::Solid => { pipeline.solid.render( render_pass, &layer.constants, &layer.solid, solid_offset..(solid_offset + count), ); solid_offset += count; } Kind::Gradient => { pipeline.gradient.render( render_pass, &layer.constants, &layer.gradient, gradient_offset..(gradient_offset + count), ); gradient_offset += count; } } } } } pub fn trim(&mut self) { self.prepare_layer = 0; } } impl Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipeline { let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu::quad uniforms layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new( mem::size_of::<Uniforms>() as wgpu::BufferAddress ), }, count: None, }], }); Self { solid: solid::Pipeline::new(device, format, &constant_layout), gradient: gradient::Pipeline::new(device, format, &constant_layout), constant_layout, } } } #[derive(Debug)] pub struct Layer { constants: wgpu::BindGroup, constants_buffer: wgpu::Buffer, solid: solid::Layer, gradient: gradient::Layer, } impl Layer { pub fn new(device: &wgpu::Device, constant_layout: &wgpu::BindGroupLayout) -> Self { let constants_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("iced_wgpu::quad uniforms buffer"), size: mem::size_of::<Uniforms>() as wgpu::BufferAddress, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::quad uniforms bind group"), layout: constant_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: constants_buffer.as_entire_binding(), }], }); Self { constants, constants_buffer, solid: solid::Layer::new(device), gradient: gradient::Layer::new(device), } } pub fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, quads: &Batch, transformation: Transformation, scale: f32, ) { self.update(device, encoder, belt, transformation, scale); if !quads.solids.is_empty() { self.solid.prepare(device, encoder, belt, &quads.solids); } if !quads.gradients.is_empty() { self.gradient .prepare(device, encoder, belt, &quads.gradients); } } pub fn update( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, transformation: Transformation, scale: f32, ) { let uniforms = Uniforms::new(transformation, scale); let bytes = bytemuck::bytes_of(&uniforms); belt.write_buffer( encoder, &self.constants_buffer, 0, (bytes.len() as u64).try_into().expect("Sized uniforms"), device, ) .copy_from_slice(bytes); } } /// A group of [`Quad`]s rendered together. #[derive(Default, Debug)] pub struct Batch { /// The solid quads of the [`Layer`]. solids: Vec<Solid>, /// The gradient quads of the [`Layer`]. gradients: Vec<Gradient>, /// The quad order of the [`Layer`]. order: Order, } /// The quad order of a [`Layer`]; stored as a tuple of the quad type & its count. type Order = Vec<(Kind, usize)>; impl Batch { /// Returns true if there are no quads of any type in [`Quads`]. pub fn is_empty(&self) -> bool { self.solids.is_empty() && self.gradients.is_empty() } /// Adds a [`Quad`] with the provided `Background` type to the quad [`Layer`]. pub fn add(&mut self, quad: Quad, background: &Background) { let kind = match background { Background::Color(color) => { self.solids.push(Solid { color: color::pack(*color), quad, }); Kind::Solid } Background::Gradient(gradient) => { self.gradients.push(Gradient { gradient: graphics::gradient::pack( gradient, Rectangle::new(quad.position.into(), quad.size.into()), ), quad, }); Kind::Gradient } }; match self.order.last_mut() { Some((last_kind, count)) if kind == *last_kind => { *count += 1; } _ => { self.order.push((kind, 1)); } } } pub fn clear(&mut self) { self.solids.clear(); self.gradients.clear(); self.order.clear(); } pub fn append(&mut self, batch: &mut Batch) { self.solids.append(&mut batch.solids); self.gradients.append(&mut batch.gradients); self.order.append(&mut batch.order); } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] /// The kind of a quad. enum Kind { /// A solid quad Solid, /// A gradient quad Gradient, } fn color_target_state(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] { [Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })] } #[repr(C)] #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] struct Uniforms { transform: [f32; 16], scale: f32, // Uniforms must be aligned to their largest member, // this uses a mat4x4<f32> which aligns to 16, so align to that _padding: [f32; 3], } impl Uniforms { fn new(transformation: Transformation, scale: f32) -> Uniforms { Self { transform: *transformation.as_ref(), scale, _padding: [0.0; 3], } } } impl Default for Uniforms { fn default() -> Self { Self { transform: *Transformation::IDENTITY.as_ref(), scale: 1.0, _padding: [0.0; 3], } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/buffer.rs
wgpu/src/buffer.rs
use std::marker::PhantomData; use std::num::NonZeroU64; use std::ops::RangeBounds; pub const MAX_WRITE_SIZE: usize = 100 * 1024; const MAX_WRITE_SIZE_U64: NonZeroU64 = NonZeroU64::new(MAX_WRITE_SIZE as u64).expect("MAX_WRITE_SIZE must be non-zero"); #[derive(Debug)] pub struct Buffer<T> { label: &'static str, size: u64, usage: wgpu::BufferUsages, pub(crate) raw: wgpu::Buffer, type_: PhantomData<T>, } impl<T: bytemuck::Pod> Buffer<T> { pub fn new( device: &wgpu::Device, label: &'static str, amount: usize, usage: wgpu::BufferUsages, ) -> Self { let size = next_copy_size::<T>(amount); let raw = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false, }); Self { label, size, usage, raw, type_: PhantomData, } } pub fn resize(&mut self, device: &wgpu::Device, new_count: usize) -> bool { let new_size = next_copy_size::<T>(new_count); if self.size < new_size { self.raw = device.create_buffer(&wgpu::BufferDescriptor { label: Some(self.label), size: new_size, usage: self.usage, mapped_at_creation: false, }); self.size = new_size; true } else { false } } /// Returns the size of the written bytes. pub fn write( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, offset: usize, contents: &[T], ) -> usize { let bytes: &[u8] = bytemuck::cast_slice(contents); let mut bytes_written = 0; // Split write into multiple chunks if necessary while bytes_written + MAX_WRITE_SIZE < bytes.len() { belt.write_buffer( encoder, &self.raw, (offset + bytes_written) as u64, MAX_WRITE_SIZE_U64, device, ) .copy_from_slice(&bytes[bytes_written..bytes_written + MAX_WRITE_SIZE]); bytes_written += MAX_WRITE_SIZE; } // There will always be some bytes left, since the previous // loop guarantees `bytes_written < bytes.len()` let bytes_left = ((bytes.len() - bytes_written) as u64) .try_into() .expect("non-empty write"); // Write them belt.write_buffer( encoder, &self.raw, (offset + bytes_written) as u64, bytes_left, device, ) .copy_from_slice(&bytes[bytes_written..]); bytes.len() } pub fn slice(&self, bounds: impl RangeBounds<wgpu::BufferAddress>) -> wgpu::BufferSlice<'_> { self.raw.slice(bounds) } pub fn range(&self, start: usize, end: usize) -> wgpu::BufferSlice<'_> { self.slice( start as u64 * std::mem::size_of::<T>() as u64 ..end as u64 * std::mem::size_of::<T>() as u64, ) } } fn next_copy_size<T>(amount: usize) -> u64 { let align_mask = wgpu::COPY_BUFFER_ALIGNMENT - 1; (((std::mem::size_of::<T>() * amount).next_power_of_two() as u64 + align_mask) & !align_mask) .max(wgpu::COPY_BUFFER_ALIGNMENT) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/color.rs
wgpu/src/color.rs
use std::borrow::Cow; use wgpu::util::DeviceExt; pub fn convert( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: wgpu::Texture, format: wgpu::TextureFormat, ) -> wgpu::Texture { if source.format() == format { return source; } let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("iced_wgpu.offscreen.sampler"), ..wgpu::SamplerDescriptor::default() }); #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] #[repr(C)] struct Ratio { u: f32, v: f32, // Padding field for 16-byte alignment. // See https://docs.rs/wgpu/latest/wgpu/struct.DownlevelFlags.html#associatedconstant.BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED _padding: [f32; 2], } let ratio = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("iced-wgpu::triangle::msaa ratio"), contents: bytemuck::bytes_of(&Ratio { u: 1.0, v: 1.0, _padding: [0.0; 2], }), usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, }); let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu.offscreen.blit.sampler_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::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, ], }); let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu.offscreen.sampler.bind_group"), layout: &constant_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Sampler(&sampler), }, wgpu::BindGroupEntry { binding: 1, resource: ratio.as_entire_binding(), }, ], }); let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu.offscreen.blit.texture_layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, 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 pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu.offscreen.blit.pipeline_layout"), bind_group_layouts: &[&constant_layout, &texture_layout], push_constant_ranges: &[], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.offscreen.blit.shader"), source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader/blit.wgsl"))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu.offscreen.blit.pipeline"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, 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::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..wgpu::PrimitiveState::default() }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, cache: None, }); let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu.offscreen.conversion.source_texture"), size: source.size(), mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let view = &texture.create_view(&wgpu::TextureViewDescriptor::default()); let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu.offscreen.blit.texture_bind_group"), layout: &texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView( &source.create_view(&wgpu::TextureViewDescriptor::default()), ), }], }); let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu.offscreen.blit.render_pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); pass.set_pipeline(&pipeline); pass.set_bind_group(0, &constant_bind_group, &[]); pass.set_bind_group(1, &texture_bind_group, &[]); pass.draw(0..6, 0..1); texture }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/triangle.rs
wgpu/src/triangle.rs
//! Draw meshes of triangles. mod msaa; use crate::Buffer; use crate::core::{Point, Rectangle, Size, Transformation, Vector}; use crate::graphics::Antialiasing; use crate::graphics::mesh::{self, Mesh}; use rustc_hash::FxHashMap; use std::collections::hash_map; use std::sync::Weak; const INITIAL_INDEX_COUNT: usize = 1_000; const INITIAL_VERTEX_COUNT: usize = 1_000; pub type Batch = Vec<Item>; #[derive(Debug)] pub enum Item { Group { transformation: Transformation, meshes: Vec<Mesh>, }, Cached { transformation: Transformation, cache: mesh::Cache, }, } #[derive(Debug)] struct Upload { layer: Layer, transformation: Transformation, version: usize, batch: Weak<[Mesh]>, } #[derive(Debug, Default)] pub struct Storage { uploads: FxHashMap<mesh::Id, Upload>, } impl Storage { pub fn new() -> Self { Self::default() } fn get(&self, cache: &mesh::Cache) -> Option<&Upload> { if cache.is_empty() { return None; } self.uploads.get(&cache.id()) } fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, solid: &solid::Pipeline, gradient: &gradient::Pipeline, cache: &mesh::Cache, new_transformation: Transformation, ) { match self.uploads.entry(cache.id()) { hash_map::Entry::Occupied(entry) => { let upload = entry.into_mut(); if !cache.is_empty() && (upload.version != cache.version() || upload.transformation != new_transformation) { upload.layer.prepare( device, encoder, belt, solid, gradient, cache.batch(), new_transformation, ); upload.batch = cache.downgrade(); upload.version = cache.version(); upload.transformation = new_transformation; } } hash_map::Entry::Vacant(entry) => { let mut layer = Layer::new(device, solid, gradient); layer.prepare( device, encoder, belt, solid, gradient, cache.batch(), new_transformation, ); let _ = entry.insert(Upload { layer, transformation: new_transformation, version: 0, batch: cache.downgrade(), }); log::debug!( "New mesh upload: {:?} (total: {})", cache.id(), self.uploads.len() ); } } } pub fn trim(&mut self) { self.uploads .retain(|_id, upload| upload.batch.strong_count() > 0); } } #[derive(Debug, Clone)] pub struct Pipeline { msaa: Option<msaa::Pipeline>, solid: solid::Pipeline, gradient: gradient::Pipeline, } pub struct State { msaa: Option<msaa::State>, layers: Vec<Layer>, prepare_layer: usize, storage: Storage, } impl State { pub fn new(device: &wgpu::Device, pipeline: &Pipeline) -> Self { Self { msaa: pipeline .msaa .as_ref() .map(|pipeline| msaa::State::new(device, pipeline)), layers: Vec::new(), prepare_layer: 0, storage: Storage::new(), } } pub fn prepare( &mut self, pipeline: &Pipeline, device: &wgpu::Device, belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, items: &[Item], scale: Transformation, target_size: Size<u32>, ) { let projection = if let Some((state, pipeline)) = self.msaa.as_mut().zip(pipeline.msaa.as_ref()) { state.prepare(device, encoder, belt, pipeline, target_size) * scale } else { Transformation::orthographic(target_size.width, target_size.height) * scale }; for item in items { match item { Item::Group { transformation, meshes, } => { if self.layers.len() <= self.prepare_layer { self.layers .push(Layer::new(device, &pipeline.solid, &pipeline.gradient)); } let layer = &mut self.layers[self.prepare_layer]; layer.prepare( device, encoder, belt, &pipeline.solid, &pipeline.gradient, meshes, projection * *transformation, ); self.prepare_layer += 1; } Item::Cached { transformation, cache, } => { self.storage.prepare( device, encoder, belt, &pipeline.solid, &pipeline.gradient, cache, projection * *transformation, ); } } } } pub fn render( &mut self, pipeline: &Pipeline, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, start: usize, batch: &Batch, bounds: Rectangle, screen_transformation: Transformation, ) -> usize { let mut layer_count = 0; let items = batch.iter().filter_map(|item| match item { Item::Group { transformation, meshes, } => { let layer = &self.layers[start + layer_count]; layer_count += 1; Some(( layer, meshes.as_slice(), screen_transformation * *transformation, )) } Item::Cached { transformation, cache, } => { let upload = self.storage.get(cache)?; Some(( &upload.layer, cache.batch(), screen_transformation * *transformation, )) } }); render( encoder, target, self.msaa.as_ref().zip(pipeline.msaa.as_ref()), &pipeline.solid, &pipeline.gradient, bounds, items, ); layer_count } pub fn trim(&mut self) { self.storage.trim(); self.prepare_layer = 0; } } impl Pipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, antialiasing: Option<Antialiasing>, ) -> Pipeline { Pipeline { msaa: antialiasing.map(|a| msaa::Pipeline::new(device, format, a)), solid: solid::Pipeline::new(device, format, antialiasing), gradient: gradient::Pipeline::new(device, format, antialiasing), } } } fn render<'a>( encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, mut msaa: Option<(&msaa::State, &msaa::Pipeline)>, solid: &solid::Pipeline, gradient: &gradient::Pipeline, bounds: Rectangle, group: impl Iterator<Item = (&'a Layer, &'a [Mesh], Transformation)>, ) { { let mut render_pass = if let Some((_state, pipeline)) = &mut msaa { pipeline.render_pass(encoder) } else { encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu.triangle.render_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: None, timestamp_writes: None, occlusion_query_set: None, }) }; for (layer, meshes, transformation) in group { layer.render( solid, gradient, meshes, bounds, transformation, &mut render_pass, ); } } if let Some((state, pipeline)) = msaa { state.render(pipeline, encoder, target); } } #[derive(Debug)] pub struct Layer { index_buffer: Buffer<u32>, solid: solid::Layer, gradient: gradient::Layer, } impl Layer { fn new(device: &wgpu::Device, solid: &solid::Pipeline, gradient: &gradient::Pipeline) -> Self { Self { index_buffer: Buffer::new( device, "iced_wgpu.triangle.index_buffer", INITIAL_INDEX_COUNT, wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, ), solid: solid::Layer::new(device, &solid.constants_layout), gradient: gradient::Layer::new(device, &gradient.constants_layout), } } fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, solid: &solid::Pipeline, gradient: &gradient::Pipeline, meshes: &[Mesh], transformation: Transformation, ) { // Count the total amount of vertices & indices we need to handle let count = mesh::attribute_count_of(meshes); // Then we ensure the current attribute buffers are big enough, resizing if necessary. // We are not currently using the return value of these functions as we have no system in // place to calculate mesh diff, or to know whether or not that would be more performant for // the majority of use cases. Therefore we will write GPU data every frame (for now). let _ = self.index_buffer.resize(device, count.indices); let _ = self.solid.vertices.resize(device, count.solid_vertices); let _ = self .gradient .vertices .resize(device, count.gradient_vertices); if self.solid.uniforms.resize(device, count.solids) { self.solid.constants = solid::Layer::bind_group(device, &self.solid.uniforms.raw, &solid.constants_layout); } if self.gradient.uniforms.resize(device, count.gradients) { self.gradient.constants = gradient::Layer::bind_group( device, &self.gradient.uniforms.raw, &gradient.constants_layout, ); } let mut solid_vertex_offset = 0; let mut solid_uniform_offset = 0; let mut gradient_vertex_offset = 0; let mut gradient_uniform_offset = 0; let mut index_offset = 0; for mesh in meshes { let clip_bounds = mesh.clip_bounds() * transformation; let snap_distance = clip_bounds .snap() .map(|snapped_bounds| { Point::new(snapped_bounds.x as f32, snapped_bounds.y as f32) - clip_bounds.position() }) .unwrap_or(Vector::ZERO); let uniforms = Uniforms::new( transformation * mesh.transformation() * Transformation::translate(snap_distance.x, snap_distance.y), ); let indices = mesh.indices(); index_offset += self .index_buffer .write(device, encoder, belt, index_offset, indices); match mesh { Mesh::Solid { buffers, .. } => { solid_vertex_offset += self.solid.vertices.write( device, encoder, belt, solid_vertex_offset, &buffers.vertices, ); solid_uniform_offset += self.solid.uniforms.write( device, encoder, belt, solid_uniform_offset, &[uniforms], ); } Mesh::Gradient { buffers, .. } => { gradient_vertex_offset += self.gradient.vertices.write( device, encoder, belt, gradient_vertex_offset, &buffers.vertices, ); gradient_uniform_offset += self.gradient.uniforms.write( device, encoder, belt, gradient_uniform_offset, &[uniforms], ); } } } } fn render<'a>( &'a self, solid: &'a solid::Pipeline, gradient: &'a gradient::Pipeline, meshes: &[Mesh], bounds: Rectangle, transformation: Transformation, render_pass: &mut wgpu::RenderPass<'a>, ) { let mut num_solids = 0; let mut num_gradients = 0; let mut solid_offset = 0; let mut gradient_offset = 0; let mut index_offset = 0; let mut last_is_solid = None; for mesh in meshes { let Some(clip_bounds) = bounds .intersection(&(mesh.clip_bounds() * transformation)) .and_then(Rectangle::snap) else { match mesh { Mesh::Solid { buffers, .. } => { solid_offset += buffers.vertices.len(); num_solids += 1; } Mesh::Gradient { buffers, .. } => { gradient_offset += buffers.vertices.len(); num_gradients += 1; } } continue; }; render_pass.set_scissor_rect( clip_bounds.x, clip_bounds.y, clip_bounds.width, clip_bounds.height, ); match mesh { Mesh::Solid { buffers, .. } => { if !last_is_solid.unwrap_or(false) { render_pass.set_pipeline(&solid.pipeline); last_is_solid = Some(true); } render_pass.set_bind_group( 0, &self.solid.constants, &[(num_solids * std::mem::size_of::<Uniforms>()) as u32], ); render_pass.set_vertex_buffer( 0, self.solid .vertices .range(solid_offset, solid_offset + buffers.vertices.len()), ); num_solids += 1; solid_offset += buffers.vertices.len(); } Mesh::Gradient { buffers, .. } => { if last_is_solid.unwrap_or(true) { render_pass.set_pipeline(&gradient.pipeline); last_is_solid = Some(false); } render_pass.set_bind_group( 0, &self.gradient.constants, &[(num_gradients * std::mem::size_of::<Uniforms>()) as u32], ); render_pass.set_vertex_buffer( 0, self.gradient .vertices .range(gradient_offset, gradient_offset + buffers.vertices.len()), ); num_gradients += 1; gradient_offset += buffers.vertices.len(); } }; render_pass.set_index_buffer( self.index_buffer .range(index_offset, index_offset + mesh.indices().len()), wgpu::IndexFormat::Uint32, ); render_pass.draw_indexed(0..mesh.indices().len() as u32, 0, 0..1); index_offset += mesh.indices().len(); } } } fn fragment_target(texture_format: wgpu::TextureFormat) -> wgpu::ColorTargetState { wgpu::ColorTargetState { format: texture_format, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, } } fn primitive_state() -> wgpu::PrimitiveState { wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..Default::default() } } fn multisample_state(antialiasing: Option<Antialiasing>) -> wgpu::MultisampleState { wgpu::MultisampleState { count: antialiasing.map(Antialiasing::sample_count).unwrap_or(1), mask: !0, alpha_to_coverage_enabled: false, } } #[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct Uniforms { transform: [f32; 16], /// Uniform values must be 256-aligned; /// see: [`wgpu::Limits`] `min_uniform_buffer_offset_alignment`. _padding: [f32; 48], } impl Uniforms { pub fn new(transform: Transformation) -> Self { Self { transform: transform.into(), _padding: [0.0; 48], } } pub fn entry() -> wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<Self>() as u64), }, count: None, } } pub fn min_size() -> Option<wgpu::BufferSize> { wgpu::BufferSize::new(std::mem::size_of::<Self>() as u64) } } mod solid { use crate::Buffer; use crate::graphics::Antialiasing; use crate::graphics::mesh; use crate::triangle; #[derive(Debug, Clone)] pub struct Pipeline { pub pipeline: wgpu::RenderPipeline, pub constants_layout: wgpu::BindGroupLayout, } #[derive(Debug)] pub struct Layer { pub vertices: Buffer<mesh::SolidVertex2D>, pub uniforms: Buffer<triangle::Uniforms>, pub constants: wgpu::BindGroup, } impl Layer { pub fn new(device: &wgpu::Device, constants_layout: &wgpu::BindGroupLayout) -> Self { let vertices = Buffer::new( device, "iced_wgpu.triangle.solid.vertex_buffer", triangle::INITIAL_VERTEX_COUNT, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); let uniforms = Buffer::new( device, "iced_wgpu.triangle.solid.uniforms", 1, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, ); let constants = Self::bind_group(device, &uniforms.raw, constants_layout); Self { vertices, uniforms, constants, } } pub fn bind_group( device: &wgpu::Device, buffer: &wgpu::Buffer, layout: &wgpu::BindGroupLayout, ) -> wgpu::BindGroup { device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu.triangle.solid.bind_group"), layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer, offset: 0, size: triangle::Uniforms::min_size(), }), }], }) } } impl Pipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, antialiasing: Option<Antialiasing>, ) -> Self { let constants_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu.triangle.solid.bind_group_layout"), entries: &[triangle::Uniforms::entry()], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu.triangle.solid.pipeline_layout"), bind_group_layouts: &[&constants_layout], push_constant_ranges: &[], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.triangle.solid.shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( include_str!("shader/triangle.wgsl"), "\n", include_str!("shader/triangle/solid.wgsl"), "\n", include_str!("shader/color.wgsl"), ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu::triangle::solid pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("solid_vs_main"), buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<mesh::SolidVertex2D>() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array!( // Position 0 => Float32x2, // Color 1 => Float32x4, ), }], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("solid_fs_main"), targets: &[Some(triangle::fragment_target(format))], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: triangle::primitive_state(), depth_stencil: None, multisample: triangle::multisample_state(antialiasing), multiview: None, cache: None, }); Self { pipeline, constants_layout, } } } } mod gradient { use crate::Buffer; use crate::graphics::Antialiasing; use crate::graphics::mesh; use crate::triangle; #[derive(Debug, Clone)] pub struct Pipeline { pub pipeline: wgpu::RenderPipeline, pub constants_layout: wgpu::BindGroupLayout, } #[derive(Debug)] pub struct Layer { pub vertices: Buffer<mesh::GradientVertex2D>, pub uniforms: Buffer<triangle::Uniforms>, pub constants: wgpu::BindGroup, } impl Layer { pub fn new(device: &wgpu::Device, constants_layout: &wgpu::BindGroupLayout) -> Self { let vertices = Buffer::new( device, "iced_wgpu.triangle.gradient.vertex_buffer", triangle::INITIAL_VERTEX_COUNT, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); let uniforms = Buffer::new( device, "iced_wgpu.triangle.gradient.uniforms", 1, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, ); let constants = Self::bind_group(device, &uniforms.raw, constants_layout); Self { vertices, uniforms, constants, } } pub fn bind_group( device: &wgpu::Device, uniform_buffer: &wgpu::Buffer, layout: &wgpu::BindGroupLayout, ) -> wgpu::BindGroup { device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu.triangle.gradient.bind_group"), layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: uniform_buffer, offset: 0, size: triangle::Uniforms::min_size(), }), }], }) } } impl Pipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, antialiasing: Option<Antialiasing>, ) -> Self { let constants_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu.triangle.gradient.bind_group_layout"), entries: &[triangle::Uniforms::entry()], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu.triangle.gradient.pipeline_layout"), bind_group_layouts: &[&constants_layout], push_constant_ranges: &[], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.triangle.gradient.shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( include_str!("shader/triangle.wgsl"), "\n", include_str!("shader/triangle/gradient.wgsl"), "\n", include_str!("shader/color.wgsl"), "\n", include_str!("shader/color/linear_rgb.wgsl") ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu.triangle.gradient.pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("gradient_vs_main"), buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<mesh::GradientVertex2D>() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array!( // Position 0 => Float32x2, // Colors 1-2 1 => Uint32x4, // Colors 3-4 2 => Uint32x4, // Colors 5-6 3 => Uint32x4, // Colors 7-8 4 => Uint32x4, // Offsets 5 => Uint32x4, // Direction 6 => Float32x4 ), }], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("gradient_fs_main"), targets: &[Some(triangle::fragment_target(format))], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: triangle::primitive_state(), depth_stencil: None, multisample: triangle::multisample_state(antialiasing), multiview: None, cache: None, }); Self { pipeline, constants_layout, } } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/vector.rs
wgpu/src/image/vector.rs
use crate::core::svg; use crate::core::{Color, Size}; use crate::image::atlas::{self, Atlas}; use resvg::tiny_skia; use resvg::usvg; use rustc_hash::{FxHashMap, FxHashSet}; use std::fs; use std::panic; use std::sync::Arc; /// Entry in cache corresponding to an svg handle pub enum Svg { /// Parsed svg Loaded(usvg::Tree), /// Svg not found or failed to parse NotFound, } impl Svg { /// Viewport width and height pub fn viewport_dimensions(&self) -> Size<u32> { match self { Svg::Loaded(tree) => { let size = tree.size(); Size::new(size.width() as u32, size.height() as u32) } Svg::NotFound => Size::new(1, 1), } } } /// Caches svg vector and raster data #[derive(Debug, Default)] pub struct Cache { svgs: FxHashMap<u64, Svg>, rasterized: FxHashMap<(u64, u32, u32, ColorFilter), atlas::Entry>, svg_hits: FxHashSet<u64>, rasterized_hits: FxHashSet<(u64, u32, u32, ColorFilter)>, should_trim: bool, fontdb: Option<Arc<usvg::fontdb::Database>>, } type ColorFilter = Option<[u8; 4]>; impl Cache { /// Load svg pub fn load(&mut self, handle: &svg::Handle) -> &Svg { if self.svgs.contains_key(&handle.id()) { return self.svgs.get(&handle.id()).unwrap(); } // TODO: Reuse `cosmic-text` font database if self.fontdb.is_none() { let mut fontdb = usvg::fontdb::Database::new(); fontdb.load_system_fonts(); self.fontdb = Some(Arc::new(fontdb)); } let options = usvg::Options { fontdb: self .fontdb .as_ref() .expect("fontdb must be initialized") .clone(), ..usvg::Options::default() }; let svg = match handle.data() { svg::Data::Path(path) => fs::read_to_string(path) .ok() .and_then(|contents| usvg::Tree::from_str(&contents, &options).ok()) .map(Svg::Loaded) .unwrap_or(Svg::NotFound), svg::Data::Bytes(bytes) => match usvg::Tree::from_data(bytes, &options) { Ok(tree) => Svg::Loaded(tree), Err(_) => Svg::NotFound, }, }; self.should_trim = true; let _ = self.svgs.insert(handle.id(), svg); self.svgs.get(&handle.id()).unwrap() } /// Load svg and upload raster data pub fn upload( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, handle: &svg::Handle, color: Option<Color>, size: Size, scale: f32, atlas: &mut Atlas, ) -> Option<&atlas::Entry> { let id = handle.id(); let (width, height) = ( (scale * size.width).ceil() as u32, (scale * size.height).ceil() as u32, ); let color = color.map(Color::into_rgba8); let key = (id, width, height, color); // TODO: Optimize! // We currently rerasterize the SVG when its size changes. This is slow // as heck. A GPU rasterizer like `pathfinder` may perform better. // It would be cool to be able to smooth resize the `svg` example. if self.rasterized.contains_key(&key) { let _ = self.svg_hits.insert(id); let _ = self.rasterized_hits.insert(key); return self.rasterized.get(&key); } match self.load(handle) { Svg::Loaded(tree) => { if width == 0 || height == 0 { return None; } // TODO: Optimize! // We currently rerasterize the SVG when its size changes. This is slow // as heck. A GPU rasterizer like `pathfinder` may perform better. // It would be cool to be able to smooth resize the `svg` example. let mut img = tiny_skia::Pixmap::new(width, height)?; let tree_size = tree.size().to_int_size(); let target_size = if width > height { tree_size.scale_to_width(width) } else { tree_size.scale_to_height(height) }; let transform = if let Some(target_size) = target_size { let tree_size = tree_size.to_size(); let target_size = target_size.to_size(); tiny_skia::Transform::from_scale( target_size.width() / tree_size.width(), target_size.height() / tree_size.height(), ) } else { tiny_skia::Transform::default() }; // SVG rendering can panic on malformed or complex vectors. // We catch panics to prevent crashes and continue gracefully. let render = panic::catch_unwind(panic::AssertUnwindSafe(|| { resvg::render(tree, transform, &mut img.as_mut()); })); if let Err(error) = render { log::warn!("SVG rendering for {handle:?} panicked: {error:?}"); } let mut rgba = img.take(); if let Some(color) = color { rgba.chunks_exact_mut(4).for_each(|rgba| { if rgba[3] > 0 { rgba[0] = color[0]; rgba[1] = color[1]; rgba[2] = color[2]; } }); } let allocation = atlas.upload(device, encoder, belt, width, height, &rgba)?; log::debug!("allocating {id} {width}x{height}"); let _ = self.svg_hits.insert(id); let _ = self.rasterized_hits.insert(key); let _ = self.rasterized.insert(key, allocation); self.should_trim = true; self.rasterized.get(&key) } Svg::NotFound => None, } } /// Load svg and upload raster data pub fn trim(&mut self, atlas: &mut Atlas) { if !self.should_trim { return; } let svg_hits = &self.svg_hits; let rasterized_hits = &self.rasterized_hits; self.svgs.retain(|k, _| svg_hits.contains(k)); self.rasterized.retain(|k, entry| { let retain = rasterized_hits.contains(k); if !retain { atlas.remove(entry); } retain }); self.svg_hits.clear(); self.rasterized_hits.clear(); self.should_trim = false; } } impl std::fmt::Debug for Svg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Svg::Loaded(_) => write!(f, "Svg::Loaded"), Svg::NotFound => write!(f, "Svg::NotFound"), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/atlas.rs
wgpu/src/image/atlas.rs
pub mod entry; mod allocation; mod allocator; mod layer; pub use allocation::Allocation; pub use entry::Entry; pub use layer::Layer; use allocator::Allocator; pub const DEFAULT_SIZE: u32 = 2048; pub const MAX_SIZE: u32 = 2048; use crate::core::Size; use crate::graphics::color; use std::sync::Arc; #[derive(Debug)] pub struct Atlas { size: u32, backend: wgpu::Backend, texture: wgpu::Texture, texture_view: wgpu::TextureView, texture_bind_group: Arc<wgpu::BindGroup>, texture_layout: wgpu::BindGroupLayout, layers: Vec<Layer>, } impl Atlas { pub fn new( device: &wgpu::Device, backend: wgpu::Backend, texture_layout: wgpu::BindGroupLayout, ) -> Self { Self::with_size(device, backend, texture_layout, DEFAULT_SIZE) } pub fn with_size( device: &wgpu::Device, backend: wgpu::Backend, texture_layout: wgpu::BindGroupLayout, size: u32, ) -> Self { let size = size.min(MAX_SIZE); let layers = match backend { // On the GL backend we start with 2 layers, to help wgpu figure // out that this texture is `GL_TEXTURE_2D_ARRAY` rather than `GL_TEXTURE_2D` // https://github.com/gfx-rs/wgpu/blob/004e3efe84a320d9331371ed31fa50baa2414911/wgpu-hal/src/gles/mod.rs#L371 wgpu::Backend::Gl => vec![Layer::Empty, Layer::Empty], _ => vec![Layer::Empty], }; let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: layers.len() as u32, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu::image texture atlas"), size: extent, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: if color::GAMMA_CORRECTION { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }, usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::image texture atlas bind group"), layout: &texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&texture_view), }], }); Atlas { size, backend, texture, texture_view, texture_bind_group: Arc::new(texture_bind_group), texture_layout, layers, } } pub fn bind_group(&self) -> &Arc<wgpu::BindGroup> { &self.texture_bind_group } pub fn upload( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, width: u32, height: u32, pixels: &[u8], ) -> Option<Entry> { let entry = { let current_size = self.layers.len(); let entry = self.allocate(width, height)?; // We grow the internal texture after allocating if necessary let new_layers = self.layers.len() - current_size; self.grow(new_layers, device, encoder, self.backend); entry }; log::debug!("Allocated atlas entry: {entry:?}"); match &entry { Entry::Contiguous(allocation) => { self.upload_allocation(pixels, width, 0, allocation, device, encoder, belt); } Entry::Fragmented { fragments, .. } => { for fragment in fragments { let (x, y) = fragment.position; let offset = 4 * (y * width + x) as usize; self.upload_allocation( pixels, width, offset, &fragment.allocation, device, encoder, belt, ); } } } if log::log_enabled!(log::Level::Debug) { log::debug!( "Atlas layers: {} (busy: {}, allocations: {})", self.layers.len(), self.layers.iter().filter(|layer| !layer.is_empty()).count(), self.layers.iter().map(Layer::allocations).sum::<usize>(), ); } Some(entry) } pub fn remove(&mut self, entry: &Entry) { log::debug!("Removing atlas entry: {entry:?}"); match entry { Entry::Contiguous(allocation) => { self.deallocate(allocation); } Entry::Fragmented { fragments, .. } => { for fragment in fragments { self.deallocate(&fragment.allocation); } } } } fn allocate(&mut self, width: u32, height: u32) -> Option<Entry> { // Allocate one layer if texture fits perfectly if width == self.size && height == self.size { let mut empty_layers = self .layers .iter_mut() .enumerate() .filter(|(_, layer)| layer.is_empty()); if let Some((i, layer)) = empty_layers.next() { *layer = Layer::Full; return Some(Entry::Contiguous(Allocation::Full { layer: i, size: self.size, })); } self.layers.push(Layer::Full); return Some(Entry::Contiguous(Allocation::Full { layer: self.layers.len() - 1, size: self.size, })); } // Split big textures across multiple layers if width > self.size || height > self.size { let mut fragments = Vec::new(); let mut y = 0; while y < height { let height = std::cmp::min(height - y, self.size); let mut x = 0; while x < width { let width = std::cmp::min(width - x, self.size); let allocation = self.allocate(width, height)?; if let Entry::Contiguous(allocation) = allocation { fragments.push(entry::Fragment { position: (x, y), allocation, }); } x += width; } y += height; } return Some(Entry::Fragmented { size: Size::new(width, height), fragments, }); } // Try allocating on an existing layer for (i, layer) in self.layers.iter_mut().enumerate() { match layer { Layer::Empty => { let mut allocator = Allocator::new(self.size); if let Some(region) = allocator.allocate(width, height) { *layer = Layer::Busy(allocator); return Some(Entry::Contiguous(Allocation::Partial { region, layer: i, atlas_size: self.size, })); } } Layer::Busy(allocator) => { if let Some(region) = allocator.allocate(width, height) { return Some(Entry::Contiguous(Allocation::Partial { region, layer: i, atlas_size: self.size, })); } } Layer::Full => {} } } // Create new layer with atlas allocator let mut allocator = Allocator::new(self.size); if let Some(region) = allocator.allocate(width, height) { self.layers.push(Layer::Busy(allocator)); return Some(Entry::Contiguous(Allocation::Partial { region, layer: self.layers.len() - 1, atlas_size: self.size, })); } // We ran out of memory (?) None } fn deallocate(&mut self, allocation: &Allocation) { log::debug!("Deallocating atlas: {allocation:?}"); match allocation { Allocation::Full { layer, .. } => { self.layers[*layer] = Layer::Empty; } Allocation::Partial { layer, region, .. } => { let layer = &mut self.layers[*layer]; if let Layer::Busy(allocator) = layer { allocator.deallocate(region); if allocator.is_empty() { *layer = Layer::Empty; } } } } } fn upload_allocation( &self, pixels: &[u8], image_width: u32, offset: usize, allocation: &Allocation, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, ) { let (x, y) = allocation.position(); let Size { width, height } = allocation.size(); let layer = allocation.layer(); let padding = allocation.padding(); // It is a webgpu requirement that: // BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0 // So we calculate bytes_per_row by rounding width up to the next // multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT. let bytes_per_row = (4 * (width + padding.width * 2)) .next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) as usize; let total_bytes = bytes_per_row * (height + padding.height * 2) as usize; let buffer_slice = belt.allocate( wgpu::BufferSize::new(total_bytes as u64).unwrap(), wgpu::BufferSize::new(8 * 4).unwrap(), device, ); const PIXEL: usize = 4; let mut fragment = buffer_slice.get_mapped_range_mut(); let w = width as usize; let h = height as usize; let pad_w = padding.width as usize; let pad_h = padding.height as usize; let stride = PIXEL * w; // Copy image rows for row in 0..h { let src = offset + row * PIXEL * image_width as usize; let dst = (row + pad_h) * bytes_per_row; fragment[dst + PIXEL * pad_w..dst + PIXEL * pad_w + stride] .copy_from_slice(&pixels[src..src + stride]); // Add padding to the sides, if needed for i in 0..pad_w { fragment[dst + PIXEL * i..dst + PIXEL * (i + 1)] .copy_from_slice(&pixels[src..src + PIXEL]); fragment [dst + stride + PIXEL * (pad_w + i)..dst + stride + PIXEL * (pad_w + i + 1)] .copy_from_slice(&pixels[src + stride - PIXEL..src + stride]); } } // Add padding on top and bottom for row in 0..pad_h { let dst_top = row * bytes_per_row; let dst_bottom = (pad_h + h + row) * bytes_per_row; let src_top = offset; let src_bottom = offset + (h - 1) * PIXEL * image_width as usize; // Top fragment[dst_top + PIXEL * pad_w..dst_top + PIXEL * (pad_w + w)] .copy_from_slice(&pixels[src_top..src_top + PIXEL * w]); // Bottom fragment[dst_bottom + PIXEL * pad_w..dst_bottom + PIXEL * (pad_w + w)] .copy_from_slice(&pixels[src_bottom..src_bottom + PIXEL * w]); // Corners for i in 0..pad_w { // Top left fragment[dst_top + PIXEL * i..dst_top + PIXEL * (i + 1)] .copy_from_slice(&pixels[offset..offset + PIXEL]); // Top right fragment[dst_top + PIXEL * (w + pad_w + i)..dst_top + PIXEL * (w + pad_w + i + 1)] .copy_from_slice(&pixels[offset + PIXEL * (w - 1)..offset + PIXEL * w]); // Bottom left fragment[dst_bottom + PIXEL * i..dst_bottom + PIXEL * (i + 1)] .copy_from_slice(&pixels[src_bottom..src_bottom + PIXEL]); // Bottom right fragment[dst_bottom + PIXEL * (w + pad_w + i) ..dst_bottom + PIXEL * (w + pad_w + i + 1)] .copy_from_slice(&pixels[src_bottom + PIXEL * (w - 1)..src_bottom + PIXEL * w]); } } // Copy actual image encoder.copy_buffer_to_texture( wgpu::TexelCopyBufferInfo { buffer: buffer_slice.buffer(), layout: wgpu::TexelCopyBufferLayout { offset: buffer_slice.offset(), bytes_per_row: Some(bytes_per_row as u32), rows_per_image: Some(height + padding.height * 2), }, }, wgpu::TexelCopyTextureInfo { texture: &self.texture, mip_level: 0, origin: wgpu::Origin3d { x: x - padding.width, y: y - padding.height, z: layer as u32, }, aspect: wgpu::TextureAspect::default(), }, wgpu::Extent3d { width: width + padding.width * 2, height: height + padding.height * 2, depth_or_array_layers: 1, }, ); } fn grow( &mut self, amount: usize, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, backend: wgpu::Backend, ) { if amount == 0 { return; } // On the GL backend if layers.len() is a multiple of 6 we need to help wgpu figure out that this texture // is still a `GL_TEXTURE_2D_ARRAY` rather than `GL_TEXTURE_CUBE_MAP` or `GL_TEXTURE_CUBE_ARRAY`. // This will over-allocate some unused memory on GL, but it's better than not being able to // grow the atlas past multiples of 6! // https://github.com/gfx-rs/wgpu/blob/004e3efe84a320d9331371ed31fa50baa2414911/wgpu-hal/src/gles/mod.rs#L371 let depth_or_array_layers = match backend { wgpu::Backend::Gl if self.layers.len().is_multiple_of(6) => { self.layers.len() as u32 + 1 } _ => self.layers.len() as u32, }; let new_texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu::image texture atlas"), size: wgpu::Extent3d { width: self.size, height: self.size, depth_or_array_layers, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: if color::GAMMA_CORRECTION { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }, usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let amount_to_copy = self.layers.len() - amount; for (i, layer) in self.layers.iter_mut().take(amount_to_copy).enumerate() { if layer.is_empty() { continue; } encoder.copy_texture_to_texture( wgpu::TexelCopyTextureInfo { texture: &self.texture, mip_level: 0, origin: wgpu::Origin3d { x: 0, y: 0, z: i as u32, }, aspect: wgpu::TextureAspect::default(), }, wgpu::TexelCopyTextureInfo { texture: &new_texture, mip_level: 0, origin: wgpu::Origin3d { x: 0, y: 0, z: i as u32, }, aspect: wgpu::TextureAspect::default(), }, wgpu::Extent3d { width: self.size, height: self.size, depth_or_array_layers: 1, }, ); } self.texture = new_texture; self.texture_view = self.texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); self.texture_bind_group = Arc::new(device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::image texture atlas bind group"), layout: &self.texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&self.texture_view), }], })); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/mod.rs
wgpu/src/image/mod.rs
pub(crate) mod cache; pub(crate) use cache::Cache; mod atlas; #[cfg(feature = "image")] mod raster; #[cfg(feature = "svg")] mod vector; use crate::Buffer; use crate::core::border; use crate::core::{Rectangle, Size, Transformation}; use crate::graphics::Shell; use bytemuck::{Pod, Zeroable}; use std::mem; use std::sync::Arc; pub use crate::graphics::Image; pub type Batch = Vec<Image>; #[derive(Debug, Clone)] pub struct Pipeline { raw: wgpu::RenderPipeline, backend: wgpu::Backend, nearest_sampler: wgpu::Sampler, linear_sampler: wgpu::Sampler, texture_layout: wgpu::BindGroupLayout, constant_layout: wgpu::BindGroupLayout, } impl Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, backend: wgpu::Backend) -> Self { let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, min_filter: wgpu::FilterMode::Nearest, mag_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, ..Default::default() }); let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, min_filter: wgpu::FilterMode::Linear, mag_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear, ..Default::default() }); let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu::image constants layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(mem::size_of::<Uniforms>() as u64), }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, ], }); let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu::image texture atlas layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false, }, count: None, }], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu::image pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu image shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( include_str!("../shader/vertex.wgsl"), "\n", include_str!("../shader/image.wgsl"), ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu::image pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[wgpu::VertexBufferLayout { array_stride: mem::size_of::<Instance>() as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &wgpu::vertex_attr_array!( // Center 0 => Float32x2, // Clip bounds 1 => Float32x4, // Border radius 2 => Float32x4, // Tile 3 => Float32x4, // Rotation 4 => Float32, // Opacity 5 => Float32, // Atlas position 6 => Float32x2, // Atlas scale 7 => Float32x2, // Layer 8 => Sint32, // Snap 9 => Uint32, ), }], compilation_options: wgpu::PipelineCompilationOptions::default(), }, 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::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview: None, cache: None, }); Pipeline { raw: pipeline, backend, nearest_sampler, linear_sampler, texture_layout, constant_layout, } } pub fn create_cache(&self, device: &wgpu::Device, queue: &wgpu::Queue, shell: &Shell) -> Cache { Cache::new( device, queue, self.backend, self.texture_layout.clone(), shell, ) } } #[derive(Default)] pub struct State { layers: Vec<Layer>, prepare_layer: usize, nearest_instances: Vec<Instance>, linear_instances: Vec<Instance>, } impl State { pub fn new() -> Self { Self::default() } pub fn prepare( &mut self, pipeline: &Pipeline, device: &wgpu::Device, belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, cache: &mut Cache, images: &Batch, transformation: Transformation, scale: f32, ) { if self.layers.len() <= self.prepare_layer { self.layers.push(Layer::new( device, &pipeline.constant_layout, &pipeline.nearest_sampler, &pipeline.linear_sampler, )); } let layer = &mut self.layers[self.prepare_layer]; let mut atlas: Option<Arc<wgpu::BindGroup>> = None; for image in images { match &image { #[cfg(feature = "image")] Image::Raster { image, bounds, clip_bounds, } => { if let Some((atlas_entry, bind_group)) = cache.upload_raster(device, encoder, belt, &image.handle) { match atlas.as_mut() { None => { atlas = Some(bind_group.clone()); } Some(atlas) if atlas != bind_group => { layer.push(atlas, &self.nearest_instances, &self.linear_instances); *atlas = Arc::clone(bind_group); } _ => {} } add_instances( *bounds, *clip_bounds, image.border_radius, f32::from(image.rotation), image.opacity, image.snap, atlas_entry, match image.filter_method { crate::core::image::FilterMethod::Nearest => { &mut self.nearest_instances } crate::core::image::FilterMethod::Linear => { &mut self.linear_instances } }, ); } } #[cfg(not(feature = "image"))] Image::Raster { .. } => continue, #[cfg(feature = "svg")] Image::Vector { svg, bounds, clip_bounds, } => { if let Some((atlas_entry, bind_group)) = cache.upload_vector( device, encoder, belt, &svg.handle, svg.color, bounds.size(), scale, ) { match atlas.as_mut() { None => { atlas = Some(bind_group.clone()); } Some(atlas) if atlas != bind_group => { layer.push(atlas, &self.nearest_instances, &self.linear_instances); *atlas = bind_group.clone(); } _ => {} } add_instances( *bounds, *clip_bounds, border::radius(0), f32::from(svg.rotation), svg.opacity, true, atlas_entry, &mut self.nearest_instances, ); } } #[cfg(not(feature = "svg"))] Image::Vector { .. } => continue, } } if let Some(atlas) = &atlas { layer.push(atlas, &self.nearest_instances, &self.linear_instances); } layer.prepare( device, encoder, belt, transformation, scale, &self.nearest_instances, &self.linear_instances, ); self.prepare_layer += 1; self.nearest_instances.clear(); self.linear_instances.clear(); } pub fn render<'a>( &'a self, pipeline: &'a Pipeline, layer: usize, bounds: Rectangle<u32>, render_pass: &mut wgpu::RenderPass<'a>, ) { if let Some(layer) = self.layers.get(layer) { render_pass.set_pipeline(&pipeline.raw); render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); layer.render(render_pass); } } pub fn trim(&mut self) { for layer in &mut self.layers[..self.prepare_layer] { layer.clear(); } self.prepare_layer = 0; } } #[derive(Debug)] struct Layer { uniforms: wgpu::Buffer, instances: Buffer<Instance>, nearest: Vec<Group>, nearest_layout: wgpu::BindGroup, nearest_total: usize, linear: Vec<Group>, linear_layout: wgpu::BindGroup, linear_total: usize, } #[derive(Debug)] struct Group { atlas: Arc<wgpu::BindGroup>, instance_count: usize, } impl Layer { fn new( device: &wgpu::Device, constant_layout: &wgpu::BindGroupLayout, nearest_sampler: &wgpu::Sampler, linear_sampler: &wgpu::Sampler, ) -> Self { let uniforms = device.create_buffer(&wgpu::BufferDescriptor { label: Some("iced_wgpu::image uniforms buffer"), size: mem::size_of::<Uniforms>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let instances = Buffer::new( device, "iced_wgpu::image instance buffer", Instance::INITIAL, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); let nearest_layout = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::image constants bind group"), layout: constant_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniforms, offset: 0, size: None, }), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(nearest_sampler), }, ], }); let linear_layout = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::image constants bind group"), layout: constant_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniforms, offset: 0, size: None, }), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(linear_sampler), }, ], }); Self { uniforms, instances, nearest: Vec::new(), nearest_layout, nearest_total: 0, linear: Vec::new(), linear_layout, linear_total: 0, } } fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, transformation: Transformation, scale_factor: f32, nearest: &[Instance], linear: &[Instance], ) { let uniforms = Uniforms { transform: transformation.into(), scale_factor, _padding: [0.0; 3], }; let bytes = bytemuck::bytes_of(&uniforms); belt.write_buffer( encoder, &self.uniforms, 0, (bytes.len() as u64).try_into().expect("Sized uniforms"), device, ) .copy_from_slice(bytes); let _ = self .instances .resize(device, self.nearest_total + self.linear_total); let mut offset = 0; if !nearest.is_empty() { offset += self.instances.write(device, encoder, belt, 0, nearest); } if !linear.is_empty() { let _ = self.instances.write(device, encoder, belt, offset, linear); } } fn push(&mut self, atlas: &Arc<wgpu::BindGroup>, nearest: &[Instance], linear: &[Instance]) { let new_nearest = nearest.len() - self.nearest_total; if new_nearest > 0 { self.nearest.push(Group { atlas: atlas.clone(), instance_count: new_nearest, }); self.nearest_total = nearest.len(); } let new_linear = linear.len() - self.linear_total; if new_linear > 0 { self.linear.push(Group { atlas: atlas.clone(), instance_count: new_linear, }); self.linear_total = linear.len(); } } fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { render_pass.set_vertex_buffer(0, self.instances.slice(..)); let mut offset = 0; if !self.nearest.is_empty() { render_pass.set_bind_group(0, &self.nearest_layout, &[]); for group in &self.nearest { render_pass.set_bind_group(1, group.atlas.as_ref(), &[]); render_pass.draw(0..6, offset..offset + group.instance_count as u32); offset += group.instance_count as u32; } } if !self.linear.is_empty() { render_pass.set_bind_group(0, &self.linear_layout, &[]); for group in &self.linear { render_pass.set_bind_group(1, group.atlas.as_ref(), &[]); render_pass.draw(0..6, offset..offset + group.instance_count as u32); offset += group.instance_count as u32; } } } fn clear(&mut self) { self.nearest.clear(); self.nearest_total = 0; self.linear.clear(); self.linear_total = 0; } } #[repr(C)] #[derive(Debug, Clone, Copy, Zeroable, Pod)] struct Instance { _center: [f32; 2], _clip_bounds: [f32; 4], _border_radius: [f32; 4], _tile: [f32; 4], _rotation: f32, _opacity: f32, _position_in_atlas: [f32; 2], _size_in_atlas: [f32; 2], _layer: u32, _snap: u32, } impl Instance { pub const INITIAL: usize = 20; } #[repr(C)] #[derive(Debug, Clone, Copy, Zeroable, Pod)] struct Uniforms { transform: [f32; 16], scale_factor: f32, // Uniforms must be aligned to their largest member, // this uses a mat4x4<f32> which aligns to 16, so align to that _padding: [f32; 3], } fn add_instances( bounds: Rectangle, clip_bounds: Rectangle, border_radius: border::Radius, rotation: f32, opacity: f32, snap: bool, entry: &atlas::Entry, instances: &mut Vec<Instance>, ) { let center = [ bounds.x + bounds.width / 2.0, bounds.y + bounds.height / 2.0, ]; let clip_bounds = [ clip_bounds.x, clip_bounds.y, clip_bounds.width, clip_bounds.height, ]; let border_radius = border_radius.into(); match entry { atlas::Entry::Contiguous(allocation) => { add_instance( center, clip_bounds, border_radius, [bounds.x, bounds.y, bounds.width, bounds.height], rotation, opacity, snap, allocation, instances, ); } atlas::Entry::Fragmented { fragments, size } => { let scaling_x = bounds.width / size.width as f32; let scaling_y = bounds.height / size.height as f32; for fragment in fragments { let allocation = &fragment.allocation; let (fragment_x, fragment_y) = fragment.position; let Size { width: fragment_width, height: fragment_height, } = allocation.size(); let tile = [ bounds.x + fragment_x as f32 * scaling_x, bounds.y + fragment_y as f32 * scaling_y, fragment_width as f32 * scaling_x, fragment_height as f32 * scaling_y, ]; add_instance( center, clip_bounds, border_radius, tile, rotation, opacity, snap, allocation, instances, ); } } } } #[inline] fn add_instance( center: [f32; 2], clip_bounds: [f32; 4], border_radius: [f32; 4], tile: [f32; 4], rotation: f32, opacity: f32, snap: bool, allocation: &atlas::Allocation, instances: &mut Vec<Instance>, ) { let (x, y) = allocation.position(); let Size { width, height } = allocation.size(); let layer = allocation.layer(); let atlas_size = allocation.atlas_size(); let instance = Instance { _center: center, _clip_bounds: clip_bounds, _border_radius: border_radius, _tile: tile, _rotation: rotation, _opacity: opacity, _position_in_atlas: [x as f32 / atlas_size as f32, y as f32 / atlas_size as f32], _size_in_atlas: [ width as f32 / atlas_size as f32, height as f32 / atlas_size as f32, ], _layer: layer as u32, _snap: snap as u32, }; instances.push(instance); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/null.rs
wgpu/src/image/null.rs
pub use crate::graphics::Image; #[derive(Debug, Default)] pub struct Batch; impl Batch { pub fn push(&mut self, _image: Image) {} pub fn clear(&mut self) {} pub fn is_empty(&self) -> bool { true } pub fn append(&mut self, _batch: &mut Self) {} }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/cache.rs
wgpu/src/image/cache.rs
use crate::core::{self, Size}; use crate::graphics::Shell; use crate::image::atlas::{self, Atlas}; #[cfg(all(feature = "image", not(target_arch = "wasm32")))] use worker::Worker; #[cfg(feature = "image")] use std::collections::HashMap; use std::sync::Arc; pub struct Cache { atlas: Atlas, #[cfg(feature = "image")] raster: Raster, #[cfg(feature = "svg")] vector: crate::image::vector::Cache, #[cfg(all(feature = "image", not(target_arch = "wasm32")))] worker: Worker, } impl Cache { pub fn new( device: &wgpu::Device, _queue: &wgpu::Queue, backend: wgpu::Backend, layout: wgpu::BindGroupLayout, _shell: &Shell, ) -> Self { #[cfg(all(feature = "image", not(target_arch = "wasm32")))] let worker = Worker::new(device, _queue, backend, layout.clone(), _shell); Self { atlas: Atlas::new(device, backend, layout), #[cfg(feature = "image")] raster: Raster { cache: crate::image::raster::Cache::default(), pending: HashMap::new(), belt: wgpu::util::StagingBelt::new(2 * 1024 * 1024), }, #[cfg(feature = "svg")] vector: crate::image::vector::Cache::default(), #[cfg(all(feature = "image", not(target_arch = "wasm32")))] worker, } } #[cfg(feature = "image")] pub fn allocate_image( &mut self, handle: &core::image::Handle, callback: impl FnOnce(Result<core::image::Allocation, core::image::Error>) + Send + 'static, ) { use crate::image::raster::Memory; let callback = Box::new(callback); if let Some(callbacks) = self.raster.pending.get_mut(&handle.id()) { callbacks.push(callback); return; } if let Some(Memory::Device { allocation, entry, .. }) = self.raster.cache.get_mut(handle) { if let Some(allocation) = allocation .as_ref() .and_then(core::image::Allocation::upgrade) { callback(Ok(allocation)); return; } #[allow(unsafe_code)] let new = unsafe { core::image::allocate(handle, entry.size()) }; *allocation = Some(new.downgrade()); callback(Ok(new)); return; } let _ = self.raster.pending.insert(handle.id(), vec![callback]); #[cfg(not(target_arch = "wasm32"))] self.worker.load(handle, true); } #[cfg(feature = "image")] pub fn load_image( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, handle: &core::image::Handle, ) -> Result<core::image::Allocation, core::image::Error> { use crate::image::raster::Memory; if !self.raster.cache.contains(handle) { self.raster.cache.insert(handle, Memory::load(handle)); } match self.raster.cache.get_mut(handle).unwrap() { Memory::Host(image) => { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("raster image upload"), }); let entry = self.atlas.upload( device, &mut encoder, &mut self.raster.belt, image.width(), image.height(), image, ); self.raster.belt.finish(); let submission = queue.submit([encoder.finish()]); self.raster.belt.recall(); let Some(entry) = entry else { return Err(core::image::Error::OutOfMemory); }; let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None, }); #[allow(unsafe_code)] let allocation = unsafe { core::image::allocate(handle, Size::new(image.width(), image.height())) }; self.raster.cache.insert( handle, Memory::Device { entry, bind_group: None, allocation: Some(allocation.downgrade()), }, ); Ok(allocation) } Memory::Device { entry, allocation, .. } => { if let Some(allocation) = allocation .as_ref() .and_then(core::image::Allocation::upgrade) { return Ok(allocation); } #[allow(unsafe_code)] let new = unsafe { core::image::allocate(handle, entry.size()) }; *allocation = Some(new.downgrade()); Ok(new) } Memory::Error(error) => Err(error.clone()), } } #[cfg(feature = "image")] pub fn measure_image(&mut self, handle: &core::image::Handle) -> Option<Size<u32>> { self.receive(); let image = load_image( &mut self.raster.cache, &mut self.raster.pending, #[cfg(not(target_arch = "wasm32"))] &self.worker, handle, None, )?; Some(image.dimensions()) } #[cfg(feature = "svg")] pub fn measure_svg(&mut self, handle: &core::svg::Handle) -> Size<u32> { // TODO: Concurrency self.vector.load(handle).viewport_dimensions() } #[cfg(feature = "image")] pub fn upload_raster( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, handle: &core::image::Handle, ) -> Option<(&atlas::Entry, &Arc<wgpu::BindGroup>)> { use crate::image::raster::Memory; self.receive(); let memory = load_image( &mut self.raster.cache, &mut self.raster.pending, #[cfg(not(target_arch = "wasm32"))] &self.worker, handle, None, )?; if let Memory::Device { entry, bind_group, .. } = memory { return Some(( entry, bind_group.as_ref().unwrap_or(self.atlas.bind_group()), )); } let image = memory.host()?; const MAX_SYNC_SIZE: usize = 2 * 1024 * 1024; // TODO: Concurrent Wasm support if image.len() < MAX_SYNC_SIZE || cfg!(target_arch = "wasm32") { let entry = self.atlas .upload(device, encoder, belt, image.width(), image.height(), &image)?; *memory = Memory::Device { entry, bind_group: None, allocation: None, }; if let Memory::Device { entry, .. } = memory { return Some((entry, self.atlas.bind_group())); } } if !self.raster.pending.contains_key(&handle.id()) { let _ = self.raster.pending.insert(handle.id(), Vec::new()); #[cfg(not(target_arch = "wasm32"))] self.worker.upload(handle, image); } None } #[cfg(feature = "svg")] pub fn upload_vector( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, handle: &core::svg::Handle, color: Option<core::Color>, size: Size, scale: f32, ) -> Option<(&atlas::Entry, &Arc<wgpu::BindGroup>)> { // TODO: Concurrency self.vector .upload( device, encoder, belt, handle, color, size, scale, &mut self.atlas, ) .map(|entry| (entry, self.atlas.bind_group())) } pub fn trim(&mut self) { #[cfg(feature = "image")] { self.receive(); self.raster.cache.trim(&mut self.atlas, |_bind_group| { #[cfg(not(target_arch = "wasm32"))] self.worker.drop(_bind_group); }); } #[cfg(feature = "svg")] self.vector.trim(&mut self.atlas); // TODO: Concurrency } #[cfg(feature = "image")] pub fn receive(&mut self) { #[cfg(not(target_arch = "wasm32"))] while let Ok(work) = self.worker.try_recv() { use crate::image::raster::Memory; match work { worker::Work::Upload { handle, entry, bind_group, } => { let callbacks = self.raster.pending.remove(&handle.id()); let allocation = if let Some(callbacks) = callbacks { #[allow(unsafe_code)] let allocation = unsafe { core::image::allocate(&handle, entry.size()) }; let reference = allocation.downgrade(); for callback in callbacks { callback(Ok(allocation.clone())); } Some(reference) } else { None }; self.raster.cache.insert( &handle, Memory::Device { entry, bind_group: Some(bind_group), allocation, }, ); } worker::Work::Error { handle, error } => { let callbacks = self.raster.pending.remove(&handle.id()); if let Some(callbacks) = callbacks { for callback in callbacks { callback(Err(error.clone())); } } self.raster.cache.insert(&handle, Memory::Error(error)); } } } } } #[cfg(all(feature = "image", not(target_arch = "wasm32")))] impl Drop for Cache { fn drop(&mut self) { self.worker.quit(); } } #[cfg(feature = "image")] struct Raster { cache: crate::image::raster::Cache, pending: HashMap<core::image::Id, Vec<Callback>>, belt: wgpu::util::StagingBelt, } #[cfg(feature = "image")] type Callback = Box<dyn FnOnce(Result<core::image::Allocation, core::image::Error>) + Send>; #[cfg(feature = "image")] fn load_image<'a>( cache: &'a mut crate::image::raster::Cache, pending: &mut HashMap<core::image::Id, Vec<Callback>>, #[cfg(not(target_arch = "wasm32"))] worker: &Worker, handle: &core::image::Handle, callback: Option<Callback>, ) -> Option<&'a mut crate::image::raster::Memory> { use crate::image::raster::Memory; if !cache.contains(handle) { if cfg!(target_arch = "wasm32") { // TODO: Concurrent support for Wasm cache.insert(handle, Memory::load(handle)); } else if let core::image::Handle::Rgba { .. } = handle { // Load RGBA handles synchronously, since it's very cheap cache.insert(handle, Memory::load(handle)); } else if !pending.contains_key(&handle.id()) { let _ = pending.insert(handle.id(), Vec::from_iter(callback)); #[cfg(not(target_arch = "wasm32"))] worker.load(handle, false); } } cache.get_mut(handle) } #[cfg(all(feature = "image", not(target_arch = "wasm32")))] mod worker { use crate::core::Bytes; use crate::core::image; use crate::graphics::Shell; use crate::image::atlas::{self, Atlas}; use crate::image::raster; use std::sync::Arc; use std::sync::mpsc; use std::thread; pub struct Worker { jobs: mpsc::SyncSender<Job>, quit: mpsc::SyncSender<()>, work: mpsc::Receiver<Work>, handle: Option<std::thread::JoinHandle<()>>, } impl Worker { pub fn new( device: &wgpu::Device, queue: &wgpu::Queue, backend: wgpu::Backend, texture_layout: wgpu::BindGroupLayout, shell: &Shell, ) -> Self { let (jobs_sender, jobs_receiver) = mpsc::sync_channel(1_000); let (quit_sender, quit_receiver) = mpsc::sync_channel(1); let (work_sender, work_receiver) = mpsc::sync_channel(1_000); let instance = Instance { device: device.clone(), queue: queue.clone(), backend, texture_layout, shell: shell.clone(), belt: wgpu::util::StagingBelt::new(4 * 1024 * 1024), jobs: jobs_receiver, output: work_sender, quit: quit_receiver, }; let handle = thread::spawn(move || instance.run()); Self { jobs: jobs_sender, quit: quit_sender, work: work_receiver, handle: Some(handle), } } pub fn load(&self, handle: &image::Handle, is_allocation: bool) { let _ = self.jobs.send(Job::Load { handle: handle.clone(), is_allocation, }); } pub fn upload(&self, handle: &image::Handle, image: raster::Image) { let _ = self.jobs.send(Job::Upload { handle: handle.clone(), width: image.width(), height: image.height(), rgba: image.into_raw(), }); } pub fn drop(&self, bind_group: Arc<wgpu::BindGroup>) { let _ = self.jobs.send(Job::Drop(bind_group)); } pub fn try_recv(&self) -> Result<Work, mpsc::TryRecvError> { self.work.try_recv() } pub fn quit(&mut self) { let _ = self.quit.try_send(()); let _ = self.jobs.send(Job::Quit); let _ = self.handle.take().map(thread::JoinHandle::join); } } pub struct Instance { device: wgpu::Device, queue: wgpu::Queue, backend: wgpu::Backend, texture_layout: wgpu::BindGroupLayout, shell: Shell, belt: wgpu::util::StagingBelt, jobs: mpsc::Receiver<Job>, output: mpsc::SyncSender<Work>, quit: mpsc::Receiver<()>, } #[derive(Debug)] enum Job { Load { handle: image::Handle, is_allocation: bool, }, Upload { handle: image::Handle, rgba: Bytes, width: u32, height: u32, }, Drop(Arc<wgpu::BindGroup>), Quit, } pub enum Work { Upload { handle: image::Handle, entry: atlas::Entry, bind_group: Arc<wgpu::BindGroup>, }, Error { handle: image::Handle, error: image::Error, }, } impl Instance { fn run(mut self) { loop { if self.quit.try_recv().is_ok() { return; } let Ok(job) = self.jobs.recv() else { return; }; match job { Job::Load { handle, is_allocation, } => match crate::graphics::image::load(&handle) { Ok(image) => self.upload( handle, image.width(), image.height(), image.into_raw(), if is_allocation { Shell::tick } else { Shell::invalidate_layout }, ), Err(error) => { let _ = self.output.send(Work::Error { handle, error }); } }, Job::Upload { handle, rgba, width, height, } => { self.upload(handle, width, height, rgba, Shell::request_redraw); } Job::Drop(bind_group) => { drop(bind_group); } Job::Quit => return, } } } fn upload( &mut self, handle: image::Handle, width: u32, height: u32, rgba: Bytes, callback: fn(&Shell), ) { let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("raster image upload"), }); let mut atlas = Atlas::with_size( &self.device, self.backend, self.texture_layout.clone(), width.max(height), ); let Some(entry) = atlas.upload( &self.device, &mut encoder, &mut self.belt, width, height, &rgba, ) else { return; }; let output = self.output.clone(); let shell = self.shell.clone(); self.belt.finish(); let submission = self.queue.submit([encoder.finish()]); self.belt.recall(); let bind_group = atlas.bind_group().clone(); self.queue.on_submitted_work_done(move || { let _ = output.send(Work::Upload { handle, entry, bind_group, }); callback(&shell); }); let _ = self.device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None, }); } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/raster.rs
wgpu/src/image/raster.rs
use crate::core::Size; use crate::core::image; use crate::graphics; use crate::image::atlas::{self, Atlas}; use rustc_hash::{FxHashMap, FxHashSet}; use std::sync::{Arc, Weak}; pub type Image = graphics::image::Buffer; /// Entry in cache corresponding to an image handle #[derive(Debug)] pub enum Memory { /// Image data on host Host(Image), /// Storage entry Device { entry: atlas::Entry, bind_group: Option<Arc<wgpu::BindGroup>>, allocation: Option<Weak<image::Memory>>, }, Error(image::Error), } impl Memory { pub fn load(handle: &image::Handle) -> Self { match graphics::image::load(handle) { Ok(image) => Self::Host(image), Err(error) => Self::Error(error), } } pub fn dimensions(&self) -> Size<u32> { match self { Memory::Host(image) => { let (width, height) = image.dimensions(); Size::new(width, height) } Memory::Device { entry, .. } => entry.size(), Memory::Error(_) => Size::new(1, 1), } } pub fn host(&self) -> Option<Image> { match self { Memory::Host(image) => Some(image.clone()), Memory::Device { .. } | Memory::Error(_) => None, } } } #[derive(Debug, Default)] pub struct Cache { map: FxHashMap<image::Id, Memory>, hits: FxHashSet<image::Id>, should_trim: bool, } impl Cache { pub fn get_mut(&mut self, handle: &image::Handle) -> Option<&mut Memory> { let _ = self.hits.insert(handle.id()); self.map.get_mut(&handle.id()) } pub fn insert(&mut self, handle: &image::Handle, memory: Memory) { let _ = self.map.insert(handle.id(), memory); let _ = self.hits.insert(handle.id()); self.should_trim = true; } pub fn contains(&self, handle: &image::Handle) -> bool { self.map.contains_key(&handle.id()) } pub fn trim(&mut self, atlas: &mut Atlas, on_drop: impl Fn(Arc<wgpu::BindGroup>)) { // Only trim if new entries have landed in the `Cache` if !self.should_trim { return; } let hits = &self.hits; self.map.retain(|id, memory| { // Retain active allocations if let Memory::Device { allocation, .. } = memory && allocation .as_ref() .is_some_and(|allocation| allocation.strong_count() > 0) { return true; } let retain = hits.contains(id); if !retain { log::debug!("Dropping image allocation: {id:?}"); if let Memory::Device { entry, bind_group, .. } = memory { if let Some(bind_group) = bind_group.take() { on_drop(bind_group); } else { atlas.remove(entry); } } } retain }); self.hits.clear(); self.should_trim = false; } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/atlas/allocation.rs
wgpu/src/image/atlas/allocation.rs
use crate::core::Size; use crate::image::atlas::allocator; #[derive(Debug)] pub enum Allocation { Partial { layer: usize, region: allocator::Region, atlas_size: u32, }, Full { layer: usize, size: u32, }, } impl Allocation { pub fn position(&self) -> (u32, u32) { match self { Allocation::Partial { region, .. } => region.position(), Allocation::Full { .. } => (0, 0), } } pub fn size(&self) -> Size<u32> { match self { Allocation::Partial { region, .. } => region.size(), Allocation::Full { size, .. } => Size::new(*size, *size), } } pub fn padding(&self) -> Size<u32> { match self { Allocation::Partial { region, .. } => region.padding(), Allocation::Full { .. } => Size::new(0, 0), } } pub fn layer(&self) -> usize { match self { Allocation::Partial { layer, .. } => *layer, Allocation::Full { layer, .. } => *layer, } } pub fn atlas_size(&self) -> u32 { match self { Allocation::Partial { atlas_size, .. } => *atlas_size, Allocation::Full { size, .. } => *size, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/atlas/layer.rs
wgpu/src/image/atlas/layer.rs
use crate::image::atlas::Allocator; #[derive(Debug)] pub enum Layer { Empty, Busy(Allocator), Full, } impl Layer { pub fn is_empty(&self) -> bool { matches!(self, Layer::Empty) } pub fn allocations(&self) -> usize { match self { Layer::Empty => 0, Layer::Busy(allocator) => allocator.allocations(), Layer::Full => 1, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/atlas/allocator.rs
wgpu/src/image/atlas/allocator.rs
use crate::core; use guillotiere::{AtlasAllocator, Size}; pub struct Allocator { raw: AtlasAllocator, allocations: usize, } impl Allocator { const PADDING: u32 = 1; pub fn new(size: u32) -> Allocator { let raw = AtlasAllocator::new(Size::new(size as i32, size as i32)); Allocator { raw, allocations: 0, } } pub fn allocate(&mut self, width: u32, height: u32) -> Option<Region> { let size = self.raw.size(); let padded_width = width + Self::PADDING * 2; let padded_height = height + Self::PADDING * 2; let pad_width = padded_width as i32 <= size.width; let pad_height = padded_height as i32 <= size.height; let mut allocation = self.raw.allocate(Size::new( if pad_width { padded_width } else { width } as i32, if pad_height { padded_height } else { height } as i32, ))?; if pad_width { allocation.rectangle.min.x += Self::PADDING as i32; allocation.rectangle.max.x -= Self::PADDING as i32; } if pad_height { allocation.rectangle.min.y += Self::PADDING as i32; allocation.rectangle.max.y -= Self::PADDING as i32; } self.allocations += 1; Some(Region { allocation, padding: core::Size::new( if pad_width { Self::PADDING } else { 0 }, if pad_height { Self::PADDING } else { 0 }, ), }) } pub fn deallocate(&mut self, region: &Region) { self.raw.deallocate(region.allocation.id); self.allocations = self.allocations.saturating_sub(1); } pub fn is_empty(&self) -> bool { self.allocations == 0 } pub fn allocations(&self) -> usize { self.allocations } } pub struct Region { allocation: guillotiere::Allocation, padding: core::Size<u32>, } impl Region { pub fn position(&self) -> (u32, u32) { let rectangle = &self.allocation.rectangle; (rectangle.min.x as u32, rectangle.min.y as u32) } pub fn size(&self) -> core::Size<u32> { let size = self.allocation.rectangle.size(); core::Size::new(size.width as u32, size.height as u32) } pub fn padding(&self) -> crate::core::Size<u32> { self.padding } } impl std::fmt::Debug for Allocator { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Allocator") } } impl std::fmt::Debug for Region { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Region") .field("id", &self.allocation.id) .field("rectangle", &self.allocation.rectangle) .finish() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/image/atlas/entry.rs
wgpu/src/image/atlas/entry.rs
use crate::core::Size; use crate::image::atlas; #[derive(Debug)] pub enum Entry { Contiguous(atlas::Allocation), Fragmented { size: Size<u32>, fragments: Vec<Fragment>, }, } impl Entry { #[cfg(feature = "image")] pub fn size(&self) -> Size<u32> { match self { Entry::Contiguous(allocation) => allocation.size(), Entry::Fragmented { size, .. } => *size, } } } #[derive(Debug)] pub struct Fragment { pub position: (u32, u32), pub allocation: atlas::Allocation, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/window/compositor.rs
wgpu/src/window/compositor.rs
//! Connect a window with a renderer. use crate::core::Color; use crate::graphics::color; use crate::graphics::compositor; use crate::graphics::error; use crate::graphics::{self, Shell, Viewport}; use crate::settings::{self, Settings}; use crate::{Engine, Renderer}; /// A window graphics backend for iced powered by `wgpu`. pub struct Compositor { instance: wgpu::Instance, adapter: wgpu::Adapter, format: wgpu::TextureFormat, alpha_mode: wgpu::CompositeAlphaMode, engine: Engine, settings: Settings, } /// A compositor error. #[derive(Debug, Clone, thiserror::Error)] pub enum Error { /// The surface creation failed. #[error("the surface creation failed: {0}")] SurfaceCreationFailed(#[from] wgpu::CreateSurfaceError), /// The surface is not compatible. #[error("the surface is not compatible")] IncompatibleSurface, /// No adapter was found for the options requested. #[error("no adapter was found for the options requested: {0:?}")] NoAdapterFound(String), /// No device request succeeded. #[error("no device request succeeded: {0:?}")] RequestDeviceFailed(Vec<(wgpu::Limits, wgpu::RequestDeviceError)>), } impl From<Error> for graphics::Error { fn from(error: Error) -> Self { Self::GraphicsAdapterNotFound { backend: "wgpu", reason: error::Reason::RequestFailed(error.to_string()), } } } impl Compositor { /// Requests a new [`Compositor`] with the given [`Settings`]. /// /// Returns `None` if no compatible graphics adapter could be found. pub async fn request<W: compositor::Window>( settings: Settings, compatible_window: Option<W>, shell: Shell, ) -> Result<Self, Error> { let instance = wgpu::util::new_instance_with_webgpu_detection(&wgpu::InstanceDescriptor { backends: settings.backends, flags: if cfg!(feature = "strict-assertions") { wgpu::InstanceFlags::debugging() } else { wgpu::InstanceFlags::empty() }, ..Default::default() }) .await; log::info!("{settings:#?}"); #[cfg(not(target_arch = "wasm32"))] if log::max_level() >= log::LevelFilter::Info { let available_adapters: Vec<_> = instance .enumerate_adapters(settings.backends) .iter() .map(wgpu::Adapter::get_info) .collect(); log::info!("Available adapters: {available_adapters:#?}"); } #[allow(unsafe_code)] let compatible_surface = compatible_window.and_then(|window| instance.create_surface(window).ok()); let adapter_options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::from_env() .unwrap_or(wgpu::PowerPreference::HighPerformance), compatible_surface: compatible_surface.as_ref(), force_fallback_adapter: false, }; let adapter = instance .request_adapter(&adapter_options) .await .map_err(|_error| Error::NoAdapterFound(format!("{adapter_options:?}")))?; log::info!("Selected: {:#?}", adapter.get_info()); let (format, alpha_mode) = compatible_surface .as_ref() .and_then(|surface| { let capabilities = surface.get_capabilities(&adapter); let formats = capabilities.formats.iter().copied(); log::info!("Available formats: {formats:#?}"); let mut formats = formats.filter(|format| format.required_features() == wgpu::Features::empty()); let format = if color::GAMMA_CORRECTION { formats.find(wgpu::TextureFormat::is_srgb) } else { formats.find(|format| !wgpu::TextureFormat::is_srgb(format)) }; let format = format.or_else(|| { log::warn!("No format found!"); capabilities.formats.first().copied() }); let alpha_modes = capabilities.alpha_modes; log::info!("Available alpha modes: {alpha_modes:#?}"); let preferred_alpha = if alpha_modes.contains(&wgpu::CompositeAlphaMode::PostMultiplied) { wgpu::CompositeAlphaMode::PostMultiplied } else if alpha_modes.contains(&wgpu::CompositeAlphaMode::PreMultiplied) { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto }; format.zip(Some(preferred_alpha)) }) .ok_or(Error::IncompatibleSurface)?; log::info!("Selected format: {format:?} with alpha mode: {alpha_mode:?}"); #[cfg(target_arch = "wasm32")] let limits = [wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits())]; #[cfg(not(target_arch = "wasm32"))] let limits = [wgpu::Limits::default(), wgpu::Limits::downlevel_defaults()]; let limits = limits.into_iter().map(|limits| wgpu::Limits { max_bind_groups: 2, max_non_sampler_bindings: 2048, ..limits }); let mut errors = Vec::new(); for required_limits in limits { let result = adapter .request_device(&wgpu::DeviceDescriptor { label: Some("iced_wgpu::window::compositor device descriptor"), required_features: wgpu::Features::SHADER_F16, required_limits: required_limits.clone(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, experimental_features: wgpu::ExperimentalFeatures::disabled(), }) .await; match result { Ok((device, queue)) => { let engine = Engine::new( &adapter, device, queue, format, settings.antialiasing, shell, ); return Ok(Compositor { instance, adapter, format, alpha_mode, engine, settings, }); } Err(error) => { errors.push((required_limits, error)); } } } Err(Error::RequestDeviceFailed(errors)) } } /// Creates a [`Compositor`] with the given [`Settings`] and window. pub async fn new<W: compositor::Window>( settings: Settings, compatible_window: W, shell: Shell, ) -> Result<Compositor, Error> { Compositor::request(settings, Some(compatible_window), shell).await } /// Presents the given primitives with the given [`Compositor`]. pub fn present( renderer: &mut Renderer, surface: &mut wgpu::Surface<'static>, viewport: &Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { match surface.get_current_texture() { Ok(frame) => { let view = &frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let _submission = renderer.present( Some(background_color), frame.texture.format(), view, viewport, ); // Present the frame on_pre_present(); frame.present(); Ok(()) } Err(error) => match error { wgpu::SurfaceError::Timeout => Err(compositor::SurfaceError::Timeout), wgpu::SurfaceError::Outdated => Err(compositor::SurfaceError::Outdated), wgpu::SurfaceError::Lost => Err(compositor::SurfaceError::Lost), wgpu::SurfaceError::OutOfMemory => Err(compositor::SurfaceError::OutOfMemory), wgpu::SurfaceError::Other => Err(compositor::SurfaceError::Other), }, } } impl graphics::Compositor for Compositor { type Renderer = Renderer; type Surface = wgpu::Surface<'static>; async fn with_backend( settings: graphics::Settings, _display: impl compositor::Display, compatible_window: impl compositor::Window, shell: Shell, backend: Option<&str>, ) -> Result<Self, graphics::Error> { match backend { None | Some("wgpu") => { let mut settings = Settings::from(settings); if let Some(backends) = wgpu::Backends::from_env() { settings.backends = backends; } if let Some(present_mode) = settings::present_mode_from_env() { settings.present_mode = present_mode; } Ok(new(settings, compatible_window, shell).await?) } Some(backend) => Err(graphics::Error::GraphicsAdapterNotFound { backend: "wgpu", reason: error::Reason::DidNotMatch { preferred_backend: backend.to_owned(), }, }), } } fn create_renderer(&self) -> Self::Renderer { Renderer::new( self.engine.clone(), self.settings.default_font, self.settings.default_text_size, ) } fn create_surface<W: compositor::Window>( &mut self, window: W, width: u32, height: u32, ) -> Self::Surface { let mut surface = self .instance .create_surface(window) .expect("Create surface"); if width > 0 && height > 0 { self.configure_surface(&mut surface, width, height); } surface } fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { surface.configure( &self.engine.device, &wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: self.format, present_mode: self.settings.present_mode, width, height, alpha_mode: self.alpha_mode, view_formats: vec![], desired_maximum_frame_latency: 1, }, ); } fn information(&self) -> compositor::Information { let information = self.adapter.get_info(); compositor::Information { adapter: information.name, backend: format!("{:?}", information.backend), } } fn present( &mut self, renderer: &mut Self::Renderer, surface: &mut Self::Surface, viewport: &Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { present( renderer, surface, viewport, background_color, on_pre_present, ) } fn screenshot( &mut self, renderer: &mut Self::Renderer, viewport: &Viewport, background_color: Color, ) -> Vec<u8> { renderer.screenshot(viewport, background_color) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/quad/solid.rs
wgpu/src/quad/solid.rs
use crate::Buffer; use crate::graphics::color; use crate::quad::{self, Quad}; use bytemuck::{Pod, Zeroable}; use std::ops::Range; /// A quad filled with a solid color. #[derive(Clone, Copy, Debug, Pod, Zeroable)] #[repr(C)] pub struct Solid { /// The background color data of the quad. pub color: color::Packed, /// The [`Quad`] data of the [`Solid`]. pub quad: Quad, } #[derive(Debug)] pub struct Layer { instances: Buffer<Solid>, instance_count: usize, } impl Layer { pub fn new(device: &wgpu::Device) -> Self { let instances = Buffer::new( device, "iced_wgpu.quad.solid.buffer", quad::INITIAL_INSTANCES, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); Self { instances, instance_count: 0, } } pub fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, instances: &[Solid], ) { let _ = self.instances.resize(device, instances.len()); let _ = self.instances.write(device, encoder, belt, 0, instances); self.instance_count = instances.len(); } } #[derive(Debug, Clone)] pub struct Pipeline { pipeline: wgpu::RenderPipeline, } impl Pipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, constants_layout: &wgpu::BindGroupLayout, ) -> Self { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu.quad.solid.pipeline"), push_constant_ranges: &[], bind_group_layouts: &[constants_layout], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.quad.solid.shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( include_str!("../shader/color.wgsl"), "\n", include_str!("../shader/quad.wgsl"), "\n", include_str!("../shader/vertex.wgsl"), "\n", include_str!("../shader/quad/solid.wgsl"), ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu.quad.solid.pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("solid_vs_main"), buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Solid>() as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &wgpu::vertex_attr_array!( // Color 0 => Float32x4, // Position 1 => Float32x2, // Size 2 => Float32x2, // Border color 3 => Float32x4, // Border radius 4 => Float32x4, // Border width 5 => Float32, // Shadow color 6 => Float32x4, // Shadow offset 7 => Float32x2, // Shadow blur radius 8 => Float32, // Snap 9 => Uint32, ), }], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("solid_fs_main"), targets: &quad::color_target_state(format), compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview: None, cache: None, }); Self { pipeline } } pub fn render<'a>( &'a self, render_pass: &mut wgpu::RenderPass<'a>, constants: &'a wgpu::BindGroup, layer: &'a Layer, range: Range<usize>, ) { render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, constants, &[]); render_pass.set_vertex_buffer(0, layer.instances.slice(..)); render_pass.draw(0..6, range.start as u32..range.end as u32); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/quad/gradient.rs
wgpu/src/quad/gradient.rs
use crate::Buffer; use crate::graphics::gradient; use crate::quad::{self, Quad}; use bytemuck::{Pod, Zeroable}; use std::ops::Range; /// A quad filled with interpolated colors. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Gradient { /// The background gradient data of the quad. pub gradient: gradient::Packed, /// The [`Quad`] data of the [`Gradient`]. pub quad: Quad, } #[allow(unsafe_code)] unsafe impl Pod for Gradient {} #[allow(unsafe_code)] unsafe impl Zeroable for Gradient {} #[derive(Debug)] pub struct Layer { instances: Buffer<Gradient>, instance_count: usize, } impl Layer { pub fn new(device: &wgpu::Device) -> Self { let instances = Buffer::new( device, "iced_wgpu.quad.gradient.buffer", quad::INITIAL_INSTANCES, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); Self { instances, instance_count: 0, } } pub fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, instances: &[Gradient], ) { let _ = self.instances.resize(device, instances.len()); let _ = self.instances.write(device, encoder, belt, 0, instances); self.instance_count = instances.len(); } } #[derive(Debug, Clone)] pub struct Pipeline { #[cfg(not(target_arch = "wasm32"))] pipeline: wgpu::RenderPipeline, } impl Pipeline { #[allow(unused_variables)] pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, constants_layout: &wgpu::BindGroupLayout, ) -> Self { #[cfg(not(target_arch = "wasm32"))] { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu.quad.gradient.pipeline"), push_constant_ranges: &[], bind_group_layouts: &[constants_layout], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.quad.gradient.shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( include_str!("../shader/quad.wgsl"), "\n", include_str!("../shader/vertex.wgsl"), "\n", include_str!("../shader/quad/gradient.wgsl"), "\n", include_str!("../shader/color.wgsl"), "\n", include_str!("../shader/color/linear_rgb.wgsl") ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu.quad.gradient.pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("gradient_vs_main"), buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Gradient>() as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &wgpu::vertex_attr_array!( // Colors 1-2 0 => Uint32x4, // Colors 3-4 1 => Uint32x4, // Colors 5-6 2 => Uint32x4, // Colors 7-8 3 => Uint32x4, // Offsets 1-8 4 => Uint32x4, // Direction 5 => Float32x4, // Position & Scale 6 => Float32x4, // Border color 7 => Float32x4, // Border radius 8 => Float32x4, // Border width 9 => Float32, // Snap 10 => Uint32, ), }], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("gradient_fs_main"), targets: &quad::color_target_state(format), compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview: None, cache: None, }); Self { pipeline } } #[cfg(target_arch = "wasm32")] Self {} } #[allow(unused_variables)] pub fn render<'a>( &'a self, render_pass: &mut wgpu::RenderPass<'a>, constants: &'a wgpu::BindGroup, layer: &'a Layer, range: Range<usize>, ) { #[cfg(not(target_arch = "wasm32"))] { render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, constants, &[]); render_pass.set_vertex_buffer(0, layer.instances.slice(..)); render_pass.draw(0..6, range.start as u32..range.end as u32); } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/wgpu/src/triangle/msaa.rs
wgpu/src/triangle/msaa.rs
use crate::core::{Size, Transformation}; use crate::graphics; use std::num::NonZeroU64; use std::sync::{Arc, RwLock}; #[derive(Debug, Clone)] pub struct Pipeline { format: wgpu::TextureFormat, sampler: wgpu::Sampler, raw: wgpu::RenderPipeline, constant_layout: wgpu::BindGroupLayout, texture_layout: wgpu::BindGroupLayout, sample_count: u32, targets: Arc<RwLock<Option<Targets>>>, } impl Pipeline { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, antialiasing: graphics::Antialiasing, ) -> Pipeline { let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default()); let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu::triangle:msaa uniforms 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::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, ], }); let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu::triangle::msaa texture layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, 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 layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("iced_wgpu::triangle::msaa pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu triangle blit_shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( "../shader/blit.wgsl" ))), }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("iced_wgpu::triangle::msaa pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Cw, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, multiview: None, cache: None, }); Self { format, sampler, raw: pipeline, constant_layout, texture_layout, sample_count: antialiasing.sample_count(), targets: Arc::new(RwLock::new(None)), } } fn targets(&self, device: &wgpu::Device, region_size: Size<u32>) -> Targets { let mut targets = self.targets.write().expect("Write MSAA targets"); match targets.as_mut() { Some(targets) if region_size.width <= targets.size.width && region_size.height <= targets.size.height => {} _ => { *targets = Some(Targets::new( device, self.format, &self.texture_layout, self.sample_count, region_size, )); } } targets.as_ref().unwrap().clone() } pub fn render_pass<'a>(&self, encoder: &'a mut wgpu::CommandEncoder) -> wgpu::RenderPass<'a> { let targets = self.targets.read().expect("Read MSAA targets"); let targets = targets.as_ref().unwrap(); encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu.triangle.render_pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &targets.attachment, depth_slice: None, resolve_target: Some(&targets.resolve), ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }) } } #[derive(Debug, Clone)] struct Targets { attachment: wgpu::TextureView, resolve: wgpu::TextureView, bind_group: wgpu::BindGroup, size: Size<u32>, } impl Targets { pub fn new( device: &wgpu::Device, format: wgpu::TextureFormat, texture_layout: &wgpu::BindGroupLayout, sample_count: u32, size: Size<u32>, ) -> Targets { let extent = wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1, }; let attachment = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu::triangle::msaa attachment"), size: extent, mip_level_count: 1, sample_count, dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[], }); let resolve = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu::triangle::msaa resolve target"), size: extent, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let attachment = attachment.create_view(&wgpu::TextureViewDescriptor::default()); let resolve = resolve.create_view(&wgpu::TextureViewDescriptor::default()); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::triangle::msaa texture bind group"), layout: texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&resolve), }], }); Targets { attachment, resolve, bind_group, size, } } } #[derive(Debug, Clone, Copy, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] struct Ratio { u: f32, v: f32, // Padding field for 16-byte alignment. // See https://docs.rs/wgpu/latest/wgpu/struct.DownlevelFlags.html#associatedconstant.BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED _padding: [f32; 2], } pub struct State { ratio: wgpu::Buffer, constants: wgpu::BindGroup, last_ratio: Option<Ratio>, } impl State { pub fn new(device: &wgpu::Device, pipeline: &Pipeline) -> Self { let ratio = device.create_buffer(&wgpu::BufferDescriptor { label: Some("iced_wgpu::triangle::msaa ratio"), size: std::mem::size_of::<Ratio>() as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, mapped_at_creation: false, }); let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::triangle::msaa uniforms bind group"), layout: &pipeline.constant_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Sampler(&pipeline.sampler), }, wgpu::BindGroupEntry { binding: 1, resource: ratio.as_entire_binding(), }, ], }); Self { ratio, constants, last_ratio: None, } } pub fn prepare( &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, belt: &mut wgpu::util::StagingBelt, pipeline: &Pipeline, region_size: Size<u32>, ) -> Transformation { let targets = pipeline.targets(device, region_size); let ratio = Ratio { u: region_size.width as f32 / targets.size.width as f32, v: region_size.height as f32 / targets.size.height as f32, _padding: [0.0; 2], }; if Some(ratio) != self.last_ratio { belt.write_buffer( encoder, &self.ratio, 0, NonZeroU64::new(std::mem::size_of::<Ratio>() as u64).expect("non-empty ratio"), device, ) .copy_from_slice(bytemuck::bytes_of(&ratio)); self.last_ratio = Some(ratio); } Transformation::orthographic(targets.size.width, targets.size.height) } pub fn render( &self, pipeline: &Pipeline, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, ) { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu::triangle::msaa render 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: None, timestamp_writes: None, occlusion_query_set: None, }); render_pass.set_pipeline(&pipeline.raw); render_pass.set_bind_group(0, &self.constants, &[]); render_pass.set_bind_group( 1, &pipeline .targets .read() .expect("Read MSAA targets") .as_ref() .unwrap() .bind_group, &[], ); render_pass.draw(0..6, 0..1); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/button.rs
widget/src/button.rs
//! Buttons allow your users to perform actions by pressing them. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::button; //! //! #[derive(Clone)] //! enum Message { //! ButtonPressed, //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! button("Press me!").on_press(Message::ButtonPressed).into() //! } //! ``` use crate::core::border::{self, Border}; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::theme::palette; use crate::core::touch; use crate::core::widget::Operation; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Clipboard, Color, Element, Event, Layout, Length, Padding, Rectangle, Shadow, Shell, Size, Theme, Vector, Widget, }; /// A generic widget that produces a message when pressed. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::button; /// /// #[derive(Clone)] /// enum Message { /// ButtonPressed, /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// button("Press me!").on_press(Message::ButtonPressed).into() /// } /// ``` /// /// If a [`Button::on_press`] handler is not set, the resulting [`Button`] will /// be disabled: /// /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::button; /// /// #[derive(Clone)] /// enum Message { /// ButtonPressed, /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// button("I am disabled!").into() /// } /// ``` pub struct Button<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Renderer: crate::core::Renderer, Theme: Catalog, { content: Element<'a, Message, Theme, Renderer>, on_press: Option<OnPress<'a, Message>>, width: Length, height: Length, padding: Padding, clip: bool, class: Theme::Class<'a>, status: Option<Status>, } enum OnPress<'a, Message> { Direct(Message), Closure(Box<dyn Fn() -> Message + 'a>), } impl<Message: Clone> OnPress<'_, Message> { fn get(&self) -> Message { match self { OnPress::Direct(message) => message.clone(), OnPress::Closure(f) => f(), } } } impl<'a, Message, Theme, Renderer> Button<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, Theme: Catalog, { /// Creates a new [`Button`] with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { let content = content.into(); let size = content.as_widget().size_hint(); Button { content, on_press: None, width: size.width.fluid(), height: size.height.fluid(), padding: DEFAULT_PADDING, clip: false, class: Theme::default(), status: None, } } /// Sets the width of the [`Button`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Button`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the [`Padding`] of the [`Button`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the message that will be produced when the [`Button`] is pressed. /// /// Unless `on_press` is called, the [`Button`] will be disabled. pub fn on_press(mut self, on_press: Message) -> Self { self.on_press = Some(OnPress::Direct(on_press)); self } /// Sets the message that will be produced when the [`Button`] is pressed. /// /// This is analogous to [`Button::on_press`], but using a closure to produce /// the message. /// /// This closure will only be called when the [`Button`] is actually pressed and, /// therefore, this method is useful to reduce overhead if creating the resulting /// message is slow. pub fn on_press_with(mut self, on_press: impl Fn() -> Message + 'a) -> Self { self.on_press = Some(OnPress::Closure(Box::new(on_press))); self } /// Sets the message that will be produced when the [`Button`] is pressed, /// if `Some`. /// /// If `None`, the [`Button`] will be disabled. pub fn on_press_maybe(mut self, on_press: Option<Message>) -> Self { self.on_press = on_press.map(OnPress::Direct); self } /// Sets whether the contents of the [`Button`] should be clipped on /// overflow. pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// Sets the style of the [`Button`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Button`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] struct State { is_pressed: bool, } impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Button<'a, Message, Theme, Renderer> where Message: 'a + Clone, Renderer: 'a + crate::core::Renderer, Theme: Catalog, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::default()) } fn children(&self) -> Vec<Tree> { vec![Tree::new(&self.content)] } fn diff(&self, tree: &mut Tree) { tree.diff_children(std::slice::from_ref(&self.content)); } 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::padded(limits, self.width, self.height, self.padding, |limits| { self.content .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) }) } 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.children().next().unwrap(), 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.children().next().unwrap(), cursor, renderer, clipboard, shell, viewport, ); if shell.is_event_captured() { return; } match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if self.on_press.is_some() { let bounds = layout.bounds(); if cursor.is_over(bounds) { let state = tree.state.downcast_mut::<State>(); state.is_pressed = true; shell.capture_event(); } } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) => { if let Some(on_press) = &self.on_press { let state = tree.state.downcast_mut::<State>(); if state.is_pressed { state.is_pressed = false; let bounds = layout.bounds(); if cursor.is_over(bounds) { shell.publish(on_press.get()); } shell.capture_event(); } } } Event::Touch(touch::Event::FingerLost { .. }) => { let state = tree.state.downcast_mut::<State>(); state.is_pressed = false; } _ => {} } let current_status = if self.on_press.is_none() { Status::Disabled } else if cursor.is_over(layout.bounds()) { let state = tree.state.downcast_ref::<State>(); if state.is_pressed { Status::Pressed } else { Status::Hovered } } else { Status::Active }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.status = Some(current_status); } else if self.status.is_some_and(|status| status != current_status) { 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 content_layout = layout.children().next().unwrap(); let style = theme.style(&self.class, self.status.unwrap_or(Status::Disabled)); if style.background.is_some() || style.border.width > 0.0 || style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds, border: style.border, shadow: style.shadow, snap: style.snap, }, style .background .unwrap_or(Background::Color(Color::TRANSPARENT)), ); } let viewport = if self.clip { bounds.intersection(viewport).unwrap_or(*viewport) } else { *viewport }; self.content.as_widget().draw( &tree.children[0], renderer, theme, &renderer::Style { text_color: style.text_color, }, content_layout, cursor, &viewport, ); } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let is_mouse_over = cursor.is_over(layout.bounds()); if is_mouse_over && self.on_press.is_some() { mouse::Interaction::Pointer } else { mouse::Interaction::default() } } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( &mut tree.children[0], layout.children().next().unwrap(), renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Button<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Theme: Catalog + 'a, Renderer: crate::core::Renderer + 'a, { fn from(button: Button<'a, Message, Theme, Renderer>) -> Self { Self::new(button) } } /// The default [`Padding`] of a [`Button`]. pub const DEFAULT_PADDING: Padding = Padding { top: 5.0, bottom: 5.0, right: 10.0, left: 10.0, }; /// The possible status of a [`Button`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Button`] can be pressed. Active, /// The [`Button`] can be pressed and it is being hovered. Hovered, /// The [`Button`] is being pressed. Pressed, /// The [`Button`] cannot be pressed. Disabled, } /// The style of a button. /// /// If not specified with [`Button::style`] /// the theme will provide the style. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Background`] of the button. pub background: Option<Background>, /// The text [`Color`] of the button. pub text_color: Color, /// The [`Border`] of the button. pub border: Border, /// The [`Shadow`] of the button. pub shadow: Shadow, /// Whether the button should be snapped to the pixel grid. pub snap: bool, } impl Style { /// Updates the [`Style`] with the given [`Background`]. pub fn with_background(self, background: impl Into<Background>) -> Self { Self { background: Some(background.into()), ..self } } } impl Default for Style { fn default() -> Self { Self { background: None, text_color: Color::BLACK, border: Border::default(), shadow: Shadow::default(), snap: renderer::CRISP, } } } /// The theme catalog of a [`Button`]. /// /// All themes that can be used with [`Button`] /// must implement this trait. /// /// # Example /// ```no_run /// # use iced_widget::core::{Color, Background}; /// # use iced_widget::button::{Catalog, Status, Style}; /// # struct MyTheme; /// #[derive(Debug, Default)] /// pub enum ButtonClass { /// #[default] /// Primary, /// Secondary, /// Danger /// } /// /// impl Catalog for MyTheme { /// type Class<'a> = ButtonClass; /// /// fn default<'a>() -> Self::Class<'a> { /// ButtonClass::default() /// } /// /// /// fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { /// let mut style = Style::default(); /// /// match class { /// ButtonClass::Primary => { /// style.background = Some(Background::Color(Color::from_rgb(0.529, 0.808, 0.921))); /// }, /// ButtonClass::Secondary => { /// style.background = Some(Background::Color(Color::WHITE)); /// }, /// ButtonClass::Danger => { /// style.background = Some(Background::Color(Color::from_rgb(0.941, 0.502, 0.502))); /// }, /// } /// /// style /// } /// } /// ``` /// /// Although, in order to use [`Button::style`] /// with `MyTheme`, [`Catalog::Class`] must implement /// `From<StyleFn<'_, MyTheme>>`. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } /// A styling function for a [`Button`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(primary) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// A primary button; denoting a main action. pub fn primary(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.primary.base); match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { background: Some(Background::Color(palette.primary.strong.color)), ..base }, Status::Disabled => disabled(base), } } /// A secondary button; denoting a complementary action. pub fn secondary(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.secondary.base); match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { background: Some(Background::Color(palette.secondary.strong.color)), ..base }, Status::Disabled => disabled(base), } } /// A success button; denoting a good outcome. pub fn success(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.success.base); match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { background: Some(Background::Color(palette.success.strong.color)), ..base }, Status::Disabled => disabled(base), } } /// A warning button; denoting a risky action. pub fn warning(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.warning.base); match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { background: Some(Background::Color(palette.warning.strong.color)), ..base }, Status::Disabled => disabled(base), } } /// A danger button; denoting a destructive action. pub fn danger(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.danger.base); match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { background: Some(Background::Color(palette.danger.strong.color)), ..base }, Status::Disabled => disabled(base), } } /// A text button; useful for links. pub fn text(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = Style { text_color: palette.background.base.text, ..Style::default() }; match status { Status::Active | Status::Pressed => base, Status::Hovered => Style { text_color: palette.background.base.text.scale_alpha(0.8), ..base }, Status::Disabled => disabled(base), } } /// A button using background shades. pub fn background(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.background.base); match status { Status::Active => base, Status::Pressed => Style { background: Some(Background::Color(palette.background.strong.color)), ..base }, Status::Hovered => Style { background: Some(Background::Color(palette.background.weak.color)), ..base }, Status::Disabled => disabled(base), } } /// A subtle button using weak background shades. pub fn subtle(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let base = styled(palette.background.weakest); match status { Status::Active => base, Status::Pressed => Style { background: Some(Background::Color(palette.background.strong.color)), ..base }, Status::Hovered => Style { background: Some(Background::Color(palette.background.weaker.color)), ..base }, Status::Disabled => disabled(base), } } fn styled(pair: palette::Pair) -> Style { Style { background: Some(Background::Color(pair.color)), text_color: pair.text, border: border::rounded(2), ..Style::default() } } fn disabled(style: Style) -> Style { Style { background: style .background .map(|background| background.scale_alpha(0.5)), text_color: style.text_color.scale_alpha(0.5), ..style } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/vertical_slider.rs
widget/src/vertical_slider.rs
//! Sliders let users set a value by moving an indicator. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::slider; //! //! struct State { //! value: f32, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! ValueChanged(f32), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! slider(0.0..=100.0, state.value, Message::ValueChanged).into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::ValueChanged(value) => { //! state.value = value; //! } //! } //! } //! ``` use std::ops::RangeInclusive; pub use crate::slider::{Catalog, Handle, HandleShape, Status, Style, StyleFn, default}; use crate::core::border::Border; use crate::core::keyboard; use crate::core::keyboard::key::{self, Key}; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::touch; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ self, Clipboard, Element, Event, Length, Pixels, Point, Rectangle, Shell, Size, Widget, }; /// An vertical bar and a handle that selects a single value from a range of /// values. /// /// A [`VerticalSlider`] will try to fill the vertical space of its container. /// /// The [`VerticalSlider`] range of numeric values is generic and its step size defaults /// to 1 unit. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::vertical_slider; /// /// struct State { /// value: f32, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// ValueChanged(f32), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// vertical_slider(0.0..=100.0, state.value, Message::ValueChanged).into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::ValueChanged(value) => { /// state.value = value; /// } /// } /// } /// ``` pub struct VerticalSlider<'a, T, Message, Theme = crate::Theme> where Theme: Catalog, { range: RangeInclusive<T>, step: T, shift_step: Option<T>, value: T, default: Option<T>, on_change: Box<dyn Fn(T) -> Message + 'a>, on_release: Option<Message>, width: f32, height: Length, class: Theme::Class<'a>, status: Option<Status>, } impl<'a, T, Message, Theme> VerticalSlider<'a, T, Message, Theme> where T: Copy + From<u8> + std::cmp::PartialOrd, Message: Clone, Theme: Catalog, { /// The default width of a [`VerticalSlider`]. pub const DEFAULT_WIDTH: f32 = 16.0; /// Creates a new [`VerticalSlider`]. /// /// It expects: /// * an inclusive range of possible values /// * the current value of the [`VerticalSlider`] /// * a function that will be called when the [`VerticalSlider`] is dragged. /// It receives the new value of the [`VerticalSlider`] and must produce a /// `Message`. pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self where F: 'a + Fn(T) -> Message, { let value = if value >= *range.start() { value } else { *range.start() }; let value = if value <= *range.end() { value } else { *range.end() }; VerticalSlider { value, default: None, range, step: T::from(1), shift_step: None, on_change: Box::new(on_change), on_release: None, width: Self::DEFAULT_WIDTH, height: Length::Fill, class: Theme::default(), status: None, } } /// Sets the optional default value for the [`VerticalSlider`]. /// /// If set, the [`VerticalSlider`] will reset to this value when ctrl-clicked or command-clicked. pub fn default(mut self, default: impl Into<T>) -> Self { self.default = Some(default.into()); self } /// Sets the release message of the [`VerticalSlider`]. /// This is called when the mouse is released from the slider. /// /// Typically, the user's interaction with the slider is finished when this message is produced. /// This is useful if you need to spawn a long-running task from the slider's result, where /// the default on_change message could create too many events. pub fn on_release(mut self, on_release: Message) -> Self { self.on_release = Some(on_release); self } /// Sets the width of the [`VerticalSlider`]. pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into().0; self } /// Sets the height of the [`VerticalSlider`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the step size of the [`VerticalSlider`]. pub fn step(mut self, step: T) -> Self { self.step = step; self } /// Sets the optional "shift" step for the [`VerticalSlider`]. /// /// If set, this value is used as the step while the shift key is pressed. pub fn shift_step(mut self, shift_step: impl Into<T>) -> Self { self.shift_step = Some(shift_step.into()); self } /// Sets the style of the [`VerticalSlider`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`VerticalSlider`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for VerticalSlider<'_, T, Message, Theme> where T: Copy + Into<f64> + num_traits::FromPrimitive, Message: Clone, Theme: Catalog, Renderer: core::Renderer, { 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::Shrink, 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>(); let is_dragging = state.is_dragging; let current_value = self.value; let locate = |cursor_position: Point| -> Option<T> { let bounds = layout.bounds(); if cursor_position.y >= bounds.y + bounds.height { Some(*self.range.start()) } else if cursor_position.y <= bounds.y { Some(*self.range.end()) } else { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let start = (*self.range.start()).into(); let end = (*self.range.end()).into(); let percent = 1.0 - f64::from(cursor_position.y - bounds.y) / f64::from(bounds.height); let steps = (percent * (end - start) / step).round(); let value = steps * step + start; T::from_f64(value.min(end)) } }; let increment = |value: T| -> Option<T> { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let steps = (value.into() / step).round(); let new_value = step * (steps + 1.0); if new_value > (*self.range.end()).into() { return Some(*self.range.end()); } T::from_f64(new_value) }; let decrement = |value: T| -> Option<T> { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let steps = (value.into() / step).round(); let new_value = step * (steps - 1.0); if new_value < (*self.range.start()).into() { return Some(*self.range.start()); } T::from_f64(new_value) }; let change = |new_value: T| { if (self.value.into() - new_value.into()).abs() > f64::EPSILON { shell.publish((self.on_change)(new_value)); self.value = new_value; } }; match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if let Some(cursor_position) = cursor.position_over(layout.bounds()) { if state.keyboard_modifiers.control() || state.keyboard_modifiers.command() { let _ = self.default.map(change); state.is_dragging = false; } else { let _ = locate(cursor_position).map(change); state.is_dragging = true; } shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) | Event::Touch(touch::Event::FingerLost { .. }) => { if is_dragging { if let Some(on_release) = self.on_release.clone() { shell.publish(on_release); } state.is_dragging = false; } } Event::Mouse(mouse::Event::CursorMoved { .. }) | Event::Touch(touch::Event::FingerMoved { .. }) => { if is_dragging { let _ = cursor.land().position().and_then(locate).map(change); shell.capture_event(); } } Event::Mouse(mouse::Event::WheelScrolled { delta }) if state.keyboard_modifiers.control() => { if cursor.is_over(layout.bounds()) { let delta = match *delta { mouse::ScrollDelta::Lines { x: _, y } => y, mouse::ScrollDelta::Pixels { x: _, y } => y, }; if delta < 0.0 { let _ = decrement(current_value).map(change); } else { let _ = increment(current_value).map(change); } shell.capture_event(); } } Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) => { if cursor.is_over(layout.bounds()) { match key { Key::Named(key::Named::ArrowUp) => { let _ = increment(current_value).map(change); shell.capture_event(); } Key::Named(key::Named::ArrowDown) => { let _ = decrement(current_value).map(change); shell.capture_event(); } _ => (), } } } Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => { state.keyboard_modifiers = *modifiers; } _ => {} } let current_status = if state.is_dragging { Status::Dragged } else if cursor.is_over(layout.bounds()) { Status::Hovered } else { Status::Active }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.status = Some(current_status); } else if self.status.is_some_and(|status| status != current_status) { 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 style = theme.style(&self.class, self.status.unwrap_or(Status::Active)); let (handle_width, handle_height, handle_border_radius) = match style.handle.shape { HandleShape::Circle { radius } => (radius * 2.0, radius * 2.0, radius.into()), HandleShape::Rectangle { width, border_radius, } => (f32::from(width), bounds.width, border_radius), }; let value = self.value.into() as f32; let (range_start, range_end) = { let (start, end) = self.range.clone().into_inner(); (start.into() as f32, end.into() as f32) }; let offset = if range_start >= range_end { 0.0 } else { (bounds.height - handle_width) * (value - range_end) / (range_start - range_end) }; let rail_x = bounds.x + bounds.width / 2.0; renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: rail_x - style.rail.width / 2.0, y: bounds.y, width: style.rail.width, height: offset + handle_width / 2.0, }, border: style.rail.border, ..renderer::Quad::default() }, style.rail.backgrounds.1, ); renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: rail_x - style.rail.width / 2.0, y: bounds.y + offset + handle_width / 2.0, width: style.rail.width, height: bounds.height - offset - handle_width / 2.0, }, border: style.rail.border, ..renderer::Quad::default() }, style.rail.backgrounds.0, ); renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: rail_x - handle_height / 2.0, y: bounds.y + offset, width: handle_height, height: handle_width, }, border: Border { radius: handle_border_radius, width: style.handle.border_width, color: style.handle.border_color, }, ..renderer::Quad::default() }, style.handle.background, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let state = tree.state.downcast_ref::<State>(); if state.is_dragging { // FIXME: Fall back to `Pointer` on Windows // See https://github.com/rust-windowing/winit/issues/1043 if cfg!(target_os = "windows") { mouse::Interaction::Pointer } else { mouse::Interaction::Grabbing } } else if cursor.is_over(layout.bounds()) { if cfg!(target_os = "windows") { mouse::Interaction::Pointer } else { mouse::Interaction::Grab } } else { mouse::Interaction::default() } } } impl<'a, T, Message, Theme, Renderer> From<VerticalSlider<'a, T, Message, Theme>> for Element<'a, Message, Theme, Renderer> where T: Copy + Into<f64> + num_traits::FromPrimitive + 'a, Message: Clone + 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from( slider: VerticalSlider<'a, T, Message, Theme>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(slider) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] struct State { is_dragging: bool, keyboard_modifiers: keyboard::Modifiers, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/lib.rs
widget/src/lib.rs
//! Use the built-in widgets or create your own. #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] pub use iced_renderer as renderer; pub use iced_renderer::core; pub use iced_renderer::graphics; pub use core::widget::Id; mod action; mod column; mod mouse_area; mod pin; mod responsive; mod stack; mod themer; pub mod button; pub mod checkbox; pub mod combo_box; pub mod container; pub mod float; pub mod grid; pub mod keyed; pub mod overlay; pub mod pane_grid; pub mod pick_list; pub mod progress_bar; pub mod radio; pub mod row; pub mod rule; pub mod scrollable; pub mod sensor; pub mod slider; pub mod space; pub mod table; pub mod text; pub mod text_editor; pub mod text_input; pub mod toggler; pub mod tooltip; pub mod vertical_slider; mod helpers; pub use helpers::*; #[cfg(feature = "lazy")] mod lazy; #[cfg(feature = "lazy")] pub use crate::lazy::helpers::*; #[doc(no_inline)] pub use button::Button; #[doc(no_inline)] pub use checkbox::Checkbox; #[doc(no_inline)] pub use column::Column; #[doc(no_inline)] pub use combo_box::ComboBox; #[doc(no_inline)] pub use container::Container; #[doc(no_inline)] pub use float::Float; #[doc(no_inline)] pub use grid::Grid; #[doc(no_inline)] pub use mouse_area::MouseArea; #[doc(no_inline)] pub use pane_grid::PaneGrid; #[doc(no_inline)] pub use pick_list::PickList; #[doc(no_inline)] pub use pin::Pin; #[doc(no_inline)] pub use progress_bar::ProgressBar; #[doc(no_inline)] pub use radio::Radio; #[doc(no_inline)] pub use responsive::Responsive; #[doc(no_inline)] pub use row::Row; #[doc(no_inline)] pub use rule::Rule; #[doc(no_inline)] pub use scrollable::Scrollable; #[doc(no_inline)] pub use sensor::Sensor; #[doc(no_inline)] pub use slider::Slider; #[doc(no_inline)] pub use space::Space; #[doc(no_inline)] pub use stack::Stack; #[doc(no_inline)] pub use text::Text; #[doc(no_inline)] pub use text_editor::TextEditor; #[doc(no_inline)] pub use text_input::TextInput; #[doc(no_inline)] pub use themer::Themer; #[doc(no_inline)] pub use toggler::Toggler; #[doc(no_inline)] pub use tooltip::Tooltip; #[doc(no_inline)] pub use vertical_slider::VerticalSlider; #[cfg(feature = "wgpu")] pub mod shader; #[cfg(feature = "wgpu")] #[doc(no_inline)] pub use shader::Shader; #[cfg(feature = "svg")] pub mod svg; #[cfg(feature = "svg")] #[doc(no_inline)] pub use svg::Svg; #[cfg(feature = "image")] pub mod image; #[cfg(feature = "image")] #[doc(no_inline)] pub use image::Image; #[cfg(feature = "canvas")] pub mod canvas; #[cfg(feature = "canvas")] #[doc(no_inline)] pub use canvas::Canvas; #[cfg(feature = "qr_code")] pub mod qr_code; #[cfg(feature = "qr_code")] #[doc(no_inline)] pub use qr_code::QRCode; #[cfg(feature = "markdown")] pub mod markdown; pub use crate::core::theme::{self, Theme}; pub use action::Action; pub use renderer::Renderer;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/scrollable.rs
widget/src/scrollable.rs
//! Scrollables let users navigate an endless amount of content with a scrollbar. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::{column, scrollable, space}; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! scrollable(column![ //! "Scroll me!", //! space().height(3000), //! "You did it!", //! ]).into() //! } //! ``` use crate::container; use crate::core::alignment; use crate::core::border::{self, Border}; use crate::core::keyboard; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::text; use crate::core::time::{Duration, Instant}; use crate::core::touch; use crate::core::widget; use crate::core::widget::operation::{self, Operation}; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ self, Background, Clipboard, Color, Element, Event, InputMethod, Layout, Length, Padding, Pixels, Point, Rectangle, Shadow, Shell, Size, Theme, Vector, Widget, }; pub use operation::scrollable::{AbsoluteOffset, RelativeOffset}; /// A widget that can vertically display an infinite amount of content with a /// scrollbar. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{column, scrollable, space}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// scrollable(column![ /// "Scroll me!", /// space().height(3000), /// "You did it!", /// ]).into() /// } /// ``` pub struct Scrollable<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, { id: Option<widget::Id>, width: Length, height: Length, direction: Direction, auto_scroll: bool, content: Element<'a, Message, Theme, Renderer>, on_scroll: Option<Box<dyn Fn(Viewport) -> Message + 'a>>, class: Theme::Class<'a>, last_status: Option<Status>, } impl<'a, Message, Theme, Renderer> Scrollable<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { /// Creates a new vertical [`Scrollable`]. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self::with_direction(content, Direction::default()) } /// Creates a new [`Scrollable`] with the given [`Direction`]. pub fn with_direction( content: impl Into<Element<'a, Message, Theme, Renderer>>, direction: impl Into<Direction>, ) -> Self { Scrollable { id: None, width: Length::Shrink, height: Length::Shrink, direction: direction.into(), auto_scroll: false, content: content.into(), on_scroll: None, class: Theme::default(), last_status: None, } .enclose() } fn enclose(mut self) -> Self { let size_hint = self.content.as_widget().size_hint(); if self.direction.horizontal().is_none() { self.width = self.width.enclose(size_hint.width); } if self.direction.vertical().is_none() { self.height = self.height.enclose(size_hint.height); } self } /// Makes the [`Scrollable`] scroll horizontally, with default [`Scrollbar`] settings. pub fn horizontal(self) -> Self { self.direction(Direction::Horizontal(Scrollbar::default())) } /// Sets the [`Direction`] of the [`Scrollable`]. pub fn direction(mut self, direction: impl Into<Direction>) -> Self { self.direction = direction.into(); self.enclose() } /// Sets the [`widget::Id`] of the [`Scrollable`]. pub fn id(mut self, id: impl Into<widget::Id>) -> Self { self.id = Some(id.into()); self } /// Sets the width of the [`Scrollable`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Scrollable`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets a function to call when the [`Scrollable`] is scrolled. /// /// The function takes the [`Viewport`] of the [`Scrollable`] pub fn on_scroll(mut self, f: impl Fn(Viewport) -> Message + 'a) -> Self { self.on_scroll = Some(Box::new(f)); self } /// Anchors the vertical [`Scrollable`] direction to the top. pub fn anchor_top(self) -> Self { self.anchor_y(Anchor::Start) } /// Anchors the vertical [`Scrollable`] direction to the bottom. pub fn anchor_bottom(self) -> Self { self.anchor_y(Anchor::End) } /// Anchors the horizontal [`Scrollable`] direction to the left. pub fn anchor_left(self) -> Self { self.anchor_x(Anchor::Start) } /// Anchors the horizontal [`Scrollable`] direction to the right. pub fn anchor_right(self) -> Self { self.anchor_x(Anchor::End) } /// Sets the [`Anchor`] of the horizontal direction of the [`Scrollable`], if applicable. pub fn anchor_x(mut self, alignment: Anchor) -> Self { match &mut self.direction { Direction::Horizontal(horizontal) | Direction::Both { horizontal, .. } => { horizontal.alignment = alignment; } Direction::Vertical { .. } => {} } self } /// Sets the [`Anchor`] of the vertical direction of the [`Scrollable`], if applicable. pub fn anchor_y(mut self, alignment: Anchor) -> Self { match &mut self.direction { Direction::Vertical(vertical) | Direction::Both { vertical, .. } => { vertical.alignment = alignment; } Direction::Horizontal { .. } => {} } self } /// Embeds the [`Scrollbar`] into the [`Scrollable`], instead of floating on top of the /// content. /// /// The `spacing` provided will be used as space between the [`Scrollbar`] and the contents /// of the [`Scrollable`]. pub fn spacing(mut self, new_spacing: impl Into<Pixels>) -> Self { match &mut self.direction { Direction::Horizontal(scrollbar) | Direction::Vertical(scrollbar) => { scrollbar.spacing = Some(new_spacing.into().0); } Direction::Both { .. } => {} } self } /// Sets whether the user should be allowed to auto-scroll the [`Scrollable`] /// with the middle mouse button. /// /// By default, it is disabled. pub fn auto_scroll(mut self, auto_scroll: bool) -> Self { self.auto_scroll = auto_scroll; self } /// Sets the style of this [`Scrollable`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Scrollable`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } /// The direction of [`Scrollable`]. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Direction { /// Vertical scrolling Vertical(Scrollbar), /// Horizontal scrolling Horizontal(Scrollbar), /// Both vertical and horizontal scrolling Both { /// The properties of the vertical scrollbar. vertical: Scrollbar, /// The properties of the horizontal scrollbar. horizontal: Scrollbar, }, } impl Direction { /// Returns the horizontal [`Scrollbar`], if any. pub fn horizontal(&self) -> Option<&Scrollbar> { match self { Self::Horizontal(scrollbar) => Some(scrollbar), Self::Both { horizontal, .. } => Some(horizontal), Self::Vertical(_) => None, } } /// Returns the vertical [`Scrollbar`], if any. pub fn vertical(&self) -> Option<&Scrollbar> { match self { Self::Vertical(scrollbar) => Some(scrollbar), Self::Both { vertical, .. } => Some(vertical), Self::Horizontal(_) => None, } } fn align(&self, delta: Vector) -> Vector { let horizontal_alignment = self.horizontal().map(|p| p.alignment).unwrap_or_default(); let vertical_alignment = self.vertical().map(|p| p.alignment).unwrap_or_default(); let align = |alignment: Anchor, delta: f32| match alignment { Anchor::Start => delta, Anchor::End => -delta, }; Vector::new( align(horizontal_alignment, delta.x), align(vertical_alignment, delta.y), ) } } impl Default for Direction { fn default() -> Self { Self::Vertical(Scrollbar::default()) } } /// A scrollbar within a [`Scrollable`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Scrollbar { width: f32, margin: f32, scroller_width: f32, alignment: Anchor, spacing: Option<f32>, } impl Default for Scrollbar { fn default() -> Self { Self { width: 10.0, margin: 0.0, scroller_width: 10.0, alignment: Anchor::Start, spacing: None, } } } impl Scrollbar { /// Creates new [`Scrollbar`] for use in a [`Scrollable`]. pub fn new() -> Self { Self::default() } /// Create a [`Scrollbar`] with zero width to allow a [`Scrollable`] to scroll without a visible /// scroller. pub fn hidden() -> Self { Self::default().width(0).scroller_width(0) } /// Sets the scrollbar width of the [`Scrollbar`] . pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into().0.max(0.0); self } /// Sets the scrollbar margin of the [`Scrollbar`] . pub fn margin(mut self, margin: impl Into<Pixels>) -> Self { self.margin = margin.into().0; self } /// Sets the scroller width of the [`Scrollbar`] . pub fn scroller_width(mut self, scroller_width: impl Into<Pixels>) -> Self { self.scroller_width = scroller_width.into().0.max(0.0); self } /// Sets the [`Anchor`] of the [`Scrollbar`] . pub fn anchor(mut self, alignment: Anchor) -> Self { self.alignment = alignment; self } /// Sets whether the [`Scrollbar`] should be embedded in the [`Scrollable`], using /// the given spacing between itself and the contents. /// /// An embedded [`Scrollbar`] will always be displayed, will take layout space, /// and will not float over the contents. pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self { self.spacing = Some(spacing.into().0); self } } /// The anchor of the scroller of the [`Scrollable`] relative to its [`Viewport`] /// on a given axis. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Anchor { /// Scroller is anchoer to the start of the [`Viewport`]. #[default] Start, /// Content is aligned to the end of the [`Viewport`]. End, } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Scrollable<'_, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::new()) } fn children(&self) -> Vec<Tree> { vec![Tree::new(&self.content)] } fn diff(&self, tree: &mut Tree) { tree.diff_children(std::slice::from_ref(&self.content)); } 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 { let mut layout = |right_padding, bottom_padding| { layout::padded( limits, self.width, self.height, Padding { right: right_padding, bottom: bottom_padding, ..Padding::ZERO }, |limits| { let is_horizontal = self.direction.horizontal().is_some(); let is_vertical = self.direction.vertical().is_some(); let child_limits = layout::Limits::with_compression( limits.min(), Size::new( if is_horizontal { f32::INFINITY } else { limits.max().width }, if is_vertical { f32::INFINITY } else { limits.max().height }, ), Size::new(is_horizontal, is_vertical), ); self.content.as_widget_mut().layout( &mut tree.children[0], renderer, &child_limits, ) }, ) }; match self.direction { Direction::Vertical(Scrollbar { width, margin, spacing: Some(spacing), .. }) | Direction::Horizontal(Scrollbar { width, margin, spacing: Some(spacing), .. }) => { let is_vertical = matches!(self.direction, Direction::Vertical(_)); let padding = width + margin * 2.0 + spacing; let state = tree.state.downcast_mut::<State>(); let status_quo = layout( if is_vertical && state.is_scrollbar_visible { padding } else { 0.0 }, if !is_vertical && state.is_scrollbar_visible { padding } else { 0.0 }, ); let is_scrollbar_visible = if is_vertical { status_quo.children()[0].size().height > status_quo.size().height } else { status_quo.children()[0].size().width > status_quo.size().width }; if state.is_scrollbar_visible == is_scrollbar_visible { status_quo } else { log::trace!("Scrollbar status quo has changed"); state.is_scrollbar_visible = is_scrollbar_visible; layout( if is_vertical && state.is_scrollbar_visible { padding } else { 0.0 }, if !is_vertical && state.is_scrollbar_visible { padding } else { 0.0 }, ) } } _ => layout(0.0, 0.0), } } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { let state = tree.state.downcast_mut::<State>(); let bounds = layout.bounds(); let content_layout = layout.children().next().unwrap(); let content_bounds = content_layout.bounds(); let translation = state.translation(self.direction, bounds, content_bounds); operation.scrollable(self.id.as_ref(), bounds, content_bounds, translation, state); operation.traverse(&mut |operation| { self.content.as_widget_mut().operate( &mut tree.children[0], layout.children().next().unwrap(), 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, ) { const AUTOSCROLL_DEADZONE: f32 = 20.0; const AUTOSCROLL_SMOOTHNESS: f32 = 1.5; let state = tree.state.downcast_mut::<State>(); let bounds = layout.bounds(); let cursor_over_scrollable = cursor.position_over(bounds); let content = layout.children().next().unwrap(); let content_bounds = content.bounds(); let scrollbars = Scrollbars::new(state, self.direction, bounds, content_bounds); let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) = scrollbars.is_mouse_over(cursor); let last_offsets = (state.offset_x, state.offset_y); if let Some(last_scrolled) = state.last_scrolled { let clear_transaction = match event { Event::Mouse( mouse::Event::ButtonPressed(_) | mouse::Event::ButtonReleased(_) | mouse::Event::CursorLeft, ) => true, Event::Mouse(mouse::Event::CursorMoved { .. }) => { last_scrolled.elapsed() > Duration::from_millis(100) } _ => last_scrolled.elapsed() > Duration::from_millis(1500), }; if clear_transaction { state.last_scrolled = None; } } let mut update = || { if let Some(scroller_grabbed_at) = state.y_scroller_grabbed_at() { match event { Event::Mouse(mouse::Event::CursorMoved { .. }) | Event::Touch(touch::Event::FingerMoved { .. }) => { if let Some(scrollbar) = scrollbars.y { let Some(cursor_position) = cursor.land().position() else { return; }; state.scroll_y_to( scrollbar.scroll_percentage_y(scroller_grabbed_at, cursor_position), bounds, content_bounds, ); let _ = notify_scroll( state, &self.on_scroll, bounds, content_bounds, shell, ); shell.capture_event(); } } _ => {} } } else if mouse_over_y_scrollbar { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let Some(cursor_position) = cursor.position() else { return; }; if let (Some(scroller_grabbed_at), Some(scrollbar)) = (scrollbars.grab_y_scroller(cursor_position), scrollbars.y) { state.scroll_y_to( scrollbar.scroll_percentage_y(scroller_grabbed_at, cursor_position), bounds, content_bounds, ); state.interaction = Interaction::YScrollerGrabbed(scroller_grabbed_at); let _ = notify_scroll( state, &self.on_scroll, bounds, content_bounds, shell, ); } shell.capture_event(); } _ => {} } } if let Some(scroller_grabbed_at) = state.x_scroller_grabbed_at() { match event { Event::Mouse(mouse::Event::CursorMoved { .. }) | Event::Touch(touch::Event::FingerMoved { .. }) => { let Some(cursor_position) = cursor.land().position() else { return; }; if let Some(scrollbar) = scrollbars.x { state.scroll_x_to( scrollbar.scroll_percentage_x(scroller_grabbed_at, cursor_position), bounds, content_bounds, ); let _ = notify_scroll( state, &self.on_scroll, bounds, content_bounds, shell, ); } shell.capture_event(); } _ => {} } } else if mouse_over_x_scrollbar { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let Some(cursor_position) = cursor.position() else { return; }; if let (Some(scroller_grabbed_at), Some(scrollbar)) = (scrollbars.grab_x_scroller(cursor_position), scrollbars.x) { state.scroll_x_to( scrollbar.scroll_percentage_x(scroller_grabbed_at, cursor_position), bounds, content_bounds, ); state.interaction = Interaction::XScrollerGrabbed(scroller_grabbed_at); let _ = notify_scroll( state, &self.on_scroll, bounds, content_bounds, shell, ); shell.capture_event(); } } _ => {} } } if matches!(state.interaction, Interaction::AutoScrolling { .. }) && matches!( event, Event::Mouse( mouse::Event::ButtonPressed(_) | mouse::Event::WheelScrolled { .. } ) | Event::Touch(_) | Event::Keyboard(_) ) { state.interaction = Interaction::None; shell.capture_event(); shell.invalidate_layout(); shell.request_redraw(); return; } if state.last_scrolled.is_none() || !matches!(event, Event::Mouse(mouse::Event::WheelScrolled { .. })) { let translation = state.translation(self.direction, bounds, content_bounds); let cursor = match cursor_over_scrollable { Some(cursor_position) if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) => { mouse::Cursor::Available(cursor_position + translation) } _ => cursor.levitate() + translation, }; let had_input_method = shell.input_method().is_enabled(); self.content.as_widget_mut().update( &mut tree.children[0], event, content, cursor, renderer, clipboard, shell, &Rectangle { y: bounds.y + translation.y, x: bounds.x + translation.x, ..bounds }, ); if !had_input_method && let InputMethod::Enabled { cursor, .. } = shell.input_method_mut() { *cursor = *cursor - translation; } }; if matches!( event, Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch( touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. } ) ) { state.interaction = Interaction::None; return; } if shell.is_event_captured() { return; } match event { Event::Mouse(mouse::Event::WheelScrolled { delta }) => { if cursor_over_scrollable.is_none() { return; } let delta = match *delta { mouse::ScrollDelta::Lines { x, y } => { let is_shift_pressed = state.keyboard_modifiers.shift(); // macOS automatically inverts the axes when Shift is pressed let (x, y) = if cfg!(target_os = "macos") && is_shift_pressed { (y, x) } else { (x, y) }; let movement = if !is_shift_pressed { Vector::new(x, y) } else { Vector::new(y, x) }; // TODO: Configurable speed/friction (?) -movement * 60.0 } mouse::ScrollDelta::Pixels { x, y } => -Vector::new(x, y), }; state.scroll(self.direction.align(delta), bounds, content_bounds); let has_scrolled = notify_scroll(state, &self.on_scroll, bounds, content_bounds, shell); let in_transaction = state.last_scrolled.is_some(); if has_scrolled || in_transaction { shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) if self.auto_scroll && matches!(state.interaction, Interaction::None) => { let Some(origin) = cursor_over_scrollable else { return; }; state.interaction = Interaction::AutoScrolling { origin, current: origin, last_frame: None, }; shell.capture_event(); shell.invalidate_layout(); shell.request_redraw(); } Event::Touch(event) if matches!(state.interaction, Interaction::TouchScrolling(_)) || (!mouse_over_y_scrollbar && !mouse_over_x_scrollbar) => { match event { touch::Event::FingerPressed { .. } => { let Some(position) = cursor_over_scrollable else { return; }; state.interaction = Interaction::TouchScrolling(position); } touch::Event::FingerMoved { .. } => { let Interaction::TouchScrolling(scroll_box_touched_at) = state.interaction else { return; }; let Some(cursor_position) = cursor.position() else { return; }; let delta = Vector::new( scroll_box_touched_at.x - cursor_position.x, scroll_box_touched_at.y - cursor_position.y, ); state.scroll(self.direction.align(delta), bounds, content_bounds); state.interaction = Interaction::TouchScrolling(cursor_position); // TODO: bubble up touch movements if not consumed. let _ = notify_scroll( state, &self.on_scroll, bounds, content_bounds, shell, ); } _ => {} } shell.capture_event(); } Event::Mouse(mouse::Event::CursorMoved { position }) => { if let Interaction::AutoScrolling { origin, last_frame, .. } = state.interaction { let delta = *position - origin; state.interaction = Interaction::AutoScrolling { origin, current: *position, last_frame, }; if (delta.x.abs() >= AUTOSCROLL_DEADZONE || delta.y.abs() >= AUTOSCROLL_DEADZONE) && last_frame.is_none() { shell.request_redraw(); } } } Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => { state.keyboard_modifiers = *modifiers; } Event::Window(window::Event::RedrawRequested(now)) => { if let Interaction::AutoScrolling { origin, current, last_frame, } = state.interaction { if last_frame == Some(*now) { shell.request_redraw(); return; } state.interaction = Interaction::AutoScrolling { origin, current, last_frame: None, }; let mut delta = current - origin; if delta.x.abs() < AUTOSCROLL_DEADZONE { delta.x = 0.0; } if delta.y.abs() < AUTOSCROLL_DEADZONE { delta.y = 0.0; } if delta.x != 0.0 || delta.y != 0.0 { let time_delta = if let Some(last_frame) = last_frame { *now - last_frame } else { Duration::ZERO };
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/svg.rs
widget/src/svg.rs
//! Svg widgets display vector graphics in your application. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::svg; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! svg("tiger.svg").into() //! } //! ``` use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::svg; use crate::core::widget::Tree; use crate::core::window; use crate::core::{ Clipboard, Color, ContentFit, Element, Event, Layout, Length, Point, Rectangle, Rotation, Shell, Size, Theme, Vector, Widget, }; use std::path::PathBuf; pub use crate::core::svg::Handle; /// A vector graphics image. /// /// An [`Svg`] image resizes smoothly without losing any quality. /// /// [`Svg`] images can have a considerable rendering cost when resized, /// specially when they are complex. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::svg; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// svg("tiger.svg").into() /// } /// ``` pub struct Svg<'a, Theme = crate::Theme> where Theme: Catalog, { handle: Handle, width: Length, height: Length, content_fit: ContentFit, class: Theme::Class<'a>, rotation: Rotation, opacity: f32, status: Option<Status>, } impl<'a, Theme> Svg<'a, Theme> where Theme: Catalog, { /// Creates a new [`Svg`] from the given [`Handle`]. pub fn new(handle: impl Into<Handle>) -> Self { Svg { handle: handle.into(), width: Length::Fill, height: Length::Shrink, content_fit: ContentFit::Contain, class: Theme::default(), rotation: Rotation::default(), opacity: 1.0, status: None, } } /// Creates a new [`Svg`] that will display the contents of the file at the /// provided path. #[must_use] pub fn from_path(path: impl Into<PathBuf>) -> Self { Self::new(Handle::from_path(path)) } /// Sets the width of the [`Svg`]. #[must_use] pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Svg`]. #[must_use] pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the [`ContentFit`] of the [`Svg`]. /// /// Defaults to [`ContentFit::Contain`] #[must_use] pub fn content_fit(self, content_fit: ContentFit) -> Self { Self { content_fit, ..self } } /// Sets the style of the [`Svg`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Svg`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } /// Applies the given [`Rotation`] to the [`Svg`]. pub fn rotation(mut self, rotation: impl Into<Rotation>) -> Self { self.rotation = rotation.into(); self } /// Sets the opacity of the [`Svg`]. /// /// It should be in the [0.0, 1.0] range—`0.0` meaning completely transparent, /// and `1.0` meaning completely opaque. pub fn opacity(mut self, opacity: impl Into<f32>) -> Self { self.opacity = opacity.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Svg<'_, Theme> where Renderer: svg::Renderer, Theme: Catalog, { 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 { // The raw w/h of the underlying image let Size { width, height } = renderer.measure_svg(&self.handle); let image_size = Size::new(width as f32, height as f32); // The rotated size of the svg let rotated_size = self.rotation.apply(image_size); // The size to be available to the widget prior to `Shrink`ing let raw_size = limits.resolve(self.width, self.height, rotated_size); // The uncropped size of the image when fit to the bounds above let full_size = self.content_fit.fit(rotated_size, raw_size); // Shrink the widget to fit the resized image, if requested let final_size = Size { width: match self.width { Length::Shrink => f32::min(raw_size.width, full_size.width), _ => raw_size.width, }, height: match self.height { Length::Shrink => f32::min(raw_size.height, full_size.height), _ => raw_size.height, }, }; layout::Node::new(final_size) } fn update( &mut self, _state: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, _renderer: &Renderer, _clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, _viewport: &Rectangle, ) { let current_status = if cursor.is_over(layout.bounds()) { Status::Hovered } else { Status::Idle }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.status = Some(current_status); } else if self.status.is_some_and(|status| status != current_status) { shell.request_redraw(); } } fn draw( &self, _state: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { let Size { width, height } = renderer.measure_svg(&self.handle); let image_size = Size::new(width as f32, height as f32); let rotated_size = self.rotation.apply(image_size); let bounds = layout.bounds(); let adjusted_fit = self.content_fit.fit(rotated_size, bounds.size()); let scale = Vector::new( adjusted_fit.width / rotated_size.width, adjusted_fit.height / rotated_size.height, ); let final_size = image_size * scale; let position = match self.content_fit { ContentFit::None => Point::new( bounds.x + (rotated_size.width - adjusted_fit.width) / 2.0, bounds.y + (rotated_size.height - adjusted_fit.height) / 2.0, ), _ => Point::new( bounds.center_x() - final_size.width / 2.0, bounds.center_y() - final_size.height / 2.0, ), }; let drawing_bounds = Rectangle::new(position, final_size); let style = theme.style(&self.class, self.status.unwrap_or(Status::Idle)); renderer.draw_svg( svg::Svg { handle: self.handle.clone(), color: style.color, rotation: self.rotation.radians(), opacity: self.opacity, }, drawing_bounds, bounds, ); } } impl<'a, Message, Theme, Renderer> From<Svg<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Theme: Catalog + 'a, Renderer: svg::Renderer + 'a, { fn from(icon: Svg<'a, Theme>) -> Element<'a, Message, Theme, Renderer> { Element::new(icon) } } /// The possible status of an [`Svg`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Svg`] is idle. Idle, /// The [`Svg`] is being hovered. Hovered, } /// The appearance of an [`Svg`]. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Style { /// The [`Color`] filter of an [`Svg`]. /// /// Useful for coloring a symbolic icon. /// /// `None` keeps the original color. pub color: Option<Color>, } /// The theme catalog of an [`Svg`]. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(|_theme, _status| Style::default()) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// A styling function for an [`Svg`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl<Theme> From<Style> for StyleFn<'_, Theme> { fn from(style: Style) -> Self { Box::new(move |_theme, _status| style) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/image.rs
widget/src/image.rs
//! Images display raster graphics in different formats (PNG, JPG, etc.). //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::image; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! image("ferris.png").into() //! } //! ``` //! <img src="https://github.com/iced-rs/iced/blob/9712b319bb7a32848001b96bd84977430f14b623/examples/resources/ferris.png?raw=true" width="300"> pub mod viewer; pub use viewer::Viewer; use crate::core::border; use crate::core::image; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::Tree; use crate::core::{ ContentFit, Element, Layout, Length, Point, Rectangle, Rotation, Size, Vector, Widget, }; pub use image::{FilterMethod, Handle}; /// Creates a new [`Viewer`] with the given image `Handle`. pub fn viewer<Handle>(handle: Handle) -> Viewer<Handle> { Viewer::new(handle) } /// A frame that displays an image while keeping aspect ratio. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::image; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// image("ferris.png").into() /// } /// ``` /// <img src="https://github.com/iced-rs/iced/blob/9712b319bb7a32848001b96bd84977430f14b623/examples/resources/ferris.png?raw=true" width="300"> pub struct Image<Handle = image::Handle> { handle: Handle, width: Length, height: Length, crop: Option<Rectangle<u32>>, border_radius: border::Radius, content_fit: ContentFit, filter_method: FilterMethod, rotation: Rotation, opacity: f32, scale: f32, expand: bool, } impl<Handle> Image<Handle> { /// Creates a new [`Image`] with the given path. pub fn new(handle: impl Into<Handle>) -> Self { Image { handle: handle.into(), width: Length::Shrink, height: Length::Shrink, crop: None, border_radius: border::Radius::default(), content_fit: ContentFit::default(), filter_method: FilterMethod::default(), rotation: Rotation::default(), opacity: 1.0, scale: 1.0, expand: false, } } /// Sets the width of the [`Image`] boundaries. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Image`] boundaries. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets whether the [`Image`] should try to fill as much space /// available as possible while keeping aspect ratio and without /// allocating extra space in any axis with a [`Length::Shrink`] /// sizing strategy. /// /// This is similar to using [`Length::Fill`] for both the /// [`width`](Self::width) and the [`height`](Self::height), /// but without the downside of blank space. pub fn expand(mut self, expand: bool) -> Self { self.expand = expand; self } /// Sets the [`ContentFit`] of the [`Image`]. /// /// Defaults to [`ContentFit::Contain`] pub fn content_fit(mut self, content_fit: ContentFit) -> Self { self.content_fit = content_fit; self } /// Sets the [`FilterMethod`] of the [`Image`]. pub fn filter_method(mut self, filter_method: FilterMethod) -> Self { self.filter_method = filter_method; self } /// Applies the given [`Rotation`] to the [`Image`]. pub fn rotation(mut self, rotation: impl Into<Rotation>) -> Self { self.rotation = rotation.into(); self } /// Sets the opacity of the [`Image`]. /// /// It should be in the [0.0, 1.0] range—`0.0` meaning completely transparent, /// and `1.0` meaning completely opaque. pub fn opacity(mut self, opacity: impl Into<f32>) -> Self { self.opacity = opacity.into(); self } /// Sets the scale of the [`Image`]. /// /// The region of the [`Image`] drawn will be scaled from the center by the given scale factor. /// This can be useful to create certain effects and animations, like smooth zoom in / out. pub fn scale(mut self, scale: impl Into<f32>) -> Self { self.scale = scale.into(); self } /// Crops the [`Image`] to the given region described by the [`Rectangle`] in absolute /// coordinates. /// /// Cropping is done before applying any transformation or [`ContentFit`]. In practice, /// this means that cropping an [`Image`] with this method should produce the same result /// as cropping it externally (e.g. with an image editor) and creating a new [`Handle`] /// for the cropped version. /// /// However, this method is much more efficient; since it just leverages scissoring during /// rendering and no image cropping actually takes place. Instead, it reuses the existing /// image allocations and should be as efficient as not cropping at all! /// /// The `region` coordinates will be clamped to the image dimensions, if necessary. pub fn crop(mut self, region: Rectangle<u32>) -> Self { self.crop = Some(region); self } /// Sets the [`border::Radius`] of the [`Image`]. /// /// Currently, it will only be applied around the rectangular bounding box /// of the [`Image`]. pub fn border_radius(mut self, border_radius: impl Into<border::Radius>) -> Self { self.border_radius = border_radius.into(); self } } /// Computes the layout of an [`Image`]. pub fn layout<Renderer, Handle>( renderer: &Renderer, limits: &layout::Limits, handle: &Handle, width: Length, height: Length, region: Option<Rectangle<u32>>, content_fit: ContentFit, rotation: Rotation, expand: bool, ) -> layout::Node where Renderer: image::Renderer<Handle = Handle>, { // The raw w/h of the underlying image let image_size = crop(renderer.measure_image(handle).unwrap_or_default(), region); // The rotated size of the image let rotated_size = rotation.apply(image_size); // The size to be available to the widget prior to `Shrink`ing let bounds = if expand { limits.width(width).height(height).max() } else { limits.resolve(width, height, rotated_size) }; // The uncropped size of the image when fit to the bounds above let full_size = content_fit.fit(rotated_size, bounds); // Shrink the widget to fit the resized image, if requested let final_size = Size { width: match width { Length::Shrink => f32::min(bounds.width, full_size.width), _ => bounds.width, }, height: match height { Length::Shrink => f32::min(bounds.height, full_size.height), _ => bounds.height, }, }; layout::Node::new(final_size) } fn drawing_bounds<Renderer, Handle>( renderer: &Renderer, bounds: Rectangle, handle: &Handle, region: Option<Rectangle<u32>>, content_fit: ContentFit, rotation: Rotation, scale: f32, ) -> Rectangle where Renderer: image::Renderer<Handle = Handle>, { let original_size = renderer.measure_image(handle).unwrap_or_default(); let image_size = crop(original_size, region); let rotated_size = rotation.apply(image_size); let adjusted_fit = content_fit.fit(rotated_size, bounds.size()); let fit_scale = Vector::new( adjusted_fit.width / rotated_size.width, adjusted_fit.height / rotated_size.height, ); let final_size = image_size * fit_scale * scale; let (crop_offset, final_size) = if let Some(region) = region { let x = region.x.min(original_size.width) as f32; let y = region.y.min(original_size.height) as f32; let width = image_size.width; let height = image_size.height; let ratio = Vector::new( original_size.width as f32 / width, original_size.height as f32 / height, ); let final_size = final_size * ratio; let scale = Vector::new( final_size.width / original_size.width as f32, final_size.height / original_size.height as f32, ); let offset = match content_fit { ContentFit::None => Vector::new(x * scale.x, y * scale.y), _ => Vector::new( ((original_size.width as f32 - width) / 2.0 - x) * scale.x, ((original_size.height as f32 - height) / 2.0 - y) * scale.y, ), }; (offset, final_size) } else { (Vector::ZERO, final_size) }; let position = match content_fit { ContentFit::None => Point::new( bounds.x + (rotated_size.width - adjusted_fit.width) / 2.0, bounds.y + (rotated_size.height - adjusted_fit.height) / 2.0, ), _ => Point::new( bounds.center_x() - final_size.width / 2.0, bounds.center_y() - final_size.height / 2.0, ), }; Rectangle::new(position + crop_offset, final_size) } fn crop(size: Size<u32>, region: Option<Rectangle<u32>>) -> Size<f32> { if let Some(region) = region { Size::new( region.width.min(size.width) as f32, region.height.min(size.height) as f32, ) } else { Size::new(size.width as f32, size.height as f32) } } /// Draws an [`Image`] pub fn draw<Renderer, Handle>( renderer: &mut Renderer, layout: Layout<'_>, handle: &Handle, crop: Option<Rectangle<u32>>, border_radius: border::Radius, content_fit: ContentFit, filter_method: FilterMethod, rotation: Rotation, opacity: f32, scale: f32, ) where Renderer: image::Renderer<Handle = Handle>, Handle: Clone, { let bounds = layout.bounds(); let drawing_bounds = drawing_bounds(renderer, bounds, handle, crop, content_fit, rotation, scale); renderer.draw_image( image::Image { handle: handle.clone(), border_radius, filter_method, rotation: rotation.radians(), opacity, snap: true, }, drawing_bounds, bounds, ); } impl<Message, Theme, Renderer, Handle> Widget<Message, Theme, Renderer> for Image<Handle> where Renderer: image::Renderer<Handle = Handle>, Handle: Clone, { 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( renderer, limits, &self.handle, self.width, self.height, self.crop, self.content_fit, self.rotation, self.expand, ) } fn draw( &self, _tree: &Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { draw( renderer, layout, &self.handle, self.crop, self.border_radius, self.content_fit, self.filter_method, self.rotation, self.opacity, self.scale, ); } } impl<'a, Message, Theme, Renderer, Handle> From<Image<Handle>> for Element<'a, Message, Theme, Renderer> where Renderer: image::Renderer<Handle = Handle>, Handle: Clone + 'a, { fn from(image: Image<Handle>) -> Element<'a, Message, Theme, Renderer> { Element::new(image) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/tooltip.rs
widget/src/tooltip.rs
//! Tooltips display a hint of information over some element when hovered. //! //! By default, the tooltip is displayed immediately, however, this can be adjusted //! with [`Tooltip::delay`]. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::{container, tooltip}; //! //! enum Message { //! // ... //! } //! //! fn view(_state: &State) -> Element<'_, Message> { //! tooltip( //! "Hover me to display the tooltip!", //! container("This is the tooltip contents!") //! .padding(10) //! .style(container::rounded_box), //! tooltip::Position::Bottom, //! ).into() //! } //! ``` use crate::container; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::text; use crate::core::time::{Duration, Instant}; use crate::core::widget::{self, Widget}; use crate::core::window; use crate::core::{ Clipboard, Element, Event, Length, Padding, Pixels, Point, Rectangle, Shell, Size, Vector, }; /// An element to display a widget over another. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{container, tooltip}; /// /// enum Message { /// // ... /// } /// /// fn view(_state: &State) -> Element<'_, Message> { /// tooltip( /// "Hover me to display the tooltip!", /// container("This is the tooltip contents!") /// .padding(10) /// .style(container::rounded_box), /// tooltip::Position::Bottom, /// ).into() /// } /// ``` pub struct Tooltip<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: container::Catalog, Renderer: text::Renderer, { content: Element<'a, Message, Theme, Renderer>, tooltip: Element<'a, Message, Theme, Renderer>, position: Position, gap: f32, padding: f32, snap_within_viewport: bool, delay: Duration, class: Theme::Class<'a>, } impl<'a, Message, Theme, Renderer> Tooltip<'a, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: text::Renderer, { /// The default padding of a [`Tooltip`] drawn by this renderer. const DEFAULT_PADDING: f32 = 5.0; /// Creates a new [`Tooltip`]. /// /// [`Tooltip`]: struct.Tooltip.html pub fn new( content: impl Into<Element<'a, Message, Theme, Renderer>>, tooltip: impl Into<Element<'a, Message, Theme, Renderer>>, position: Position, ) -> Self { Tooltip { content: content.into(), tooltip: tooltip.into(), position, gap: 0.0, padding: Self::DEFAULT_PADDING, snap_within_viewport: true, delay: Duration::ZERO, class: Theme::default(), } } /// Sets the gap between the content and its [`Tooltip`]. pub fn gap(mut self, gap: impl Into<Pixels>) -> Self { self.gap = gap.into().0; self } /// Sets the padding of the [`Tooltip`]. pub fn padding(mut self, padding: impl Into<Pixels>) -> Self { self.padding = padding.into().0; self } /// Sets the delay before the [`Tooltip`] is shown. /// /// Set to [`Duration::ZERO`] to be shown immediately. pub fn delay(mut self, delay: Duration) -> Self { self.delay = delay; self } /// Sets whether the [`Tooltip`] is snapped within the viewport. pub fn snap_within_viewport(mut self, snap: bool) -> Self { self.snap_within_viewport = snap; self } /// Sets the style of the [`Tooltip`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> container::Style + 'a) -> Self where Theme::Class<'a>: From<container::StyleFn<'a, Theme>>, { self.class = (Box::new(style) as container::StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Tooltip`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Tooltip<'_, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: text::Renderer, { fn children(&self) -> Vec<widget::Tree> { vec![ widget::Tree::new(&self.content), widget::Tree::new(&self.tooltip), ] } fn diff(&self, tree: &mut widget::Tree) { tree.diff_children(&[self.content.as_widget(), self.tooltip.as_widget()]); } fn state(&self) -> widget::tree::State { widget::tree::State::new(State::default()) } fn tag(&self) -> widget::tree::Tag { widget::tree::Tag::of::<State>() } fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn size_hint(&self) -> Size<Length> { self.content.as_widget().size_hint() } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.content .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) } fn update( &mut self, tree: &mut widget::Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { if let Event::Mouse(_) | Event::Window(window::Event::RedrawRequested(_)) = event { let state = tree.state.downcast_mut::<State>(); let now = Instant::now(); let cursor_position = cursor.position_over(layout.bounds()); match (*state, cursor_position) { (State::Idle, Some(cursor_position)) => { if self.delay == Duration::ZERO { *state = State::Open { cursor_position }; shell.invalidate_layout(); } else { *state = State::Hovered { at: now }; } shell.request_redraw_at(now + self.delay); } (State::Hovered { .. }, None) => { *state = State::Idle; } (State::Hovered { at, .. }, _) if at.elapsed() < self.delay => { shell.request_redraw_at(now + self.delay - at.elapsed()); } (State::Hovered { .. }, Some(cursor_position)) => { *state = State::Open { cursor_position }; shell.invalidate_layout(); } ( State::Open { cursor_position: last_position, }, Some(cursor_position), ) if self.position == Position::FollowCursor && last_position != cursor_position => { *state = State::Open { cursor_position }; shell.request_redraw(); } (State::Open { .. }, None) => { *state = State::Idle; shell.invalidate_layout(); if !matches!(event, Event::Window(window::Event::RedrawRequested(_)),) { shell.request_redraw(); } } (State::Open { .. }, Some(_)) | (State::Idle, None) => (), } } self.content.as_widget_mut().update( &mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn mouse_interaction( &self, tree: &widget::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 draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, inherited_style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.content.as_widget().draw( &tree.children[0], renderer, theme, inherited_style, layout, cursor, viewport, ); } fn overlay<'b>( &'b mut self, tree: &'b mut widget::Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { let state = tree.state.downcast_ref::<State>(); let mut children = tree.children.iter_mut(); let content = self.content.as_widget_mut().overlay( children.next().unwrap(), layout, renderer, viewport, translation, ); let tooltip = if let State::Open { cursor_position } = *state { Some(overlay::Element::new(Box::new(Overlay { position: layout.position() + translation, tooltip: &mut self.tooltip, tree: children.next().unwrap(), cursor_position, content_bounds: layout.bounds(), snap_within_viewport: self.snap_within_viewport, positioning: self.position, gap: self.gap, padding: self.padding, class: &self.class, }))) } else { None }; if content.is_some() || tooltip.is_some() { Some( overlay::Group::with_children(content.into_iter().chain(tooltip).collect()) .overlay(), ) } else { None } } fn operate( &mut self, tree: &mut widget::Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { operation.container(None, layout.bounds()); operation.traverse(&mut |operation| { self.content.as_widget_mut().operate( &mut tree.children[0], layout, renderer, operation, ); }); } } impl<'a, Message, Theme, Renderer> From<Tooltip<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: container::Catalog + 'a, Renderer: text::Renderer + 'a, { fn from( tooltip: Tooltip<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(tooltip) } } /// The position of the tooltip. Defaults to following the cursor. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Position { /// The tooltip will appear on the top of the widget. #[default] Top, /// The tooltip will appear on the bottom of the widget. Bottom, /// The tooltip will appear on the left of the widget. Left, /// The tooltip will appear on the right of the widget. Right, /// The tooltip will follow the cursor. FollowCursor, } #[derive(Debug, Clone, Copy, PartialEq, Default)] enum State { #[default] Idle, Hovered { at: Instant, }, Open { cursor_position: Point, }, } struct Overlay<'a, 'b, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: text::Renderer, { position: Point, tooltip: &'b mut Element<'a, Message, Theme, Renderer>, tree: &'b mut widget::Tree, cursor_position: Point, content_bounds: Rectangle, snap_within_viewport: bool, positioning: Position, gap: f32, padding: f32, class: &'b Theme::Class<'a>, } impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer> for Overlay<'_, '_, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: text::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { let viewport = Rectangle::with_size(bounds); let tooltip_layout = self.tooltip.as_widget_mut().layout( self.tree, renderer, &layout::Limits::new( Size::ZERO, if self.snap_within_viewport { viewport.size() } else { Size::INFINITE }, ) .shrink(Padding::new(self.padding)), ); let text_bounds = tooltip_layout.bounds(); let x_center = self.position.x + (self.content_bounds.width - text_bounds.width) / 2.0; let y_center = self.position.y + (self.content_bounds.height - text_bounds.height) / 2.0; let mut tooltip_bounds = { let offset = match self.positioning { Position::Top => Vector::new( x_center, self.position.y - text_bounds.height - self.gap - self.padding, ), Position::Bottom => Vector::new( x_center, self.position.y + self.content_bounds.height + self.gap + self.padding, ), Position::Left => Vector::new( self.position.x - text_bounds.width - self.gap - self.padding, y_center, ), Position::Right => Vector::new( self.position.x + self.content_bounds.width + self.gap + self.padding, y_center, ), Position::FollowCursor => { let translation = self.position - self.content_bounds.position(); Vector::new( self.cursor_position.x, self.cursor_position.y - text_bounds.height, ) + translation } }; Rectangle { x: offset.x - self.padding, y: offset.y - self.padding, width: text_bounds.width + self.padding * 2.0, height: text_bounds.height + self.padding * 2.0, } }; if self.snap_within_viewport { if tooltip_bounds.x < viewport.x { tooltip_bounds.x = viewport.x; } else if viewport.x + viewport.width < tooltip_bounds.x + tooltip_bounds.width { tooltip_bounds.x = viewport.x + viewport.width - tooltip_bounds.width; } if tooltip_bounds.y < viewport.y { tooltip_bounds.y = viewport.y; } else if viewport.y + viewport.height < tooltip_bounds.y + tooltip_bounds.height { tooltip_bounds.y = viewport.y + viewport.height - tooltip_bounds.height; } } layout::Node::with_children( tooltip_bounds.size(), vec![tooltip_layout.translate(Vector::new(self.padding, self.padding))], ) .translate(Vector::new(tooltip_bounds.x, tooltip_bounds.y)) } fn draw( &self, renderer: &mut Renderer, theme: &Theme, inherited_style: &renderer::Style, layout: Layout<'_>, cursor_position: mouse::Cursor, ) { let style = theme.style(self.class); container::draw_background(renderer, &style, layout.bounds()); let defaults = renderer::Style { text_color: style.text_color.unwrap_or(inherited_style.text_color), }; self.tooltip.as_widget().draw( self.tree, renderer, theme, &defaults, layout.children().next().unwrap(), cursor_position, &Rectangle::with_size(Size::INFINITE), ); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/column.rs
widget/src/column.rs
//! Distribute content vertically. use crate::core::alignment::{self, Alignment}; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents vertically. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{button, column}; /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// column![ /// "I am on top!", /// button("I am in the center!"), /// "I am below.", /// ].into() /// } /// ``` pub struct Column<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { spacing: f32, padding: Padding, width: Length, height: Length, max_width: f32, align: Alignment, clip: bool, children: Vec<Element<'a, Message, Theme, Renderer>>, } impl<'a, Message, Theme, Renderer> Column<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Creates an empty [`Column`]. pub fn new() -> Self { Self::from_vec(Vec::new()) } /// Creates a [`Column`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { Self::from_vec(Vec::with_capacity(capacity)) } /// Creates a [`Column`] with the given elements. pub fn with_children( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { let iterator = children.into_iter(); Self::with_capacity(iterator.size_hint().0).extend(iterator) } /// Creates a [`Column`] from an already allocated [`Vec`]. /// /// Keep in mind that the [`Column`] will not inspect the [`Vec`], which means /// it won't automatically adapt to the sizing strategy of its contents. /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Column::width`] or [`Column::height`] accordingly. pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, width: Length::Shrink, height: Length::Shrink, max_width: f32::INFINITY, align: Alignment::Start, clip: false, children, } } /// Sets the vertical spacing _between_ elements. /// /// Custom margins per element do not exist in iced. You should use this /// method instead! While less flexible, it helps you keep spacing between /// elements consistent. pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self { self.spacing = amount.into().0; self } /// Sets the [`Padding`] of the [`Column`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the width of the [`Column`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Column`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the maximum width of the [`Column`]. pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self { self.max_width = max_width.into().0; self } /// Sets the horizontal alignment of the contents of the [`Column`] . pub fn align_x(mut self, align: impl Into<alignment::Horizontal>) -> Self { self.align = Alignment::from(align.into()); self } /// Sets whether the contents of the [`Column`] should be clipped on /// overflow. pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// Adds an element to the [`Column`]. pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); if !child_size.is_void() { self.width = self.width.enclose(child_size.width); self.height = self.height.enclose(child_size.height); self.children.push(child); } self } /// Extends the [`Column`] with the given children. pub fn extend( self, children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { children.into_iter().fold(self, Self::push) } /// Turns the [`Column`] into a [`Wrapping`] column. /// /// The original alignment of the [`Column`] is preserved per column wrapped. pub fn wrap(self) -> Wrapping<'a, Message, Theme, Renderer> { Wrapping { column: self, horizontal_spacing: None, align_y: alignment::Vertical::Top, } } } impl<Message, Renderer> Default for Column<'_, Message, Renderer> where Renderer: crate::core::Renderer, { fn default() -> Self { Self::new() } } impl<'a, Message, Theme, Renderer: crate::core::Renderer> FromIterator<Element<'a, Message, Theme, Renderer>> for Column<'a, Message, Theme, Renderer> { fn from_iter<T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>>(iter: T) -> Self { Self::with_children(iter) } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Column<'_, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.children.iter().map(Tree::new).collect() } fn diff(&self, tree: &mut Tree) { tree.diff_children(&self.children); } 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 { let limits = limits.max_width(self.max_width); layout::flex::resolve( layout::flex::Axis::Vertical, renderer, &limits, self.width, self.height, self.padding, self.spacing, self.align, &mut self.children, &mut tree.children, ) } 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.children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, 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, ) { for ((child, tree), layout) in self .children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { child.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .zip(&tree.children) .zip(layout.children()) .map(|((child, tree), layout)| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if let Some(clipped_viewport) = layout.bounds().intersection(viewport) { let viewport = if self.clip { &clipped_viewport } else { viewport }; for ((child, tree), layout) in self .children .iter() .zip(&tree.children) .zip(layout.children()) .filter(|(_, layout)| layout.bounds().intersects(viewport)) { child .as_widget() .draw(tree, renderer, theme, style, layout, cursor, viewport); } } } 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>> { overlay::from_children( &mut self.children, tree, layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Column<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(column: Column<'a, Message, Theme, Renderer>) -> Self { Self::new(column) } } /// A [`Column`] that wraps its contents. /// /// Create a [`Column`] first, and then call [`Column::wrap`] to /// obtain a [`Column`] that wraps its contents. /// /// The original alignment of the [`Column`] is preserved per column wrapped. #[allow(missing_debug_implementations)] pub struct Wrapping<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { column: Column<'a, Message, Theme, Renderer>, horizontal_spacing: Option<f32>, align_y: alignment::Vertical, } impl<Message, Theme, Renderer> Wrapping<'_, Message, Theme, Renderer> { /// Sets the horizontal spacing _between_ columns. pub fn horizontal_spacing(mut self, amount: impl Into<Pixels>) -> Self { self.horizontal_spacing = Some(amount.into().0); self } /// Sets the vertical alignment of the wrapping [`Column`]. pub fn align_x(mut self, align_y: impl Into<alignment::Vertical>) -> Self { self.align_y = align_y.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Wrapping<'_, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.column.children() } fn diff(&self, tree: &mut Tree) { self.column.diff(tree); } fn size(&self) -> Size<Length> { self.column.size() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let limits = limits .width(self.column.width) .height(self.column.height) .shrink(self.column.padding); let child_limits = limits.loose(); let spacing = self.column.spacing; let horizontal_spacing = self.horizontal_spacing.unwrap_or(spacing); let max_height = limits.max().height; let mut children: Vec<layout::Node> = Vec::new(); let mut intrinsic_size = Size::ZERO; let mut column_start = 0; let mut column_width = 0.0; let mut x = 0.0; let mut y = 0.0; let align_factor = match self.column.align { Alignment::Start => 0.0, Alignment::Center => 2.0, Alignment::End => 1.0, }; let align_x = |column_start: std::ops::Range<usize>, column_width: f32, children: &mut Vec<layout::Node>| { if align_factor != 0.0 { for node in &mut children[column_start] { let width = node.size().width; node.translate_mut(Vector::new((column_width - width) / align_factor, 0.0)); } } }; for (i, child) in self.column.children.iter_mut().enumerate() { let node = child .as_widget_mut() .layout(&mut tree.children[i], renderer, &child_limits); let child_size = node.size(); if y != 0.0 && y + child_size.height > max_height { intrinsic_size.height = intrinsic_size.height.max(y - spacing); align_x(column_start..i, column_width, &mut children); x += column_width + horizontal_spacing; y = 0.0; column_start = i; column_width = 0.0; } column_width = column_width.max(child_size.width); children .push(node.move_to((x + self.column.padding.left, y + self.column.padding.top))); y += child_size.height + spacing; } if y != 0.0 { intrinsic_size.height = intrinsic_size.height.max(y - spacing); } intrinsic_size.width = x + column_width; align_x(column_start..children.len(), column_width, &mut children); let align_factor = match self.align_y { alignment::Vertical::Top => 0.0, alignment::Vertical::Center => 2.0, alignment::Vertical::Bottom => 1.0, }; if align_factor != 0.0 { let total_height = intrinsic_size.height; let mut column_start = 0; for i in 0..children.len() { let bounds = children[i].bounds(); let column_height = bounds.y + bounds.height; let next_y = children .get(i + 1) .map(|node| node.bounds().y) .unwrap_or_default(); if next_y == 0.0 { let translation = Vector::new(0.0, (total_height - column_height) / align_factor); for node in &mut children[column_start..=i] { node.translate_mut(translation); } column_start = i + 1; } } } let size = limits.resolve(self.column.width, self.column.height, intrinsic_size); layout::Node::with_children(size.expand(self.column.padding), children) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { self.column.operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { self.column.update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.column .mouse_interaction(tree, layout, cursor, viewport, renderer) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.column .draw(tree, renderer, theme, style, layout, cursor, viewport); } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.column .overlay(tree, layout, renderer, viewport, translation) } } impl<'a, Message, Theme, Renderer> From<Wrapping<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(column: Wrapping<'a, Message, Theme, Renderer>) -> Self { Self::new(column) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/helpers.rs
widget/src/helpers.rs
//! Helper functions to create pure widgets. use crate::button::{self, Button}; use crate::checkbox::{self, Checkbox}; use crate::combo_box::{self, ComboBox}; use crate::container::{self, Container}; use crate::core; use crate::core::theme; use crate::core::widget::operation::{self, Operation}; use crate::core::window; use crate::core::{Element, Length, Size, Widget}; use crate::float::{self, Float}; use crate::keyed; use crate::overlay; use crate::pane_grid::{self, PaneGrid}; use crate::pick_list::{self, PickList}; use crate::progress_bar::{self, ProgressBar}; use crate::radio::{self, Radio}; use crate::scrollable::{self, Scrollable}; use crate::slider::{self, Slider}; use crate::text::{self, Text}; use crate::text_editor::{self, TextEditor}; use crate::text_input::{self, TextInput}; use crate::toggler::{self, Toggler}; use crate::tooltip::{self, Tooltip}; use crate::vertical_slider::{self, VerticalSlider}; use crate::{Column, Grid, MouseArea, Pin, Responsive, Row, Sensor, Space, Stack, Themer}; use std::borrow::Borrow; use std::ops::RangeInclusive; pub use crate::table::table; /// Creates a [`Column`] with the given children. /// /// Columns distribute their children vertically. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{button, column}; /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// column![ /// "I am on top!", /// button("I am in the center!"), /// "I am below.", /// ].into() /// } /// ``` #[macro_export] macro_rules! column { () => ( $crate::Column::new() ); ($($x:expr),+ $(,)?) => ( $crate::Column::with_children([$($crate::core::Element::from($x)),+]) ); } /// Creates a [`Row`] with the given children. /// /// Rows distribute their children horizontally. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{button, row}; /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// row![ /// "I am to the left!", /// button("I am in the middle!"), /// "I am to the right!", /// ].into() /// } /// ``` #[macro_export] macro_rules! row { () => ( $crate::Row::new() ); ($($x:expr),+ $(,)?) => ( $crate::Row::with_children([$($crate::core::Element::from($x)),+]) ); } /// Creates a [`Stack`] with the given children. /// /// [`Stack`]: crate::Stack #[macro_export] macro_rules! stack { () => ( $crate::Stack::new() ); ($($x:expr),+ $(,)?) => ( $crate::Stack::with_children([$($crate::core::Element::from($x)),+]) ); } /// Creates a [`Grid`] with the given children. /// /// [`Grid`]: crate::Grid #[macro_export] macro_rules! grid { () => ( $crate::Grid::new() ); ($($x:expr),+ $(,)?) => ( $crate::Grid::with_children([$($crate::core::Element::from($x)),+]) ); } /// Creates a new [`Text`] widget with the provided content. /// /// [`Text`]: core::widget::Text /// /// This macro uses the same syntax as [`format!`], but creates a new [`Text`] widget instead. /// /// See [the formatting documentation in `std::fmt`](std::fmt) /// for details of the macro argument syntax. /// /// # Examples /// /// ```no_run /// # mod iced { /// # pub mod widget { /// # macro_rules! text { /// # ($($arg:tt)*) => {unimplemented!()} /// # } /// # pub(crate) use text; /// # } /// # } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::core::Theme, ()>; /// use iced::widget::text; /// /// enum Message { /// // ... /// } /// /// fn view(_state: &State) -> Element<Message> { /// let simple = text!("Hello, world!"); /// /// let keyword = text!("Hello, {}", "world!"); /// /// let planet = "Earth"; /// let local_variable = text!("Hello, {planet}!"); /// // ... /// # unimplemented!() /// } /// ``` #[macro_export] macro_rules! text { ($($arg:tt)*) => { $crate::Text::new(format!($($arg)*)) }; } /// Creates some [`Rich`] text with the given spans. /// /// [`Rich`]: text::Rich /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::*; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::font; /// use iced::widget::{rich_text, span}; /// use iced::{color, never, Font}; /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// rich_text![ /// span("I am red!").color(color!(0xff0000)), /// span(" "), /// span("And I am bold!").font(Font { weight: font::Weight::Bold, ..Font::default() }), /// ] /// .on_link_click(never) /// .size(20) /// .into() /// } /// ``` #[macro_export] macro_rules! rich_text { () => ( $crate::text::Rich::new() ); ($($x:expr),+ $(,)?) => ( $crate::text::Rich::from_iter([$($crate::text::Span::from($x)),+]) ); } /// Creates a new [`Container`] with the provided content. /// /// Containers let you align a widget inside their boundaries. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::container; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// container("This text is centered inside a rounded box!") /// .padding(10) /// .center(800) /// .style(container::rounded_box) /// .into() /// } /// ``` pub fn container<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { Container::new(content) } /// Creates a new [`Container`] that fills all the available space /// and centers its contents inside. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let center = container("Center!").center(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn center<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content).center(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// horizontally and centers its contents inside. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let center_x = container("Horizontal Center!").center_x(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn center_x<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content).center_x(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// vertically and centers its contents inside. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let center_y = container("Vertical Center!").center_y(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn center_y<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content).center_y(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// horizontally and right-aligns its contents inside. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let right = container("Right!").align_right(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn right<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content).align_right(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// and aligns its contents inside to the right center. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let right_center = container("Bottom Center!").align_right(Fill).center_y(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn right_center<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content) .align_right(Length::Fill) .center_y(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// vertically and bottom-aligns its contents inside. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let bottom = container("Bottom!").align_bottom(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn bottom<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content).align_bottom(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// and aligns its contents inside to the bottom center. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let bottom_center = container("Bottom Center!").center_x(Fill).align_bottom(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn bottom_center<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content) .center_x(Length::Fill) .align_bottom(Length::Fill) } /// Creates a new [`Container`] that fills all the available space /// and aligns its contents inside to the bottom right corner. /// /// This is equivalent to: /// ```rust,no_run /// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } /// let bottom_right = container("Bottom!").align_right(Fill).align_bottom(Fill); /// ``` /// /// [`Container`]: crate::Container pub fn bottom_right<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Container<'a, Message, Theme, Renderer> where Theme: container::Catalog + 'a, Renderer: core::Renderer, { container(content) .align_right(Length::Fill) .align_bottom(Length::Fill) } /// Creates a new [`Pin`] widget with the given content. /// /// A [`Pin`] widget positions its contents at some fixed coordinates inside of its boundaries. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::Length::Fill; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::pin; /// use iced::Fill; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// pin("This text is displayed at coordinates (50, 50)!") /// .x(50) /// .y(50) /// .into() /// } /// ``` pub fn pin<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Pin<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { Pin::new(content) } /// Creates a new [`Column`] with the given children. /// /// Columns distribute their children vertically. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{column, text}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// column((0..5).map(|i| text!("Item {i}").into())).into() /// } /// ``` pub fn column<'a, Message, Theme, Renderer>( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Column<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { Column::with_children(children) } /// Creates a new [`keyed::Column`] from an iterator of elements. /// /// Keyed columns distribute content vertically while keeping continuity. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{keyed_column, text}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// keyed_column((0..=100).map(|i| { /// (i, text!("Item {i}").into()) /// })).into() /// } /// ``` pub fn keyed_column<'a, Key, Message, Theme, Renderer>( children: impl IntoIterator<Item = (Key, Element<'a, Message, Theme, Renderer>)>, ) -> keyed::Column<'a, Key, Message, Theme, Renderer> where Key: Copy + PartialEq, Renderer: core::Renderer, { keyed::Column::with_children(children) } /// Creates a new [`Row`] from an iterator. /// /// Rows distribute their children horizontally. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{row, text}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// row((0..5).map(|i| text!("Item {i}").into())).into() /// } /// ``` pub fn row<'a, Message, Theme, Renderer>( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Row<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { Row::with_children(children) } /// Creates a new [`Grid`] from an iterator. pub fn grid<'a, Message, Theme, Renderer>( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Grid<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { Grid::with_children(children) } /// Creates a new [`Stack`] with the given children. /// /// [`Stack`]: crate::Stack pub fn stack<'a, Message, Theme, Renderer>( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Stack<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { Stack::with_children(children) } /// Wraps the given widget and captures any mouse button presses inside the bounds of /// the widget—effectively making it _opaque_. /// /// This helper is meant to be used to mark elements in a [`Stack`] to avoid mouse /// events from passing through layers. /// /// [`Stack`]: crate::Stack pub fn opaque<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::{Event, Rectangle, Shell, Size}; struct Opaque<'a, Message, Theme, Renderer> { content: Element<'a, Message, Theme, Renderer>, } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Opaque<'_, Message, Theme, Renderer> where Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { self.content.as_widget().tag() } fn state(&self) -> tree::State { self.content.as_widget().state() } fn children(&self) -> Vec<Tree> { self.content.as_widget().children() } fn diff(&self, tree: &mut Tree) { self.content.as_widget().diff(tree); } fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn size_hint(&self) -> Size<Length> { self.content.as_widget().size_hint() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.content.as_widget_mut().layout(tree, renderer, limits) } 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, renderer, theme, style, layout, cursor, viewport); } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn operation::Operation, ) { self.content .as_widget_mut() .operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn core::Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { let is_mouse_press = matches!(event, core::Event::Mouse(mouse::Event::ButtonPressed(_))); self.content.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); if is_mouse_press && cursor.is_over(layout.bounds()) { shell.capture_event(); } } fn mouse_interaction( &self, state: &core::widget::Tree, layout: core::Layout<'_>, cursor: core::mouse::Cursor, viewport: &core::Rectangle, renderer: &Renderer, ) -> core::mouse::Interaction { let interaction = self .content .as_widget() .mouse_interaction(state, layout, cursor, viewport, renderer); if interaction == mouse::Interaction::None && cursor.is_over(layout.bounds()) { mouse::Interaction::Idle } else { interaction } } fn overlay<'b>( &'b mut self, state: &'b mut core::widget::Tree, layout: core::Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, ) -> Option<core::overlay::Element<'b, Message, Theme, Renderer>> { self.content .as_widget_mut() .overlay(state, layout, renderer, viewport, translation) } } Element::new(Opaque { content: content.into(), }) } /// Displays a widget on top of another one, only when the base widget is hovered. /// /// This works analogously to a [`stack`], but it will only display the layer on top /// when the cursor is over the base. It can be useful for removing visual clutter. /// /// [`stack`]: stack() pub fn hover<'a, Message, Theme, Renderer>( base: impl Into<Element<'a, Message, Theme, Renderer>>, top: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::{Event, Rectangle, Shell, Size}; struct Hover<'a, Message, Theme, Renderer> { base: Element<'a, Message, Theme, Renderer>, top: Element<'a, Message, Theme, Renderer>, is_top_focused: bool, is_top_overlay_active: bool, is_hovered: bool, } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Hover<'_, Message, Theme, Renderer> where Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { struct Tag; tree::Tag::of::<Tag>() } fn children(&self) -> Vec<Tree> { vec![Tree::new(&self.base), Tree::new(&self.top)] } fn diff(&self, tree: &mut Tree) { tree.diff_children(&[&self.base, &self.top]); } fn size(&self) -> Size<Length> { self.base.as_widget().size() } fn size_hint(&self) -> Size<Length> { self.base.as_widget().size_hint() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let base = self .base .as_widget_mut() .layout(&mut tree.children[0], renderer, limits); let top = self.top.as_widget_mut().layout( &mut tree.children[1], renderer, &layout::Limits::new(Size::ZERO, base.size()), ); layout::Node::with_children(base.size(), vec![base, top]) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if let Some(bounds) = layout.bounds().intersection(viewport) { let mut children = layout.children().zip(&tree.children); let (base_layout, base_tree) = children.next().unwrap(); self.base.as_widget().draw( base_tree, renderer, theme, style, base_layout, cursor, viewport, ); if cursor.is_over(layout.bounds()) || self.is_top_focused || self.is_top_overlay_active { let (top_layout, top_tree) = children.next().unwrap(); renderer.with_layer(bounds, |renderer| { self.top.as_widget().draw( top_tree, renderer, theme, style, top_layout, cursor, viewport, ); }); } } } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn operation::Operation, ) { let children = [&mut self.base, &mut self.top] .into_iter() .zip(layout.children().zip(&mut tree.children)); for (child, (layout, tree)) in children { child .as_widget_mut() .operate(tree, layout, renderer, operation); } } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn core::Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { let mut children = layout.children().zip(&mut tree.children); let (base_layout, base_tree) = children.next().unwrap(); let (top_layout, top_tree) = children.next().unwrap(); let is_hovered = cursor.is_over(layout.bounds()); if matches!(event, Event::Window(window::Event::RedrawRequested(_))) { let mut count_focused = operation::focusable::count(); self.top.as_widget_mut().operate( top_tree, top_layout, renderer, &mut operation::black_box(&mut count_focused), ); self.is_top_focused = match count_focused.finish() { operation::Outcome::Some(count) => count.focused.is_some(), _ => false, }; self.is_hovered = is_hovered; } else if is_hovered != self.is_hovered { shell.request_redraw(); } let is_visible = is_hovered || self.is_top_focused || self.is_top_overlay_active; if matches!( event, Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::ButtonReleased(_)) ) || is_visible { let redraw_request = shell.redraw_request(); self.top.as_widget_mut().update( top_tree, event, top_layout, cursor, renderer, clipboard, shell, viewport, ); // Ignore redraw requests of invisible content if !is_visible { Shell::replace_redraw_request(shell, redraw_request); } if shell.is_event_captured() { return; } }; self.base.as_widget_mut().update( base_tree, event, base_layout, cursor, renderer, clipboard, shell, viewport, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { [&self.base, &self.top] .into_iter() .rev() .zip(layout.children().rev().zip(tree.children.iter().rev())) .map(|(child, (layout, tree))| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .find(|&interaction| interaction != mouse::Interaction::None) .unwrap_or_default() } fn overlay<'b>( &'b mut self, tree: &'b mut core::widget::Tree, layout: core::Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, ) -> Option<core::overlay::Element<'b, Message, Theme, Renderer>> { let mut overlays = [&mut self.base, &mut self.top] .into_iter() .zip(layout.children().zip(tree.children.iter_mut())) .map(|(child, (layout, tree))| { child .as_widget_mut() .overlay(tree, layout, renderer, viewport, translation) }); if let Some(base_overlay) = overlays.next()? { return Some(base_overlay); } let top_overlay = overlays.next()?; self.is_top_overlay_active = top_overlay.is_some(); top_overlay } } Element::new(Hover { base: base.into(), top: top.into(), is_top_focused: false, is_top_overlay_active: false, is_hovered: false, }) } /// Creates a new [`Sensor`] widget. /// /// A [`Sensor`] widget can generate messages when its contents are shown, /// hidden, or resized. /// /// It can even notify you with anticipation at a given distance! pub fn sensor<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Sensor<'a, (), Message, Theme, Renderer> where Renderer: core::Renderer, { Sensor::new(content) } /// Creates a new [`Scrollable`] with the provided content. /// /// Scrollables let users navigate an endless amount of content with a scrollbar. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{column, scrollable, space}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// scrollable(column![ /// "Scroll me!", /// space().height(3000), /// "You did it!", /// ]).into() /// } /// ``` pub fn scrollable<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Scrollable<'a, Message, Theme, Renderer> where Theme: scrollable::Catalog + 'a, Renderer: core::text::Renderer, { Scrollable::new(content) } /// Creates a new [`Button`] with the provided content. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::button; /// /// #[derive(Clone)] /// enum Message { /// ButtonPressed, /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// button("Press me!").on_press(Message::ButtonPressed).into() /// } /// ``` pub fn button<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Button<'a, Message, Theme, Renderer> where Theme: button::Catalog + 'a, Renderer: core::Renderer, { Button::new(content) } /// Creates a new [`Tooltip`] for the provided content with the given /// [`Element`] and [`tooltip::Position`]. /// /// Tooltips display a hint of information over some element when hovered. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{container, tooltip}; /// /// enum Message { /// // ... /// } /// /// fn view(_state: &State) -> Element<'_, Message> { /// tooltip( /// "Hover me to display the tooltip!", /// container("This is the tooltip contents!") /// .padding(10) /// .style(container::rounded_box), /// tooltip::Position::Bottom, /// ).into() /// } /// ``` pub fn tooltip<'a, Message, Theme, Renderer>( content: impl Into<Element<'a, Message, Theme, Renderer>>,
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/row.rs
widget/src/row.rs
//! Distribute content horizontally. use crate::core::alignment::{self, Alignment}; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ Clipboard, Element, Event, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents horizontally. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{button, row}; /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// row![ /// "I am to the left!", /// button("I am in the middle!"), /// "I am to the right!", /// ].into() /// } /// ``` pub struct Row<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { spacing: f32, padding: Padding, width: Length, height: Length, align: Alignment, clip: bool, children: Vec<Element<'a, Message, Theme, Renderer>>, } impl<'a, Message, Theme, Renderer> Row<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Creates an empty [`Row`]. pub fn new() -> Self { Self::from_vec(Vec::new()) } /// Creates a [`Row`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { Self::from_vec(Vec::with_capacity(capacity)) } /// Creates a [`Row`] with the given elements. pub fn with_children( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { let iterator = children.into_iter(); Self::with_capacity(iterator.size_hint().0).extend(iterator) } /// Creates a [`Row`] from an already allocated [`Vec`]. /// /// Keep in mind that the [`Row`] will not inspect the [`Vec`], which means /// it won't automatically adapt to the sizing strategy of its contents. /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Row::width`] or [`Row::height`] accordingly. pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, width: Length::Shrink, height: Length::Shrink, align: Alignment::Start, clip: false, children, } } /// Sets the horizontal spacing _between_ elements. /// /// Custom margins per element do not exist in iced. You should use this /// method instead! While less flexible, it helps you keep spacing between /// elements consistent. pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self { self.spacing = amount.into().0; self } /// Sets the [`Padding`] of the [`Row`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the width of the [`Row`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Row`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the vertical alignment of the contents of the [`Row`] . pub fn align_y(mut self, align: impl Into<alignment::Vertical>) -> Self { self.align = Alignment::from(align.into()); self } /// Sets whether the contents of the [`Row`] should be clipped on /// overflow. pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// Adds an [`Element`] to the [`Row`]. pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); if !child_size.is_void() { self.width = self.width.enclose(child_size.width); self.height = self.height.enclose(child_size.height); self.children.push(child); } self } /// Extends the [`Row`] with the given children. pub fn extend( self, children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { children.into_iter().fold(self, Self::push) } /// Turns the [`Row`] into a [`Wrapping`] row. /// /// The original alignment of the [`Row`] is preserved per row wrapped. pub fn wrap(self) -> Wrapping<'a, Message, Theme, Renderer> { Wrapping { row: self, vertical_spacing: None, align_x: alignment::Horizontal::Left, } } } impl<Message, Renderer> Default for Row<'_, Message, Renderer> where Renderer: crate::core::Renderer, { fn default() -> Self { Self::new() } } impl<'a, Message, Theme, Renderer: crate::core::Renderer> FromIterator<Element<'a, Message, Theme, Renderer>> for Row<'a, Message, Theme, Renderer> { fn from_iter<T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>>(iter: T) -> Self { Self::with_children(iter) } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Row<'_, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.children.iter().map(Tree::new).collect() } fn diff(&self, tree: &mut Tree) { tree.diff_children(&self.children); } 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::flex::resolve( layout::flex::Axis::Horizontal, renderer, limits, self.width, self.height, self.padding, self.spacing, self.align, &mut self.children, &mut tree.children, ) } 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.children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, 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, ) { for ((child, tree), layout) in self .children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { child.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .zip(&tree.children) .zip(layout.children()) .map(|((child, tree), layout)| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if let Some(clipped_viewport) = layout.bounds().intersection(viewport) { let viewport = if self.clip { &clipped_viewport } else { viewport }; for ((child, tree), layout) in self .children .iter() .zip(&tree.children) .zip(layout.children()) .filter(|(_, layout)| layout.bounds().intersects(viewport)) { child .as_widget() .draw(tree, renderer, theme, style, layout, cursor, viewport); } } } 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>> { overlay::from_children( &mut self.children, tree, layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Row<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(row: Row<'a, Message, Theme, Renderer>) -> Self { Self::new(row) } } /// A [`Row`] that wraps its contents. /// /// Create a [`Row`] first, and then call [`Row::wrap`] to /// obtain a [`Row`] that wraps its contents. /// /// The original alignment of the [`Row`] is preserved per row wrapped. pub struct Wrapping<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { row: Row<'a, Message, Theme, Renderer>, vertical_spacing: Option<f32>, align_x: alignment::Horizontal, } impl<Message, Theme, Renderer> Wrapping<'_, Message, Theme, Renderer> { /// Sets the vertical spacing _between_ lines. pub fn vertical_spacing(mut self, amount: impl Into<Pixels>) -> Self { self.vertical_spacing = Some(amount.into().0); self } /// Sets the horizontal alignment of the wrapping [`Row`]. pub fn align_x(mut self, align_x: impl Into<alignment::Horizontal>) -> Self { self.align_x = align_x.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Wrapping<'_, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.row.children() } fn diff(&self, tree: &mut Tree) { self.row.diff(tree); } fn size(&self) -> Size<Length> { self.row.size() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let limits = limits .width(self.row.width) .height(self.row.height) .shrink(self.row.padding); let child_limits = limits.loose(); let spacing = self.row.spacing; let vertical_spacing = self.vertical_spacing.unwrap_or(spacing); let max_width = limits.max().width; let mut children: Vec<layout::Node> = Vec::new(); let mut intrinsic_size = Size::ZERO; let mut row_start = 0; let mut row_height = 0.0; let mut x = 0.0; let mut y = 0.0; let align_factor = match self.row.align { Alignment::Start => 0.0, Alignment::Center => 2.0, Alignment::End => 1.0, }; let align_y = |row_start: std::ops::Range<usize>, row_height: f32, children: &mut Vec<layout::Node>| { if align_factor != 0.0 { for node in &mut children[row_start] { let height = node.size().height; node.translate_mut(Vector::new(0.0, (row_height - height) / align_factor)); } } }; for (i, child) in self.row.children.iter_mut().enumerate() { let node = child .as_widget_mut() .layout(&mut tree.children[i], renderer, &child_limits); let child_size = node.size(); if x != 0.0 && x + child_size.width > max_width { intrinsic_size.width = intrinsic_size.width.max(x - spacing); align_y(row_start..i, row_height, &mut children); y += row_height + vertical_spacing; x = 0.0; row_start = i; row_height = 0.0; } row_height = row_height.max(child_size.height); children.push(node.move_to((x + self.row.padding.left, y + self.row.padding.top))); x += child_size.width + spacing; } if x != 0.0 { intrinsic_size.width = intrinsic_size.width.max(x - spacing); } intrinsic_size.height = y + row_height; align_y(row_start..children.len(), row_height, &mut children); let align_factor = match self.align_x { alignment::Horizontal::Left => 0.0, alignment::Horizontal::Center => 2.0, alignment::Horizontal::Right => 1.0, }; if align_factor != 0.0 { let total_width = intrinsic_size.width; let mut row_start = 0; for i in 0..children.len() { let bounds = children[i].bounds(); let row_width = bounds.x + bounds.width; let next_x = children .get(i + 1) .map(|node| node.bounds().x) .unwrap_or_default(); if next_x == 0.0 { let translation = Vector::new((total_width - row_width) / align_factor, 0.0); for node in &mut children[row_start..=i] { node.translate_mut(translation); } row_start = i + 1; } } } let size = limits.resolve(self.row.width, self.row.height, intrinsic_size); layout::Node::with_children(size.expand(self.row.padding), children) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { self.row.operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { self.row.update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.row .mouse_interaction(tree, layout, cursor, viewport, renderer) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.row .draw(tree, renderer, theme, style, layout, cursor, viewport); } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.row .overlay(tree, layout, renderer, viewport, translation) } } impl<'a, Message, Theme, Renderer> From<Wrapping<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(row: Wrapping<'a, Message, Theme, Renderer>) -> Self { Self::new(row) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/container.rs
widget/src/container.rs
//! Containers let you align a widget inside their boundaries. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::container; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! container("This text is centered inside a rounded box!") //! .padding(10) //! .center(800) //! .style(container::rounded_box) //! .into() //! } //! ``` use crate::core::alignment::{self, Alignment}; use crate::core::border::{self, Border}; use crate::core::gradient::{self, Gradient}; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::theme; use crate::core::widget::tree::{self, Tree}; use crate::core::widget::{self, Operation}; use crate::core::{ self, Background, Clipboard, Color, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shadow, Shell, Size, Theme, Vector, Widget, color, }; /// A widget that aligns its contents inside of its boundaries. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::container; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// container("This text is centered inside a rounded box!") /// .padding(10) /// .center(800) /// .style(container::rounded_box) /// .into() /// } /// ``` pub struct Container<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: core::Renderer, { id: Option<widget::Id>, padding: Padding, width: Length, height: Length, max_width: f32, max_height: f32, horizontal_alignment: alignment::Horizontal, vertical_alignment: alignment::Vertical, clip: bool, content: Element<'a, Message, Theme, Renderer>, class: Theme::Class<'a>, } impl<'a, Message, Theme, Renderer> Container<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { /// Creates a [`Container`] with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { let content = content.into(); let size = content.as_widget().size_hint(); Container { id: None, padding: Padding::ZERO, width: size.width.fluid(), height: size.height.fluid(), max_width: f32::INFINITY, max_height: f32::INFINITY, horizontal_alignment: alignment::Horizontal::Left, vertical_alignment: alignment::Vertical::Top, clip: false, class: Theme::default(), content, } } /// Sets the [`widget::Id`] of the [`Container`]. pub fn id(mut self, id: impl Into<widget::Id>) -> Self { self.id = Some(id.into()); self } /// Sets the [`Padding`] of the [`Container`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the width of the [`Container`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Container`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the maximum width of the [`Container`]. pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self { self.max_width = max_width.into().0; self } /// Sets the maximum height of the [`Container`]. pub fn max_height(mut self, max_height: impl Into<Pixels>) -> Self { self.max_height = max_height.into().0; self } /// Sets the width of the [`Container`] and centers its contents horizontally. pub fn center_x(self, width: impl Into<Length>) -> Self { self.width(width).align_x(alignment::Horizontal::Center) } /// Sets the height of the [`Container`] and centers its contents vertically. pub fn center_y(self, height: impl Into<Length>) -> Self { self.height(height).align_y(alignment::Vertical::Center) } /// Sets the width and height of the [`Container`] and centers its contents in /// both the horizontal and vertical axes. /// /// This is equivalent to chaining [`center_x`] and [`center_y`]. /// /// [`center_x`]: Self::center_x /// [`center_y`]: Self::center_y pub fn center(self, length: impl Into<Length>) -> Self { let length = length.into(); self.center_x(length).center_y(length) } /// Sets the width of the [`Container`] and aligns its contents to the left. pub fn align_left(self, width: impl Into<Length>) -> Self { self.width(width).align_x(alignment::Horizontal::Left) } /// Sets the width of the [`Container`] and aligns its contents to the right. pub fn align_right(self, width: impl Into<Length>) -> Self { self.width(width).align_x(alignment::Horizontal::Right) } /// Sets the height of the [`Container`] and aligns its contents to the top. pub fn align_top(self, height: impl Into<Length>) -> Self { self.height(height).align_y(alignment::Vertical::Top) } /// Sets the height of the [`Container`] and aligns its contents to the bottom. pub fn align_bottom(self, height: impl Into<Length>) -> Self { self.height(height).align_y(alignment::Vertical::Bottom) } /// Sets the content alignment for the horizontal axis of the [`Container`]. pub fn align_x(mut self, alignment: impl Into<alignment::Horizontal>) -> Self { self.horizontal_alignment = alignment.into(); self } /// Sets the content alignment for the vertical axis of the [`Container`]. pub fn align_y(mut self, alignment: impl Into<alignment::Vertical>) -> Self { self.vertical_alignment = alignment.into(); self } /// Sets whether the contents of the [`Container`] should be clipped on /// overflow. pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// Sets the style of the [`Container`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Container`]. #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Container<'_, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { self.content.as_widget().tag() } fn state(&self) -> tree::State { self.content.as_widget().state() } fn children(&self) -> Vec<Tree> { self.content.as_widget().children() } fn diff(&self, tree: &mut Tree) { self.content.as_widget().diff(tree); } 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( limits, self.width, self.height, self.max_width, self.max_height, self.padding, self.horizontal_alignment, self.vertical_alignment, |limits| self.content.as_widget_mut().layout(tree, renderer, limits), ) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { operation.container(self.id.as_ref(), layout.bounds()); operation.traverse(&mut |operation| { self.content.as_widget_mut().operate( tree, layout.children().next().unwrap(), 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( tree, event, layout.children().next().unwrap(), cursor, renderer, clipboard, shell, 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, layout.children().next().unwrap(), cursor, viewport, renderer, ) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, renderer_style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let bounds = layout.bounds(); let style = theme.style(&self.class); if let Some(clipped_viewport) = bounds.intersection(viewport) { draw_background(renderer, &style, bounds); self.content.as_widget().draw( tree, renderer, theme, &renderer::Style { text_color: style.text_color.unwrap_or(renderer_style.text_color), }, layout.children().next().unwrap(), cursor, if self.clip { &clipped_viewport } else { viewport }, ); } } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( tree, layout.children().next().unwrap(), renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Container<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from( container: Container<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(container) } } /// Computes the layout of a [`Container`]. pub fn layout( limits: &layout::Limits, width: Length, height: Length, max_width: f32, max_height: f32, padding: Padding, horizontal_alignment: alignment::Horizontal, vertical_alignment: alignment::Vertical, layout_content: impl FnOnce(&layout::Limits) -> layout::Node, ) -> layout::Node { layout::positioned( &limits.max_width(max_width).max_height(max_height), width, height, padding, |limits| layout_content(&limits.loose()), |content, size| { content.align( Alignment::from(horizontal_alignment), Alignment::from(vertical_alignment), size, ) }, ) } /// Draws the background of a [`Container`] given its [`Style`] and its `bounds`. pub fn draw_background<Renderer>(renderer: &mut Renderer, style: &Style, bounds: Rectangle) where Renderer: core::Renderer, { if style.background.is_some() || style.border.width > 0.0 || style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds, border: style.border, shadow: style.shadow, snap: style.snap, }, style .background .unwrap_or(Background::Color(Color::TRANSPARENT)), ); } } /// The appearance of a container. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The text [`Color`] of the container. pub text_color: Option<Color>, /// The [`Background`] of the container. pub background: Option<Background>, /// The [`Border`] of the container. pub border: Border, /// The [`Shadow`] of the container. pub shadow: Shadow, /// Whether the container should be snapped to the pixel grid. pub snap: bool, } impl Default for Style { fn default() -> Self { Self { text_color: None, background: None, border: Border::default(), shadow: Shadow::default(), snap: renderer::CRISP, } } } impl Style { /// Updates the text color of the [`Style`]. pub fn color(self, color: impl Into<Color>) -> Self { Self { text_color: Some(color.into()), ..self } } /// Updates the border of the [`Style`]. pub fn border(self, border: impl Into<Border>) -> Self { Self { border: border.into(), ..self } } /// Updates the background of the [`Style`]. pub fn background(self, background: impl Into<Background>) -> Self { Self { background: Some(background.into()), ..self } } /// Updates the shadow of the [`Style`]. pub fn shadow(self, shadow: impl Into<Shadow>) -> Self { Self { shadow: shadow.into(), ..self } } } impl From<Color> for Style { fn from(color: Color) -> Self { Self::default().background(color) } } impl From<Gradient> for Style { fn from(gradient: Gradient) -> Self { Self::default().background(gradient) } } impl From<gradient::Linear> for Style { fn from(gradient: gradient::Linear) -> Self { Self::default().background(gradient) } } /// The theme catalog of a [`Container`]. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`Container`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl<Theme> From<Style> for StyleFn<'_, Theme> { fn from(style: Style) -> Self { Box::new(move |_theme| style) } } impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(transparent) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// A transparent [`Container`]. pub fn transparent<Theme>(_theme: &Theme) -> Style { Style::default() } /// A [`Container`] with the given [`Background`]. pub fn background(background: impl Into<Background>) -> Style { Style::default().background(background) } /// A rounded [`Container`] with a background. pub fn rounded_box(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { background: Some(palette.background.weak.color.into()), text_color: Some(palette.background.weak.text), border: border::rounded(2), ..Style::default() } } /// A bordered [`Container`] with a background. pub fn bordered_box(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { background: Some(palette.background.weakest.color.into()), text_color: Some(palette.background.weakest.text), border: Border { width: 1.0, radius: 5.0.into(), color: palette.background.weak.color, }, ..Style::default() } } /// A [`Container`] with a dark background and white text. pub fn dark(_theme: &Theme) -> Style { style(theme::palette::Pair { color: color!(0x111111), text: Color::WHITE, }) } /// A [`Container`] with a primary background color. pub fn primary(theme: &Theme) -> Style { let palette = theme.extended_palette(); style(palette.primary.base) } /// A [`Container`] with a secondary background color. pub fn secondary(theme: &Theme) -> Style { let palette = theme.extended_palette(); style(palette.secondary.base) } /// A [`Container`] with a success background color. pub fn success(theme: &Theme) -> Style { let palette = theme.extended_palette(); style(palette.success.base) } /// A [`Container`] with a warning background color. pub fn warning(theme: &Theme) -> Style { let palette = theme.extended_palette(); style(palette.warning.base) } /// A [`Container`] with a danger background color. pub fn danger(theme: &Theme) -> Style { let palette = theme.extended_palette(); style(palette.danger.base) } fn style(pair: theme::palette::Pair) -> Style { Style { background: Some(pair.color.into()), text_color: Some(pair.text), border: border::rounded(2), ..Style::default() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text_input.rs
widget/src/text_input.rs
//! Text inputs display fields that can be filled with text. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::text_input; //! //! struct State { //! content: String, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! ContentChanged(String) //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! text_input("Type something here...", &state.content) //! .on_input(Message::ContentChanged) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::ContentChanged(content) => { //! state.content = content; //! } //! } //! } //! ``` mod editor; mod value; pub mod cursor; pub use cursor::Cursor; pub use value::Value; use editor::Editor; use crate::core::alignment; use crate::core::clipboard::{self, Clipboard}; use crate::core::input_method; use crate::core::keyboard; use crate::core::keyboard::key; use crate::core::layout; use crate::core::mouse::{self, click}; use crate::core::renderer; use crate::core::text::paragraph::{self, Paragraph as _}; use crate::core::text::{self, Text}; use crate::core::time::{Duration, Instant}; use crate::core::touch; use crate::core::widget; use crate::core::widget::operation::{self, Operation}; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Alignment, Background, Border, Color, Element, Event, InputMethod, Layout, Length, Padding, Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget, }; /// A field that can be filled with text. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::text_input; /// /// struct State { /// content: String, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// ContentChanged(String) /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// text_input("Type something here...", &state.content) /// .on_input(Message::ContentChanged) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::ContentChanged(content) => { /// state.content = content; /// } /// } /// } /// ``` pub struct TextInput<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, { id: Option<widget::Id>, placeholder: String, value: Value, is_secure: bool, font: Option<Renderer::Font>, width: Length, padding: Padding, size: Option<Pixels>, line_height: text::LineHeight, alignment: alignment::Horizontal, on_input: Option<Box<dyn Fn(String) -> Message + 'a>>, on_paste: Option<Box<dyn Fn(String) -> Message + 'a>>, on_submit: Option<Message>, icon: Option<Icon<Renderer::Font>>, class: Theme::Class<'a>, last_status: Option<Status>, } /// The default [`Padding`] of a [`TextInput`]. pub const DEFAULT_PADDING: Padding = Padding::new(5.0); impl<'a, Message, Theme, Renderer> TextInput<'a, Message, Theme, Renderer> where Message: Clone, Theme: Catalog, Renderer: text::Renderer, { /// Creates a new [`TextInput`] with the given placeholder and /// its current value. pub fn new(placeholder: &str, value: &str) -> Self { TextInput { id: None, placeholder: String::from(placeholder), value: Value::new(value), is_secure: false, font: None, width: Length::Fill, padding: DEFAULT_PADDING, size: None, line_height: text::LineHeight::default(), alignment: alignment::Horizontal::Left, on_input: None, on_paste: None, on_submit: None, icon: None, class: Theme::default(), last_status: None, } } /// Sets the [`widget::Id`] of the [`TextInput`]. pub fn id(mut self, id: impl Into<widget::Id>) -> Self { self.id = Some(id.into()); self } /// Converts the [`TextInput`] into a secure password input. pub fn secure(mut self, is_secure: bool) -> Self { self.is_secure = is_secure; self } /// Sets the message that should be produced when some text is typed into /// the [`TextInput`]. /// /// If this method is not called, the [`TextInput`] will be disabled. pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self { self.on_input = Some(Box::new(on_input)); self } /// Sets the message that should be produced when some text is typed into /// the [`TextInput`], if `Some`. /// /// If `None`, the [`TextInput`] will be disabled. pub fn on_input_maybe(mut self, on_input: Option<impl Fn(String) -> Message + 'a>) -> Self { self.on_input = on_input.map(|f| Box::new(f) as _); self } /// Sets the message that should be produced when the [`TextInput`] is /// focused and the enter key is pressed. pub fn on_submit(mut self, message: Message) -> Self { self.on_submit = Some(message); self } /// Sets the message that should be produced when the [`TextInput`] is /// focused and the enter key is pressed, if `Some`. pub fn on_submit_maybe(mut self, on_submit: Option<Message>) -> Self { self.on_submit = on_submit; self } /// Sets the message that should be produced when some text is pasted into /// the [`TextInput`]. pub fn on_paste(mut self, on_paste: impl Fn(String) -> Message + 'a) -> Self { self.on_paste = Some(Box::new(on_paste)); self } /// Sets the message that should be produced when some text is pasted into /// the [`TextInput`], if `Some`. pub fn on_paste_maybe(mut self, on_paste: Option<impl Fn(String) -> Message + 'a>) -> Self { self.on_paste = on_paste.map(|f| Box::new(f) as _); self } /// Sets the [`Font`] of the [`TextInput`]. /// /// [`Font`]: text::Renderer::Font pub fn font(mut self, font: Renderer::Font) -> Self { self.font = Some(font); self } /// Sets the [`Icon`] of the [`TextInput`]. pub fn icon(mut self, icon: Icon<Renderer::Font>) -> Self { self.icon = Some(icon); self } /// Sets the width of the [`TextInput`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the [`Padding`] of the [`TextInput`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the text size of the [`TextInput`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = Some(size.into()); self } /// Sets the [`text::LineHeight`] of the [`TextInput`]. pub fn line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.line_height = line_height.into(); self } /// Sets the horizontal alignment of the [`TextInput`]. pub fn align_x(mut self, alignment: impl Into<alignment::Horizontal>) -> Self { self.alignment = alignment.into(); self } /// Sets the style of the [`TextInput`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`TextInput`]. #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } /// Lays out the [`TextInput`], overriding its [`Value`] if provided. /// /// [`Renderer`]: text::Renderer pub fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, value: Option<&Value>, ) -> layout::Node { let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); let value = value.unwrap_or(&self.value); let font = self.font.unwrap_or_else(|| renderer.default_font()); let text_size = self.size.unwrap_or_else(|| renderer.default_size()); let padding = self.padding.fit(Size::ZERO, limits.max()); let height = self.line_height.to_absolute(text_size); let limits = limits.width(self.width).shrink(padding); let text_bounds = limits.resolve(self.width, height, Size::ZERO); let placeholder_text = Text { font, line_height: self.line_height, content: self.placeholder.as_str(), bounds: Size::new(f32::INFINITY, text_bounds.height), size: text_size, align_x: text::Alignment::Default, align_y: alignment::Vertical::Center, shaping: text::Shaping::Advanced, wrapping: text::Wrapping::default(), hint_factor: renderer.scale_factor(), }; let _ = state.placeholder.update(placeholder_text); let secure_value = self.is_secure.then(|| value.secure()); let value = secure_value.as_ref().unwrap_or(value); let _ = state.value.update(Text { content: &value.to_string(), ..placeholder_text }); if let Some(icon) = &self.icon { let mut content = [0; 4]; let icon_text = Text { line_height: self.line_height, content: icon.code_point.encode_utf8(&mut content) as &_, font: icon.font, size: icon.size.unwrap_or_else(|| renderer.default_size()), bounds: Size::new(f32::INFINITY, text_bounds.height), align_x: text::Alignment::Center, align_y: alignment::Vertical::Center, shaping: text::Shaping::Advanced, wrapping: text::Wrapping::default(), hint_factor: renderer.scale_factor(), }; let _ = state.icon.update(icon_text); let icon_width = state.icon.min_width(); let (text_position, icon_position) = match icon.side { Side::Left => ( Point::new(padding.left + icon_width + icon.spacing, padding.top), Point::new(padding.left, padding.top), ), Side::Right => ( Point::new(padding.left, padding.top), Point::new(padding.left + text_bounds.width - icon_width, padding.top), ), }; let text_node = layout::Node::new(text_bounds - Size::new(icon_width + icon.spacing, 0.0)) .move_to(text_position); let icon_node = layout::Node::new(Size::new(icon_width, text_bounds.height)).move_to(icon_position); layout::Node::with_children(text_bounds.expand(padding), vec![text_node, icon_node]) } else { let text = layout::Node::new(text_bounds).move_to(Point::new(padding.left, padding.top)); layout::Node::with_children(text_bounds.expand(padding), vec![text]) } } fn input_method<'b>( &self, state: &'b State<Renderer::Paragraph>, layout: Layout<'_>, value: &Value, ) -> InputMethod<&'b str> { let Some(Focus { is_window_focused: true, .. }) = &state.is_focused else { return InputMethod::Disabled; }; let secure_value = self.is_secure.then(|| value.secure()); let value = secure_value.as_ref().unwrap_or(value); let text_bounds = layout.children().next().unwrap().bounds(); let caret_index = match state.cursor.state(value) { cursor::State::Index(position) => position, cursor::State::Selection { start, end } => start.min(end), }; let text = state.value.raw(); let (cursor_x, scroll_offset) = measure_cursor_and_scroll_offset(text, text_bounds, caret_index); let alignment_offset = alignment_offset(text_bounds.width, text.min_width(), self.alignment); let x = (text_bounds.x + cursor_x).floor() - scroll_offset + alignment_offset; InputMethod::Enabled { cursor: Rectangle::new( Point::new(x, text_bounds.y), Size::new(1.0, text_bounds.height), ), purpose: if self.is_secure { input_method::Purpose::Secure } else { input_method::Purpose::Normal }, preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref), } } /// Draws the [`TextInput`] with the given [`Renderer`], overriding its /// [`Value`] if provided. /// /// [`Renderer`]: text::Renderer pub fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, layout: Layout<'_>, _cursor: mouse::Cursor, value: Option<&Value>, viewport: &Rectangle, ) { let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>(); let value = value.unwrap_or(&self.value); let is_disabled = self.on_input.is_none(); let secure_value = self.is_secure.then(|| value.secure()); let value = secure_value.as_ref().unwrap_or(value); let bounds = layout.bounds(); let mut children_layout = layout.children(); let text_bounds = children_layout.next().unwrap().bounds(); let style = theme.style(&self.class, self.last_status.unwrap_or(Status::Disabled)); renderer.fill_quad( renderer::Quad { bounds, border: style.border, ..renderer::Quad::default() }, style.background, ); if self.icon.is_some() { let icon_layout = children_layout.next().unwrap(); let icon = state.icon.raw(); renderer.fill_paragraph( icon, icon_layout.bounds().anchor( icon.min_bounds(), Alignment::Center, Alignment::Center, ), style.icon, *viewport, ); } let text = value.to_string(); let (cursor, offset, is_selecting) = if let Some(focus) = state .is_focused .as_ref() .filter(|focus| focus.is_window_focused) { match state.cursor.state(value) { cursor::State::Index(position) => { let (text_value_width, offset) = measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, position); let is_cursor_visible = !is_disabled && ((focus.now - focus.updated_at).as_millis() / CURSOR_BLINK_INTERVAL_MILLIS) .is_multiple_of(2); let cursor = if is_cursor_visible { Some(( renderer::Quad { bounds: Rectangle { x: text_bounds.x + text_value_width, y: text_bounds.y, width: if renderer::CRISP { (1.0 / renderer.scale_factor().unwrap_or(1.0)).max(1.0) } else { 1.0 }, height: text_bounds.height, }, ..renderer::Quad::default() }, style.value, )) } else { None }; (cursor, offset, false) } cursor::State::Selection { start, end } => { let left = start.min(end); let right = end.max(start); let (left_position, left_offset) = measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, left); let (right_position, right_offset) = measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, right); let width = right_position - left_position; ( Some(( renderer::Quad { bounds: Rectangle { x: text_bounds.x + left_position, y: text_bounds.y, width, height: text_bounds.height, }, ..renderer::Quad::default() }, style.selection, )), if end == right { right_offset } else { left_offset }, true, ) } } } else { (None, 0.0, false) }; let draw = |renderer: &mut Renderer, viewport| { let paragraph = if text.is_empty() && state .preedit .as_ref() .map(|preedit| preedit.content.is_empty()) .unwrap_or(true) { state.placeholder.raw() } else { state.value.raw() }; let alignment_offset = alignment_offset(text_bounds.width, paragraph.min_width(), self.alignment); if let Some((cursor, color)) = cursor { renderer.with_translation( Vector::new(alignment_offset - offset, 0.0), |renderer| { renderer.fill_quad(cursor, color); }, ); } else { renderer.with_translation(Vector::ZERO, |_| {}); } renderer.fill_paragraph( paragraph, text_bounds.anchor(paragraph.min_bounds(), Alignment::Start, Alignment::Center) + Vector::new(alignment_offset - offset, 0.0), if text.is_empty() { style.placeholder } else { style.value }, viewport, ); }; if is_selecting { renderer.with_layer(text_bounds, |renderer| draw(renderer, *viewport)); } else { draw(renderer, text_bounds); } } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for TextInput<'_, Message, Theme, Renderer> where Message: Clone, Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(State::<Renderer::Paragraph>::new()) } fn diff(&self, tree: &mut Tree) { let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); // Stop pasting if input becomes disabled if self.on_input.is_none() { state.is_pasting = None; } } fn size(&self) -> Size<Length> { Size { width: self.width, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.layout(tree, renderer, limits, None) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, _renderer: &Renderer, operation: &mut dyn Operation, ) { let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); operation.text_input(self.id.as_ref(), layout.bounds(), state); operation.focusable(self.id.as_ref(), layout.bounds(), state); } 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 update_cache = |state, value| { replace_paragraph( renderer, state, layout, value, self.font, self.size, self.line_height, ); }; match &event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let state = state::<Renderer>(tree); let cursor_before = state.cursor; let click_position = cursor.position_over(layout.bounds()); state.is_focused = if click_position.is_some() { let now = Instant::now(); Some(Focus { updated_at: now, now, is_window_focused: true, }) } else { None }; if let Some(cursor_position) = click_position { let text_layout = layout.children().next().unwrap(); let target = { let text_bounds = text_layout.bounds(); let alignment_offset = alignment_offset( text_bounds.width, state.value.raw().min_width(), self.alignment, ); cursor_position.x - text_bounds.x - alignment_offset }; let click = mouse::Click::new(cursor_position, mouse::Button::Left, state.last_click); match click.kind() { click::Kind::Single => { let position = if target > 0.0 { let value = if self.is_secure { self.value.secure() } else { self.value.clone() }; find_cursor_position(text_layout.bounds(), &value, state, target) } else { None } .unwrap_or(0); if state.keyboard_modifiers.shift() { state .cursor .select_range(state.cursor.start(&self.value), position); } else { state.cursor.move_to(position); } state.is_dragging = Some(Drag::Select); } click::Kind::Double => { if self.is_secure { state.cursor.select_all(&self.value); state.is_dragging = None; } else { let position = find_cursor_position( text_layout.bounds(), &self.value, state, target, ) .unwrap_or(0); state.cursor.select_range( self.value.previous_start_of_word(position), self.value.next_end_of_word(position), ); state.is_dragging = Some(Drag::SelectWords { anchor: position }); } } click::Kind::Triple => { state.cursor.select_all(&self.value); state.is_dragging = None; } } state.last_click = Some(click); if cursor_before != state.cursor { shell.request_redraw(); } shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) | Event::Touch(touch::Event::FingerLost { .. }) => { state::<Renderer>(tree).is_dragging = None; } Event::Mouse(mouse::Event::CursorMoved { position }) | Event::Touch(touch::Event::FingerMoved { position, .. }) => { let state = state::<Renderer>(tree); if let Some(is_dragging) = &state.is_dragging { let text_layout = layout.children().next().unwrap(); let target = { let text_bounds = text_layout.bounds(); let alignment_offset = alignment_offset( text_bounds.width, state.value.raw().min_width(), self.alignment, ); position.x - text_bounds.x - alignment_offset }; let value = if self.is_secure { self.value.secure() } else { self.value.clone() }; let position = find_cursor_position(text_layout.bounds(), &value, state, target) .unwrap_or(0); let selection_before = state.cursor.selection(&value); match is_dragging { Drag::Select => { state .cursor .select_range(state.cursor.start(&value), position); } Drag::SelectWords { anchor } => { if position < *anchor { state.cursor.select_range( self.value.previous_start_of_word(position), self.value.next_end_of_word(*anchor), ); } else { state.cursor.select_range( self.value.previous_start_of_word(*anchor), self.value.next_end_of_word(position), ); } } } if let Some(focus) = &mut state.is_focused { focus.updated_at = Instant::now(); } if selection_before != state.cursor.selection(&value) { shell.request_redraw(); } shell.capture_event(); } } Event::Keyboard(keyboard::Event::KeyPressed { key, text, modified_key, physical_key, .. }) => { let state = state::<Renderer>(tree); if let Some(focus) = &mut state.is_focused { let modifiers = state.keyboard_modifiers; match key.to_latin(*physical_key) { Some('c') if state.keyboard_modifiers.command() && !self.is_secure => { if let Some((start, end)) = state.cursor.selection(&self.value) { clipboard.write( clipboard::Kind::Standard, self.value.select(start, end).to_string(), ); } shell.capture_event(); return; } Some('x') if state.keyboard_modifiers.command() && !self.is_secure => { let Some(on_input) = &self.on_input else { return; }; if let Some((start, end)) = state.cursor.selection(&self.value) { clipboard.write( clipboard::Kind::Standard, self.value.select(start, end).to_string(), ); } let mut editor = Editor::new(&mut self.value, &mut state.cursor); editor.delete(); let message = (on_input)(editor.contents()); shell.publish(message); shell.capture_event(); focus.updated_at = Instant::now(); update_cache(state, &self.value); return; } Some('v') if state.keyboard_modifiers.command() && !state.keyboard_modifiers.alt() => { let Some(on_input) = &self.on_input else { return; }; let content = match state.is_pasting.take() { Some(content) => content, None => { let content: String = clipboard .read(clipboard::Kind::Standard) .unwrap_or_default() .chars() .filter(|c| !c.is_control()) .collect(); Value::new(&content) } }; let mut editor = Editor::new(&mut self.value, &mut state.cursor); editor.paste(content.clone()); let message = if let Some(paste) = &self.on_paste { (paste)(editor.contents()) } else { (on_input)(editor.contents()) }; shell.publish(message); shell.capture_event(); state.is_pasting = Some(content); focus.updated_at = Instant::now(); update_cache(state, &self.value); return; } Some('a') if state.keyboard_modifiers.command() => { let cursor_before = state.cursor; state.cursor.select_all(&self.value); if cursor_before != state.cursor { focus.updated_at = Instant::now(); shell.request_redraw();
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/table.rs
widget/src/table.rs
//! Display tables. use crate::core; use crate::core::alignment; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::{ Alignment, Background, Element, Layout, Length, Pixels, Rectangle, Size, Widget, }; /// Creates a new [`Table`] with the given columns and rows. /// /// Columns can be created using the [`column()`] function, while rows can be any /// iterator over some data type `T`. pub fn table<'a, 'b, T, Message, Theme, Renderer>( columns: impl IntoIterator<Item = Column<'a, 'b, T, Message, Theme, Renderer>>, rows: impl IntoIterator<Item = T>, ) -> Table<'a, Message, Theme, Renderer> where T: Clone, Theme: Catalog, Renderer: core::Renderer, { Table::new(columns, rows) } /// Creates a new [`Column`] with the given header and view function. /// /// The view function will be called for each row in a [`Table`] and it must /// produce the resulting contents of a cell. pub fn column<'a, 'b, T, E, Message, Theme, Renderer>( header: impl Into<Element<'a, Message, Theme, Renderer>>, view: impl Fn(T) -> E + 'b, ) -> Column<'a, 'b, T, Message, Theme, Renderer> where T: 'a, E: Into<Element<'a, Message, Theme, Renderer>>, { Column { header: header.into(), view: Box::new(move |data| view(data).into()), width: Length::Shrink, align_x: alignment::Horizontal::Left, align_y: alignment::Vertical::Top, } } /// A grid-like visual representation of data distributed in columns and rows. pub struct Table<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, { columns: Vec<Column_>, cells: Vec<Element<'a, Message, Theme, Renderer>>, width: Length, height: Length, padding_x: f32, padding_y: f32, separator_x: f32, separator_y: f32, class: Theme::Class<'a>, } struct Column_ { width: Length, align_x: alignment::Horizontal, align_y: alignment::Vertical, } impl<'a, Message, Theme, Renderer> Table<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { /// Creates a new [`Table`] with the given columns and rows. /// /// Columns can be created using the [`column()`] function, while rows can be any /// iterator over some data type `T`. pub fn new<'b, T>( columns: impl IntoIterator<Item = Column<'a, 'b, T, Message, Theme, Renderer>>, rows: impl IntoIterator<Item = T>, ) -> Self where T: Clone, { let columns = columns.into_iter(); let rows = rows.into_iter(); let mut width = Length::Shrink; let mut height = Length::Shrink; let mut cells = Vec::with_capacity(columns.size_hint().0 * (1 + rows.size_hint().0)); let (mut columns, views): (Vec<_>, Vec<_>) = columns .map(|column| { width = width.enclose(column.width); cells.push(column.header); ( Column_ { width: column.width, align_x: column.align_x, align_y: column.align_y, }, column.view, ) }) .collect(); for row in rows { for view in &views { let cell = view(row.clone()); let size_hint = cell.as_widget().size_hint(); height = height.enclose(size_hint.height); cells.push(cell); } } if width == Length::Shrink && let Some(first) = columns.first_mut() { first.width = Length::Fill; } Self { columns, cells, width, height, padding_x: 10.0, padding_y: 5.0, separator_x: 1.0, separator_y: 1.0, class: Theme::default(), } } /// Sets the width of the [`Table`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the padding of the cells of the [`Table`]. pub fn padding(self, padding: impl Into<Pixels>) -> Self { let padding = padding.into(); self.padding_x(padding).padding_y(padding) } /// Sets the horizontal padding of the cells of the [`Table`]. pub fn padding_x(mut self, padding: impl Into<Pixels>) -> Self { self.padding_x = padding.into().0; self } /// Sets the vertical padding of the cells of the [`Table`]. pub fn padding_y(mut self, padding: impl Into<Pixels>) -> Self { self.padding_y = padding.into().0; self } /// Sets the thickness of the line separator between the cells of the [`Table`]. pub fn separator(self, separator: impl Into<Pixels>) -> Self { let separator = separator.into(); self.separator_x(separator).separator_y(separator) } /// Sets the thickness of the horizontal line separator between the cells of the [`Table`]. pub fn separator_x(mut self, separator: impl Into<Pixels>) -> Self { self.separator_x = separator.into().0; self } /// Sets the thickness of the vertical line separator between the cells of the [`Table`]. pub fn separator_y(mut self, separator: impl Into<Pixels>) -> Self { self.separator_y = separator.into().0; self } } struct Metrics { columns: Vec<f32>, rows: Vec<f32>, } impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Table<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { fn size(&self) -> Size<Length> { Size { width: self.width, height: self.height, } } fn tag(&self) -> widget::tree::Tag { widget::tree::Tag::of::<Metrics>() } fn state(&self) -> widget::tree::State { widget::tree::State::new(Metrics { columns: Vec::new(), rows: Vec::new(), }) } fn children(&self) -> Vec<widget::Tree> { self.cells .iter() .map(|cell| widget::Tree::new(cell.as_widget())) .collect() } fn diff(&self, tree: &mut widget::Tree) { tree.diff_children(&self.cells); } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let metrics = tree.state.downcast_mut::<Metrics>(); let columns = self.columns.len(); let rows = self.cells.len() / columns; let limits = limits.width(self.width).height(self.height); let available = limits.max(); let table_fluid = self.width.fluid(); let mut cells = Vec::with_capacity(self.cells.len()); cells.resize(self.cells.len(), layout::Node::default()); metrics.columns = vec![0.0; self.columns.len()]; metrics.rows = vec![0.0; rows]; let mut column_factors = vec![0; self.columns.len()]; let mut total_row_factors = 0; let mut total_fluid_height = 0.0; let mut row_factor = 0; let spacing_x = self.padding_x * 2.0 + self.separator_x; let spacing_y = self.padding_y * 2.0 + self.separator_y; // FIRST PASS // Lay out non-fluid cells let mut x = self.padding_x; let mut y = self.padding_y; for (i, (cell, state)) in self.cells.iter_mut().zip(&mut tree.children).enumerate() { let row = i / columns; let column = i % columns; let width = self.columns[column].width; let size = cell.as_widget().size(); if column == 0 { x = self.padding_x; if row > 0 { y += metrics.rows[row - 1] + spacing_y; if row_factor != 0 { total_fluid_height += metrics.rows[row - 1]; total_row_factors += row_factor; row_factor = 0; } } } let width_factor = width.fill_factor(); let height_factor = size.height.fill_factor(); if width_factor != 0 || height_factor != 0 || size.width.is_fill() { column_factors[column] = column_factors[column].max(width_factor); row_factor = row_factor.max(height_factor); continue; } let limits = layout::Limits::new( Size::ZERO, Size::new(available.width - x, available.height - y), ) .width(width); let layout = cell.as_widget_mut().layout(state, renderer, &limits); let size = limits.resolve(width, Length::Shrink, layout.size()); metrics.columns[column] = metrics.columns[column].max(size.width); metrics.rows[row] = metrics.rows[row].max(size.height); cells[i] = layout; x += size.width + spacing_x; } // SECOND PASS // Lay out fluid cells, using metrics from the first pass as limits let left = Size::new( available.width - metrics .columns .iter() .enumerate() .filter(|(i, _)| column_factors[*i] == 0) .map(|(_, width)| width) .sum::<f32>(), available.height - total_fluid_height, ); let width_unit = (left.width - spacing_x * self.columns.len().saturating_sub(1) as f32 - self.padding_x * 2.0) / column_factors.iter().sum::<u16>() as f32; let height_unit = (left.height - spacing_y * rows.saturating_sub(1) as f32 - self.padding_y * 2.0) / total_row_factors as f32; let mut x = self.padding_x; let mut y = self.padding_y; for (i, (cell, state)) in self.cells.iter_mut().zip(&mut tree.children).enumerate() { let row = i / columns; let column = i % columns; let size = cell.as_widget().size(); let width = self.columns[column].width; let width_factor = width.fill_factor(); let height_factor = size.height.fill_factor(); if column == 0 { x = self.padding_x; if row > 0 { y += metrics.rows[row - 1] + spacing_y; } } if width_factor == 0 && size.width.fill_factor() == 0 && size.height.fill_factor() == 0 { continue; } let max_width = if width_factor == 0 { if size.width.is_fill() { metrics.columns[column] } else { (available.width - x).max(0.0) } } else { width_unit * width_factor as f32 }; let max_height = if height_factor == 0 { if size.height.is_fill() { metrics.rows[row] } else { (available.height - y).max(0.0) } } else { height_unit * height_factor as f32 }; let limits = layout::Limits::new(Size::ZERO, Size::new(max_width, max_height)).width(width); let layout = cell.as_widget_mut().layout(state, renderer, &limits); let size = limits.resolve( if let Length::Fixed(_) = width { width } else { table_fluid }, Length::Shrink, layout.size(), ); metrics.columns[column] = metrics.columns[column].max(size.width); metrics.rows[row] = metrics.rows[row].max(size.height); cells[i] = layout; x += size.width + spacing_x; } // THIRD PASS // Position each cell let mut x = self.padding_x; let mut y = self.padding_y; for (i, cell) in cells.iter_mut().enumerate() { let row = i / columns; let column = i % columns; if column == 0 { x = self.padding_x; if row > 0 { y += metrics.rows[row - 1] + spacing_y; } } let Column_ { align_x, align_y, .. } = &self.columns[column]; cell.move_to_mut((x, y)); cell.align_mut( Alignment::from(*align_x), Alignment::from(*align_y), Size::new(metrics.columns[column], metrics.rows[row]), ); x += metrics.columns[column] + spacing_x; } let intrinsic = limits.resolve( self.width, self.height, Size::new( x - spacing_x + self.padding_x, y + metrics .rows .last() .copied() .map(|height| height + self.padding_y) .unwrap_or_default(), ), ); layout::Node::with_children(intrinsic, cells) } fn update( &mut self, tree: &mut widget::Tree, event: &core::Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn core::Clipboard, shell: &mut core::Shell<'_, Message>, viewport: &Rectangle, ) { for ((cell, tree), layout) in self .cells .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { cell.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { for ((cell, state), layout) in self.cells.iter().zip(&tree.children).zip(layout.children()) { cell.as_widget() .draw(state, renderer, theme, style, layout, cursor, viewport); } let bounds = layout.bounds(); let metrics = tree.state.downcast_ref::<Metrics>(); let style = theme.style(&self.class); if self.separator_x > 0.0 { let mut x = self.padding_x; for width in &metrics.columns[..metrics.columns.len().saturating_sub(1)] { x += width + self.padding_x; renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x + x, y: bounds.y, width: self.separator_x, height: bounds.height, }, snap: true, ..renderer::Quad::default() }, style.separator_x, ); x += self.separator_x + self.padding_x; } } if self.separator_y > 0.0 { let mut y = self.padding_y; for height in &metrics.rows[..metrics.rows.len().saturating_sub(1)] { y += height + self.padding_y; renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x, y: bounds.y + y, width: bounds.width, height: self.separator_y, }, snap: true, ..renderer::Quad::default() }, style.separator_y, ); y += self.separator_y + self.padding_y; } } } fn mouse_interaction( &self, tree: &widget::Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.cells .iter() .zip(&tree.children) .zip(layout.children()) .map(|((cell, tree), layout)| { cell.as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() } fn operate( &mut self, tree: &mut widget::Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { for ((cell, state), layout) in self .cells .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { cell.as_widget_mut() .operate(state, layout, renderer, operation); } } fn overlay<'b>( &'b mut self, tree: &'b mut widget::Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { overlay::from_children( &mut self.cells, tree, layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Table<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from(table: Table<'a, Message, Theme, Renderer>) -> Self { Element::new(table) } } /// A vertical visualization of some data with a header. pub struct Column<'a, 'b, T, Message, Theme = crate::Theme, Renderer = crate::Renderer> { header: Element<'a, Message, Theme, Renderer>, view: Box<dyn Fn(T) -> Element<'a, Message, Theme, Renderer> + 'b>, width: Length, align_x: alignment::Horizontal, align_y: alignment::Vertical, } impl<'a, 'b, T, Message, Theme, Renderer> Column<'a, 'b, T, Message, Theme, Renderer> { /// Sets the width of the [`Column`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the alignment for the horizontal axis of the [`Column`]. pub fn align_x(mut self, alignment: impl Into<alignment::Horizontal>) -> Self { self.align_x = alignment.into(); self } /// Sets the alignment for the vertical axis of the [`Column`]. pub fn align_y(mut self, alignment: impl Into<alignment::Vertical>) -> Self { self.align_y = alignment.into(); self } } /// The appearance of a [`Table`]. #[derive(Debug, Clone, Copy)] pub struct Style { /// The background color of the horizontal line separator between cells. pub separator_x: Background, /// The background color of the vertical line separator between cells. pub separator_y: Background, } /// The theme catalog of a [`Table`]. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`Table`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl<Theme> From<Style> for StyleFn<'_, Theme> { fn from(style: Style) -> Self { Box::new(move |_theme| style) } } impl Catalog for crate::Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The default style of a [`Table`]. pub fn default(theme: &crate::Theme) -> Style { let palette = theme.extended_palette(); let separator = palette.background.strong.color.into(); Style { separator_x: separator, separator_y: separator, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/slider.rs
widget/src/slider.rs
//! Sliders let users set a value by moving an indicator. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::slider; //! //! struct State { //! value: f32, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! ValueChanged(f32), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! slider(0.0..=100.0, state.value, Message::ValueChanged).into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::ValueChanged(value) => { //! state.value = value; //! } //! } //! } //! ``` use crate::core::border::{self, Border}; use crate::core::keyboard; use crate::core::keyboard::key::{self, Key}; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::touch; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ self, Background, Clipboard, Color, Element, Event, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Theme, Widget, }; use std::ops::RangeInclusive; /// An horizontal bar and a handle that selects a single value from a range of /// values. /// /// A [`Slider`] will try to fill the horizontal space of its container. /// /// The [`Slider`] range of numeric values is generic and its step size defaults /// to 1 unit. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::slider; /// /// struct State { /// value: f32, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// ValueChanged(f32), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// slider(0.0..=100.0, state.value, Message::ValueChanged).into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::ValueChanged(value) => { /// state.value = value; /// } /// } /// } /// ``` pub struct Slider<'a, T, Message, Theme = crate::Theme> where Theme: Catalog, { range: RangeInclusive<T>, step: T, shift_step: Option<T>, value: T, default: Option<T>, on_change: Box<dyn Fn(T) -> Message + 'a>, on_release: Option<Message>, width: Length, height: f32, class: Theme::Class<'a>, status: Option<Status>, } impl<'a, T, Message, Theme> Slider<'a, T, Message, Theme> where T: Copy + From<u8> + PartialOrd, Message: Clone, Theme: Catalog, { /// The default height of a [`Slider`]. pub const DEFAULT_HEIGHT: f32 = 16.0; /// Creates a new [`Slider`]. /// /// It expects: /// * an inclusive range of possible values /// * the current value of the [`Slider`] /// * a function that will be called when the [`Slider`] is dragged. /// It receives the new value of the [`Slider`] and must produce a /// `Message`. pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self where F: 'a + Fn(T) -> Message, { let value = if value >= *range.start() { value } else { *range.start() }; let value = if value <= *range.end() { value } else { *range.end() }; Slider { value, default: None, range, step: T::from(1), shift_step: None, on_change: Box::new(on_change), on_release: None, width: Length::Fill, height: Self::DEFAULT_HEIGHT, class: Theme::default(), status: None, } } /// Sets the optional default value for the [`Slider`]. /// /// If set, the [`Slider`] will reset to this value when ctrl-clicked or command-clicked. pub fn default(mut self, default: impl Into<T>) -> Self { self.default = Some(default.into()); self } /// Sets the release message of the [`Slider`]. /// This is called when the mouse is released from the slider. /// /// Typically, the user's interaction with the slider is finished when this message is produced. /// This is useful if you need to spawn a long-running task from the slider's result, where /// the default on_change message could create too many events. pub fn on_release(mut self, on_release: Message) -> Self { self.on_release = Some(on_release); self } /// Sets the width of the [`Slider`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Slider`]. pub fn height(mut self, height: impl Into<Pixels>) -> Self { self.height = height.into().0; self } /// Sets the step size of the [`Slider`]. pub fn step(mut self, step: impl Into<T>) -> Self { self.step = step.into(); self } /// Sets the optional "shift" step for the [`Slider`]. /// /// If set, this value is used as the step while the shift key is pressed. pub fn shift_step(mut self, shift_step: impl Into<T>) -> Self { self.shift_step = Some(shift_step.into()); self } /// Sets the style of the [`Slider`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Slider`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Slider<'_, T, Message, Theme> where T: Copy + Into<f64> + num_traits::FromPrimitive, Message: Clone, Theme: Catalog, Renderer: core::Renderer, { 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: Length::Shrink, } } 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>(); let mut update = || { let current_value = self.value; let locate = |cursor_position: Point| -> Option<T> { let bounds = layout.bounds(); if cursor_position.x <= bounds.x { Some(*self.range.start()) } else if cursor_position.x >= bounds.x + bounds.width { Some(*self.range.end()) } else { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let start = (*self.range.start()).into(); let end = (*self.range.end()).into(); let percent = f64::from(cursor_position.x - bounds.x) / f64::from(bounds.width); let steps = (percent * (end - start) / step).round(); let value = steps * step + start; T::from_f64(value.min(end)) } }; let increment = |value: T| -> Option<T> { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let steps = (value.into() / step).round(); let new_value = step * (steps + 1.0); if new_value > (*self.range.end()).into() { return Some(*self.range.end()); } T::from_f64(new_value) }; let decrement = |value: T| -> Option<T> { let step = if state.keyboard_modifiers.shift() { self.shift_step.unwrap_or(self.step) } else { self.step } .into(); let steps = (value.into() / step).round(); let new_value = step * (steps - 1.0); if new_value < (*self.range.start()).into() { return Some(*self.range.start()); } T::from_f64(new_value) }; let change = |new_value: T| { if (self.value.into() - new_value.into()).abs() > f64::EPSILON { shell.publish((self.on_change)(new_value)); self.value = new_value; } }; match &event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if let Some(cursor_position) = cursor.position_over(layout.bounds()) { if state.keyboard_modifiers.command() { let _ = self.default.map(change); state.is_dragging = false; } else { let _ = locate(cursor_position).map(change); state.is_dragging = true; } shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) | Event::Touch(touch::Event::FingerLost { .. }) => { if state.is_dragging { if let Some(on_release) = self.on_release.clone() { shell.publish(on_release); } state.is_dragging = false; } } Event::Mouse(mouse::Event::CursorMoved { .. }) | Event::Touch(touch::Event::FingerMoved { .. }) => { if state.is_dragging { let _ = cursor.land().position().and_then(locate).map(change); shell.capture_event(); } } Event::Mouse(mouse::Event::WheelScrolled { delta }) if state.keyboard_modifiers.control() => { if cursor.is_over(layout.bounds()) { let delta = match delta { mouse::ScrollDelta::Lines { x: _, y } => y, mouse::ScrollDelta::Pixels { x: _, y } => y, }; if *delta < 0.0 { let _ = decrement(current_value).map(change); } else { let _ = increment(current_value).map(change); } shell.capture_event(); } } Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) => { if cursor.is_over(layout.bounds()) { match key { Key::Named(key::Named::ArrowUp) => { let _ = increment(current_value).map(change); shell.capture_event(); } Key::Named(key::Named::ArrowDown) => { let _ = decrement(current_value).map(change); shell.capture_event(); } _ => (), } } } Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => { state.keyboard_modifiers = *modifiers; } _ => {} } }; update(); let current_status = if state.is_dragging { Status::Dragged } else if cursor.is_over(layout.bounds()) { Status::Hovered } else { Status::Active }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.status = Some(current_status); } else if self.status.is_some_and(|status| status != current_status) { 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 style = theme.style(&self.class, self.status.unwrap_or(Status::Active)); let (handle_width, handle_height, handle_border_radius) = match style.handle.shape { HandleShape::Circle { radius } => (radius * 2.0, radius * 2.0, radius.into()), HandleShape::Rectangle { width, border_radius, } => (f32::from(width), bounds.height, border_radius), }; let value = self.value.into() as f32; let (range_start, range_end) = { let (start, end) = self.range.clone().into_inner(); (start.into() as f32, end.into() as f32) }; let offset = if range_start >= range_end { 0.0 } else { (bounds.width - handle_width) * (value - range_start) / (range_end - range_start) }; let rail_y = bounds.y + bounds.height / 2.0; renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x, y: rail_y - style.rail.width / 2.0, width: offset + handle_width / 2.0, height: style.rail.width, }, border: style.rail.border, ..renderer::Quad::default() }, style.rail.backgrounds.0, ); renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x + offset + handle_width / 2.0, y: rail_y - style.rail.width / 2.0, width: bounds.width - offset - handle_width / 2.0, height: style.rail.width, }, border: style.rail.border, ..renderer::Quad::default() }, style.rail.backgrounds.1, ); renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x + offset, y: rail_y - handle_height / 2.0, width: handle_width, height: handle_height, }, border: Border { radius: handle_border_radius, width: style.handle.border_width, color: style.handle.border_color, }, ..renderer::Quad::default() }, style.handle.background, ); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let state = tree.state.downcast_ref::<State>(); if state.is_dragging { // FIXME: Fall back to `Pointer` on Windows // See https://github.com/rust-windowing/winit/issues/1043 if cfg!(target_os = "windows") { mouse::Interaction::Pointer } else { mouse::Interaction::Grabbing } } else if cursor.is_over(layout.bounds()) { if cfg!(target_os = "windows") { mouse::Interaction::Pointer } else { mouse::Interaction::Grab } } else { mouse::Interaction::default() } } } impl<'a, T, Message, Theme, Renderer> From<Slider<'a, T, Message, Theme>> for Element<'a, Message, Theme, Renderer> where T: Copy + Into<f64> + num_traits::FromPrimitive + 'a, Message: Clone + 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from(slider: Slider<'a, T, Message, Theme>) -> Element<'a, Message, Theme, Renderer> { Element::new(slider) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] struct State { is_dragging: bool, keyboard_modifiers: keyboard::Modifiers, } /// The possible status of a [`Slider`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Slider`] can be interacted with. Active, /// The [`Slider`] is being hovered. Hovered, /// The [`Slider`] is being dragged. Dragged, } /// The appearance of a slider. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The colors of the rail of the slider. pub rail: Rail, /// The appearance of the [`Handle`] of the slider. pub handle: Handle, } impl Style { /// Changes the [`HandleShape`] of the [`Style`] to a circle /// with the given radius. pub fn with_circular_handle(mut self, radius: impl Into<Pixels>) -> Self { self.handle.shape = HandleShape::Circle { radius: radius.into().0, }; self } } /// The appearance of a slider rail #[derive(Debug, Clone, Copy, PartialEq)] pub struct Rail { /// The backgrounds of the rail of the slider. pub backgrounds: (Background, Background), /// The width of the stroke of a slider rail. pub width: f32, /// The border of the rail. pub border: Border, } /// The appearance of the handle of a slider. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Handle { /// The shape of the handle. pub shape: HandleShape, /// The [`Background`] of the handle. pub background: Background, /// The border width of the handle. pub border_width: f32, /// The border [`Color`] of the handle. pub border_color: Color, } /// The shape of the handle of a slider. #[derive(Debug, Clone, Copy, PartialEq)] pub enum HandleShape { /// A circular handle. Circle { /// The radius of the circle. radius: f32, }, /// A rectangular shape. Rectangle { /// The width of the rectangle. width: u16, /// The border radius of the corners of the rectangle. border_radius: border::Radius, }, } /// The theme catalog of a [`Slider`]. pub trait Catalog: Sized { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } /// A styling function for a [`Slider`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// The default style of a [`Slider`]. pub fn default(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let color = match status { Status::Active => palette.primary.base.color, Status::Hovered => palette.primary.strong.color, Status::Dragged => palette.primary.weak.color, }; Style { rail: Rail { backgrounds: (color.into(), palette.background.strong.color.into()), width: 4.0, border: Border { radius: 2.0.into(), width: 0.0, color: Color::TRANSPARENT, }, }, handle: Handle { shape: HandleShape::Circle { radius: 7.0 }, background: color.into(), border_color: Color::TRANSPARENT, border_width: 0.0, }, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/canvas.rs
widget/src/canvas.rs
//! Canvases can be leveraged to draw interactive 2D graphics. //! //! # Example: Drawing a Simple Circle //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::mouse; //! use iced::widget::canvas; //! use iced::{Color, Rectangle, Renderer, Theme}; //! //! // First, we define the data we need for drawing //! #[derive(Debug)] //! struct Circle { //! radius: f32, //! } //! //! // Then, we implement the `Program` trait //! impl<Message> canvas::Program<Message> for Circle { //! // No internal state //! type State = (); //! //! fn draw( //! &self, //! _state: &(), //! renderer: &Renderer, //! _theme: &Theme, //! bounds: Rectangle, //! _cursor: mouse::Cursor //! ) -> Vec<canvas::Geometry> { //! // We prepare a new `Frame` //! let mut frame = canvas::Frame::new(renderer, bounds.size()); //! //! // We create a `Path` representing a simple circle //! let circle = canvas::Path::circle(frame.center(), self.radius); //! //! // And fill it with some color //! frame.fill(&circle, Color::BLACK); //! //! // Then, we produce the geometry //! vec![frame.into_geometry()] //! } //! } //! //! // Finally, we simply use our `Circle` to create the `Canvas`! //! fn view<'a, Message: 'a>(_state: &'a State) -> Element<'a, Message> { //! canvas(Circle { radius: 50.0 }).into() //! } //! ``` mod program; pub use program::Program; pub use crate::Action; pub use crate::core::event::Event; pub use crate::graphics::cache::Group; pub use crate::graphics::geometry::{ Fill, Gradient, Image, LineCap, LineDash, LineJoin, Path, Stroke, Style, Text, fill, gradient, path, stroke, }; use crate::core::event; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget}; use crate::graphics::geometry; use std::marker::PhantomData; /// A simple cache that stores generated [`Geometry`] to avoid recomputation. /// /// A [`Cache`] will not redraw its geometry unless the dimensions of its layer /// change or it is explicitly cleared. pub type Cache<Renderer = crate::Renderer> = geometry::Cache<Renderer>; /// The geometry supported by a renderer. pub type Geometry<Renderer = crate::Renderer> = <Renderer as geometry::Renderer>::Geometry; /// The frame supported by a renderer. pub type Frame<Renderer = crate::Renderer> = geometry::Frame<Renderer>; /// A widget capable of drawing 2D graphics. /// /// # Example: Drawing a Simple Circle /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::mouse; /// use iced::widget::canvas; /// use iced::{Color, Rectangle, Renderer, Theme}; /// /// // First, we define the data we need for drawing /// #[derive(Debug)] /// struct Circle { /// radius: f32, /// } /// /// // Then, we implement the `Program` trait /// impl<Message> canvas::Program<Message> for Circle { /// // No internal state /// type State = (); /// /// fn draw( /// &self, /// _state: &(), /// renderer: &Renderer, /// _theme: &Theme, /// bounds: Rectangle, /// _cursor: mouse::Cursor /// ) -> Vec<canvas::Geometry> { /// // We prepare a new `Frame` /// let mut frame = canvas::Frame::new(renderer, bounds.size()); /// /// // We create a `Path` representing a simple circle /// let circle = canvas::Path::circle(frame.center(), self.radius); /// /// // And fill it with some color /// frame.fill(&circle, Color::BLACK); /// /// // Then, we produce the geometry /// vec![frame.into_geometry()] /// } /// } /// /// // Finally, we simply use our `Circle` to create the `Canvas`! /// fn view<'a, Message: 'a>(_state: &'a State) -> Element<'a, Message> { /// canvas(Circle { radius: 50.0 }).into() /// } /// ``` #[derive(Debug)] pub struct Canvas<P, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Renderer: geometry::Renderer, P: Program<Message, Theme, Renderer>, { width: Length, height: Length, program: P, message_: PhantomData<Message>, theme_: PhantomData<Theme>, renderer_: PhantomData<Renderer>, last_mouse_interaction: Option<mouse::Interaction>, } impl<P, Message, Theme, Renderer> Canvas<P, Message, Theme, Renderer> where P: Program<Message, Theme, Renderer>, Renderer: geometry::Renderer, { const DEFAULT_SIZE: f32 = 100.0; /// Creates a new [`Canvas`]. pub fn new(program: P) -> Self { Canvas { width: Length::Fixed(Self::DEFAULT_SIZE), height: Length::Fixed(Self::DEFAULT_SIZE), program, message_: PhantomData, theme_: PhantomData, renderer_: PhantomData, last_mouse_interaction: None, } } /// Sets the width of the [`Canvas`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Canvas`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } } impl<P, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Canvas<P, Message, Theme, Renderer> where Renderer: geometry::Renderer, P: Program<Message, Theme, Renderer>, { fn tag(&self) -> tree::Tag { struct Tag<T>(T); tree::Tag::of::<Tag<P::State>>() } fn state(&self) -> tree::State { tree::State::new(P::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 bounds = layout.bounds(); let state = tree.state.downcast_mut::<P::State>(); let is_redraw_request = matches!(event, Event::Window(window::Event::RedrawRequested(_now)),); if let Some(action) = self.program.update(state, event, bounds, cursor) { let (message, redraw_request, event_status) = action.into_inner(); shell.request_redraw_at(redraw_request); if let Some(message) = message { shell.publish(message); } if event_status == event::Status::Captured { shell.capture_event(); } } if shell.redraw_request() != window::RedrawRequest::NextFrame { let mouse_interaction = self.mouse_interaction(tree, layout, cursor, viewport, renderer); if is_redraw_request { self.last_mouse_interaction = Some(mouse_interaction); } else if self .last_mouse_interaction .is_some_and(|last_mouse_interaction| last_mouse_interaction != mouse_interaction) { shell.request_redraw(); } } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let bounds = layout.bounds(); let state = tree.state.downcast_ref::<P::State>(); self.program.mouse_interaction(state, bounds, cursor) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, ) { let bounds = layout.bounds(); if bounds.width < 1.0 || bounds.height < 1.0 { return; } let state = tree.state.downcast_ref::<P::State>(); renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { let layers = self.program.draw(state, renderer, theme, bounds, cursor); for layer in layers { renderer.draw_geometry(layer); } }); } } impl<'a, P, Message, Theme, Renderer> From<Canvas<P, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: 'a + geometry::Renderer, P: 'a + Program<Message, Theme, Renderer>, { fn from(canvas: Canvas<P, Message, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> { Element::new(canvas) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/toggler.rs
widget/src/toggler.rs
//! Togglers let users make binary choices by toggling a switch. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::toggler; //! //! struct State { //! is_checked: bool, //! } //! //! enum Message { //! TogglerToggled(bool), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! toggler(state.is_checked) //! .label("Toggle me!") //! .on_toggle(Message::TogglerToggled) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::TogglerToggled(is_checked) => { //! state.is_checked = is_checked; //! } //! } //! } //! ``` use crate::core::alignment; use crate::core::border; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::text; use crate::core::touch; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Border, Clipboard, Color, Element, Event, Layout, Length, Pixels, Rectangle, Shell, Size, Theme, Widget, }; /// A toggler widget. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::toggler; /// /// struct State { /// is_checked: bool, /// } /// /// enum Message { /// TogglerToggled(bool), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// toggler(state.is_checked) /// .label("Toggle me!") /// .on_toggle(Message::TogglerToggled) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::TogglerToggled(is_checked) => { /// state.is_checked = is_checked; /// } /// } /// } /// ``` pub struct Toggler<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, { is_toggled: bool, on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>, label: Option<text::Fragment<'a>>, width: Length, size: f32, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_alignment: text::Alignment, text_shaping: text::Shaping, text_wrapping: text::Wrapping, spacing: f32, font: Option<Renderer::Font>, class: Theme::Class<'a>, last_status: Option<Status>, } impl<'a, Message, Theme, Renderer> Toggler<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { /// The default size of a [`Toggler`]. pub const DEFAULT_SIZE: f32 = 16.0; /// Creates a new [`Toggler`]. /// /// It expects: /// * a boolean describing whether the [`Toggler`] is checked or not /// * An optional label for the [`Toggler`] /// * a function that will be called when the [`Toggler`] is toggled. It /// will receive the new state of the [`Toggler`] and must produce a /// `Message`. pub fn new(is_toggled: bool) -> Self { Toggler { is_toggled, on_toggle: None, label: None, width: Length::Shrink, size: Self::DEFAULT_SIZE, text_size: None, text_line_height: text::LineHeight::default(), text_alignment: text::Alignment::Default, text_shaping: text::Shaping::default(), text_wrapping: text::Wrapping::default(), spacing: Self::DEFAULT_SIZE / 2.0, font: None, class: Theme::default(), last_status: None, } } /// Sets the label of the [`Toggler`]. pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self { self.label = Some(label.into_fragment()); self } /// Sets the message that should be produced when a user toggles /// the [`Toggler`]. /// /// If this method is not called, the [`Toggler`] will be disabled. pub fn on_toggle(mut self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self { self.on_toggle = Some(Box::new(on_toggle)); self } /// Sets the message that should be produced when a user toggles /// the [`Toggler`], if `Some`. /// /// If `None`, the [`Toggler`] will be disabled. pub fn on_toggle_maybe(mut self, on_toggle: Option<impl Fn(bool) -> Message + 'a>) -> Self { self.on_toggle = on_toggle.map(|on_toggle| Box::new(on_toggle) as _); self } /// Sets the size of the [`Toggler`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = size.into().0; self } /// Sets the width of the [`Toggler`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the text size o the [`Toggler`]. pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self { self.text_size = Some(text_size.into()); self } /// Sets the text [`text::LineHeight`] of the [`Toggler`]. pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.text_line_height = line_height.into(); self } /// Sets the horizontal alignment of the text of the [`Toggler`] pub fn text_alignment(mut self, alignment: impl Into<text::Alignment>) -> Self { self.text_alignment = alignment.into(); self } /// Sets the [`text::Shaping`] strategy of the [`Toggler`]. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the [`text::Wrapping`] strategy of the [`Toggler`]. pub fn text_wrapping(mut self, wrapping: text::Wrapping) -> Self { self.text_wrapping = wrapping; self } /// Sets the spacing between the [`Toggler`] and the text. pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self { self.spacing = spacing.into().0; self } /// Sets the [`Renderer::Font`] of the text of the [`Toggler`] /// /// [`Renderer::Font`]: crate::core::text::Renderer pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the style of the [`Toggler`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Toggler`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Toggler<'_, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<widget::text::State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(widget::text::State::<Renderer::Paragraph>::default()) } fn size(&self) -> Size<Length> { Size { width: self.width, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let limits = limits.width(self.width); layout::next_to_each_other( &limits, if self.label.is_some() { self.spacing } else { 0.0 }, |_| { let size = if renderer::CRISP { let scale_factor = renderer.scale_factor().unwrap_or(1.0); (self.size * scale_factor).round() / scale_factor } else { self.size }; layout::Node::new(Size::new(2.0 * size, size)) }, |limits| { if let Some(label) = self.label.as_deref() { let state = tree .state .downcast_mut::<widget::text::State<Renderer::Paragraph>>(); widget::text::layout( state, renderer, limits, label, widget::text::Format { width: self.width, height: Length::Shrink, line_height: self.text_line_height, size: self.text_size, font: self.font, align_x: self.text_alignment, align_y: alignment::Vertical::Top, shaping: self.text_shaping, wrapping: self.text_wrapping, }, ) } else { layout::Node::new(Size::ZERO) } }, ) } 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 Some(on_toggle) = &self.on_toggle else { return; }; match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let mouse_over = cursor.is_over(layout.bounds()); if mouse_over { shell.publish(on_toggle(!self.is_toggled)); shell.capture_event(); } } _ => {} } let current_status = if self.on_toggle.is_none() { Status::Disabled { is_toggled: self.is_toggled, } } else if cursor.is_over(layout.bounds()) { Status::Hovered { is_toggled: self.is_toggled, } } else { Status::Active { is_toggled: self.is_toggled, } }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.last_status = Some(current_status); } else if self .last_status .is_some_and(|status| status != current_status) { shell.request_redraw(); } } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { if cursor.is_over(layout.bounds()) { if self.on_toggle.is_some() { mouse::Interaction::Pointer } else { mouse::Interaction::NotAllowed } } else { mouse::Interaction::default() } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let mut children = layout.children(); let toggler_layout = children.next().unwrap(); let style = theme.style( &self.class, self.last_status.unwrap_or(Status::Disabled { is_toggled: self.is_toggled, }), ); if self.label.is_some() { let label_layout = children.next().unwrap(); let state: &widget::text::State<Renderer::Paragraph> = tree.state.downcast_ref(); crate::text::draw( renderer, defaults, label_layout.bounds(), state.raw(), crate::text::Style { color: style.text_color, }, viewport, ); } let scale_factor = renderer.scale_factor().unwrap_or(1.0); let bounds = toggler_layout.bounds(); let border_radius = style .border_radius .unwrap_or_else(|| border::Radius::new(bounds.height / 2.0)); renderer.fill_quad( renderer::Quad { bounds, border: Border { radius: border_radius, width: style.background_border_width, color: style.background_border_color, }, ..renderer::Quad::default() }, style.background, ); let toggle_bounds = { // Try to align toggle to the pixel grid let bounds = if renderer::CRISP { (bounds * scale_factor).round() } else { bounds }; let padding = (style.padding_ratio * bounds.height).round(); Rectangle { x: bounds.x + if self.is_toggled { bounds.width - bounds.height + padding } else { padding }, y: bounds.y + padding, width: bounds.height - (2.0 * padding), height: bounds.height - (2.0 * padding), } * (1.0 / scale_factor) }; renderer.fill_quad( renderer::Quad { bounds: toggle_bounds, border: Border { radius: border_radius, width: style.foreground_border_width, color: style.foreground_border_color, }, ..renderer::Quad::default() }, style.foreground, ); } } impl<'a, Message, Theme, Renderer> From<Toggler<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn from( toggler: Toggler<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(toggler) } } /// The possible status of a [`Toggler`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Toggler`] can be interacted with. Active { /// Indicates whether the [`Toggler`] is toggled. is_toggled: bool, }, /// The [`Toggler`] is being hovered. Hovered { /// Indicates whether the [`Toggler`] is toggled. is_toggled: bool, }, /// The [`Toggler`] is disabled. Disabled { /// Indicates whether the [`Toggler`] is toggled. is_toggled: bool, }, } /// The appearance of a toggler. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The background [`Color`] of the toggler. pub background: Background, /// The width of the background border of the toggler. pub background_border_width: f32, /// The [`Color`] of the background border of the toggler. pub background_border_color: Color, /// The foreground [`Color`] of the toggler. pub foreground: Background, /// The width of the foreground border of the toggler. pub foreground_border_width: f32, /// The [`Color`] of the foreground border of the toggler. pub foreground_border_color: Color, /// The text [`Color`] of the toggler. pub text_color: Option<Color>, /// The border radius of the toggler. /// /// If `None`, the toggler will be perfectly round. pub border_radius: Option<border::Radius>, /// The ratio of separation between the background and the toggle in relative height. pub padding_ratio: f32, } /// The theme catalog of a [`Toggler`]. pub trait Catalog: Sized { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } /// A styling function for a [`Toggler`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// The default style of a [`Toggler`]. pub fn default(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let background = match status { Status::Active { is_toggled } | Status::Hovered { is_toggled } => { if is_toggled { palette.primary.base.color } else { palette.background.strong.color } } Status::Disabled { is_toggled } => { if is_toggled { palette.background.strong.color } else { palette.background.weak.color } } }; let foreground = match status { Status::Active { is_toggled } => { if is_toggled { palette.primary.base.text } else { palette.background.base.color } } Status::Hovered { is_toggled } => { if is_toggled { Color { a: 0.5, ..palette.primary.base.text } } else { palette.background.weak.color } } Status::Disabled { .. } => palette.background.weakest.color, }; Style { background: background.into(), foreground: foreground.into(), foreground_border_width: 0.0, foreground_border_color: Color::TRANSPARENT, background_border_width: 0.0, background_border_color: Color::TRANSPARENT, text_color: None, border_radius: None, padding_ratio: 0.1, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text.rs
widget/src/text.rs
//! Draw and interact with text. mod rich; pub use crate::core::text::{Fragment, Highlighter, IntoFragment, Span}; pub use crate::core::widget::text::*; pub use rich::Rich; /// A bunch of text. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::text; /// use iced::color; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// text("Hello, this is iced!") /// .size(20) /// .color(color!(0x0000ff)) /// .into() /// } /// ``` pub type Text<'a, Theme = crate::Theme, Renderer = crate::Renderer> = crate::core::widget::Text<'a, Theme, Renderer>;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/combo_box.rs
widget/src/combo_box.rs
//! Combo boxes display a dropdown list of searchable and selectable options. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::combo_box; //! //! struct State { //! fruits: combo_box::State<Fruit>, //! favorite: Option<Fruit>, //! } //! //! #[derive(Debug, Clone)] //! enum Fruit { //! Apple, //! Orange, //! Strawberry, //! Tomato, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! FruitSelected(Fruit), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! combo_box( //! &state.fruits, //! "Select your favorite fruit...", //! state.favorite.as_ref(), //! Message::FruitSelected //! ) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::FruitSelected(fruit) => { //! state.favorite = Some(fruit); //! } //! } //! } //! //! impl std::fmt::Display for Fruit { //! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { //! f.write_str(match self { //! Self::Apple => "Apple", //! Self::Orange => "Orange", //! Self::Strawberry => "Strawberry", //! Self::Tomato => "Tomato", //! }) //! } //! } //! ``` use crate::core::keyboard; use crate::core::keyboard::key; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::text; use crate::core::time::Instant; use crate::core::widget::{self, Widget}; use crate::core::{ Clipboard, Element, Event, Length, Padding, Pixels, Rectangle, Shell, Size, Theme, Vector, }; use crate::overlay::menu; use crate::text::LineHeight; use crate::text_input::{self, TextInput}; use std::cell::RefCell; use std::fmt::Display; /// A widget for searching and selecting a single value from a list of options. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::combo_box; /// /// struct State { /// fruits: combo_box::State<Fruit>, /// favorite: Option<Fruit>, /// } /// /// #[derive(Debug, Clone)] /// enum Fruit { /// Apple, /// Orange, /// Strawberry, /// Tomato, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// FruitSelected(Fruit), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// combo_box( /// &state.fruits, /// "Select your favorite fruit...", /// state.favorite.as_ref(), /// Message::FruitSelected /// ) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::FruitSelected(fruit) => { /// state.favorite = Some(fruit); /// } /// } /// } /// /// impl std::fmt::Display for Fruit { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// f.write_str(match self { /// Self::Apple => "Apple", /// Self::Orange => "Orange", /// Self::Strawberry => "Strawberry", /// Self::Tomato => "Tomato", /// }) /// } /// } /// ``` pub struct ComboBox<'a, T, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, { state: &'a State<T>, text_input: TextInput<'a, TextInputEvent, Theme, Renderer>, font: Option<Renderer::Font>, selection: text_input::Value, on_selected: Box<dyn Fn(T) -> Message>, on_option_hovered: Option<Box<dyn Fn(T) -> Message>>, on_open: Option<Message>, on_close: Option<Message>, on_input: Option<Box<dyn Fn(String) -> Message>>, padding: Padding, size: Option<f32>, text_shaping: text::Shaping, menu_class: <Theme as menu::Catalog>::Class<'a>, menu_height: Length, } impl<'a, T, Message, Theme, Renderer> ComboBox<'a, T, Message, Theme, Renderer> where T: std::fmt::Display + Clone, Theme: Catalog, Renderer: text::Renderer, { /// Creates a new [`ComboBox`] with the given list of options, a placeholder, /// the current selected value, and the message to produce when an option is /// selected. pub fn new( state: &'a State<T>, placeholder: &str, selection: Option<&T>, on_selected: impl Fn(T) -> Message + 'static, ) -> Self { let text_input = TextInput::new(placeholder, &state.value()) .on_input(TextInputEvent::TextChanged) .class(Theme::default_input()); let selection = selection.map(T::to_string).unwrap_or_default(); Self { state, text_input, font: None, selection: text_input::Value::new(&selection), on_selected: Box::new(on_selected), on_option_hovered: None, on_input: None, on_open: None, on_close: None, padding: text_input::DEFAULT_PADDING, size: None, text_shaping: text::Shaping::default(), menu_class: <Theme as Catalog>::default_menu(), menu_height: Length::Shrink, } } /// Sets the message that should be produced when some text is typed into /// the [`TextInput`] of the [`ComboBox`]. pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'static) -> Self { self.on_input = Some(Box::new(on_input)); self } /// Sets the message that will be produced when an option of the /// [`ComboBox`] is hovered using the arrow keys. pub fn on_option_hovered(mut self, on_option_hovered: impl Fn(T) -> Message + 'static) -> Self { self.on_option_hovered = Some(Box::new(on_option_hovered)); self } /// Sets the message that will be produced when the [`ComboBox`] is /// opened. pub fn on_open(mut self, message: Message) -> Self { self.on_open = Some(message); self } /// Sets the message that will be produced when the outside area /// of the [`ComboBox`] is pressed. pub fn on_close(mut self, message: Message) -> Self { self.on_close = Some(message); self } /// Sets the [`Padding`] of the [`ComboBox`]. pub fn padding(mut self, padding: impl Into<Padding>) -> Self { self.padding = padding.into(); self.text_input = self.text_input.padding(self.padding); self } /// Sets the [`Renderer::Font`] of the [`ComboBox`]. /// /// [`Renderer::Font`]: text::Renderer pub fn font(mut self, font: Renderer::Font) -> Self { self.text_input = self.text_input.font(font); self.font = Some(font); self } /// Sets the [`text_input::Icon`] of the [`ComboBox`]. pub fn icon(mut self, icon: text_input::Icon<Renderer::Font>) -> Self { self.text_input = self.text_input.icon(icon); self } /// Sets the text sixe of the [`ComboBox`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { let size = size.into(); self.text_input = self.text_input.size(size); self.size = Some(size.0); self } /// Sets the [`LineHeight`] of the [`ComboBox`]. pub fn line_height(self, line_height: impl Into<LineHeight>) -> Self { Self { text_input: self.text_input.line_height(line_height), ..self } } /// Sets the width of the [`ComboBox`]. pub fn width(self, width: impl Into<Length>) -> Self { Self { text_input: self.text_input.width(width), ..self } } /// Sets the height of the menu of the [`ComboBox`]. pub fn menu_height(mut self, menu_height: impl Into<Length>) -> Self { self.menu_height = menu_height.into(); self } /// Sets the [`text::Shaping`] strategy of the [`ComboBox`]. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the style of the input of the [`ComboBox`]. #[must_use] pub fn input_style( mut self, style: impl Fn(&Theme, text_input::Status) -> text_input::Style + 'a, ) -> Self where <Theme as text_input::Catalog>::Class<'a>: From<text_input::StyleFn<'a, Theme>>, { self.text_input = self.text_input.style(style); self } /// Sets the style of the menu of the [`ComboBox`]. #[must_use] pub fn menu_style(mut self, style: impl Fn(&Theme) -> menu::Style + 'a) -> Self where <Theme as menu::Catalog>::Class<'a>: From<menu::StyleFn<'a, Theme>>, { self.menu_class = (Box::new(style) as menu::StyleFn<'a, Theme>).into(); self } /// Sets the style class of the input of the [`ComboBox`]. #[cfg(feature = "advanced")] #[must_use] pub fn input_class( mut self, class: impl Into<<Theme as text_input::Catalog>::Class<'a>>, ) -> Self { self.text_input = self.text_input.class(class); self } /// Sets the style class of the menu of the [`ComboBox`]. #[cfg(feature = "advanced")] #[must_use] pub fn menu_class(mut self, class: impl Into<<Theme as menu::Catalog>::Class<'a>>) -> Self { self.menu_class = class.into(); self } } /// The local state of a [`ComboBox`]. #[derive(Debug, Clone)] pub struct State<T> { options: Vec<T>, inner: RefCell<Inner<T>>, } #[derive(Debug, Clone)] struct Inner<T> { value: String, option_matchers: Vec<String>, filtered_options: Filtered<T>, } #[derive(Debug, Clone)] struct Filtered<T> { options: Vec<T>, updated: Instant, } impl<T> State<T> where T: Display + Clone, { /// Creates a new [`State`] for a [`ComboBox`] with the given list of options. pub fn new(options: Vec<T>) -> Self { Self::with_selection(options, None) } /// Creates a new [`State`] for a [`ComboBox`] with the given list of options /// and selected value. pub fn with_selection(options: Vec<T>, selection: Option<&T>) -> Self { let value = selection.map(T::to_string).unwrap_or_default(); // Pre-build "matcher" strings ahead of time so that search is fast let option_matchers = build_matchers(&options); let filtered_options = Filtered::new( search(&options, &option_matchers, &value) .cloned() .collect(), ); Self { options, inner: RefCell::new(Inner { value, option_matchers, filtered_options, }), } } /// Returns the options of the [`State`]. /// /// These are the options provided when the [`State`] /// was constructed with [`State::new`]. pub fn options(&self) -> &[T] { &self.options } /// Pushes a new option to the [`State`]. pub fn push(&mut self, new_option: T) { let mut inner = self.inner.borrow_mut(); inner.option_matchers.push(build_matcher(&new_option)); self.options.push(new_option); inner.filtered_options = Filtered::new( search(&self.options, &inner.option_matchers, &inner.value) .cloned() .collect(), ); } /// Returns ownership of the options of the [`State`]. pub fn into_options(self) -> Vec<T> { self.options } fn value(&self) -> String { let inner = self.inner.borrow(); inner.value.clone() } fn with_inner<O>(&self, f: impl FnOnce(&Inner<T>) -> O) -> O { let inner = self.inner.borrow(); f(&inner) } fn with_inner_mut(&self, f: impl FnOnce(&mut Inner<T>)) { let mut inner = self.inner.borrow_mut(); f(&mut inner); } fn sync_filtered_options(&self, options: &mut Filtered<T>) { let inner = self.inner.borrow(); inner.filtered_options.sync(options); } } impl<T> Default for State<T> where T: Display + Clone, { fn default() -> Self { Self::new(Vec::new()) } } impl<T> Filtered<T> where T: Clone, { fn new(options: Vec<T>) -> Self { Self { options, updated: Instant::now(), } } fn empty() -> Self { Self { options: vec![], updated: Instant::now(), } } fn update(&mut self, options: Vec<T>) { self.options = options; self.updated = Instant::now(); } fn sync(&self, other: &mut Filtered<T>) { if other.updated != self.updated { *other = self.clone(); } } } struct Menu<T> { menu: menu::State, hovered_option: Option<usize>, new_selection: Option<T>, filtered_options: Filtered<T>, } #[derive(Debug, Clone)] enum TextInputEvent { TextChanged(String), } impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for ComboBox<'_, T, Message, Theme, Renderer> where T: Display + Clone + 'static, Message: Clone, Theme: Catalog, Renderer: text::Renderer, { fn size(&self) -> Size<Length> { Widget::<TextInputEvent, Theme, Renderer>::size(&self.text_input) } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let is_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; self.text_input.layout( &mut tree.children[0], renderer, limits, (!is_focused).then_some(&self.selection), ) } fn tag(&self) -> widget::tree::Tag { widget::tree::Tag::of::<Menu<T>>() } fn state(&self) -> widget::tree::State { widget::tree::State::new(Menu::<T> { menu: menu::State::new(), filtered_options: Filtered::empty(), hovered_option: Some(0), new_selection: None, }) } fn children(&self) -> Vec<widget::Tree> { vec![widget::Tree::new(&self.text_input as &dyn Widget<_, _, _>)] } fn diff(&self, _tree: &mut widget::Tree) { // do nothing so the children don't get cleared } fn update( &mut self, tree: &mut widget::Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { let menu = tree.state.downcast_mut::<Menu<T>>(); let started_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; // This is intended to check whether or not the message buffer was empty, // since `Shell` does not expose such functionality. let mut published_message_to_shell = false; // Create a new list of local messages let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); // Provide it to the widget self.text_input.update( &mut tree.children[0], event, layout, cursor, renderer, clipboard, &mut local_shell, viewport, ); if local_shell.is_event_captured() { shell.capture_event(); } shell.request_redraw_at(local_shell.redraw_request()); shell.request_input_method(local_shell.input_method()); // Then finally react to them here for message in local_messages { let TextInputEvent::TextChanged(new_value) = message; if let Some(on_input) = &self.on_input { shell.publish((on_input)(new_value.clone())); } // Couple the filtered options with the `ComboBox` // value and only recompute them when the value changes, // instead of doing it in every `view` call self.state.with_inner_mut(|state| { menu.hovered_option = Some(0); state.value = new_value; state.filtered_options.update( search(&self.state.options, &state.option_matchers, &state.value) .cloned() .collect(), ); }); shell.invalidate_layout(); shell.request_redraw(); } let is_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; if is_focused { self.state.with_inner(|state| { if !started_focused && let Some(on_option_hovered) = &mut self.on_option_hovered { let hovered_option = menu.hovered_option.unwrap_or(0); if let Some(option) = state.filtered_options.options.get(hovered_option) { shell.publish(on_option_hovered(option.clone())); published_message_to_shell = true; } } if let Event::Keyboard(keyboard::Event::KeyPressed { key: keyboard::Key::Named(named_key), modifiers, .. }) = event { let shift_modifier = modifiers.shift(); match (named_key, shift_modifier) { (key::Named::Enter, _) => { if let Some(index) = &menu.hovered_option && let Some(option) = state.filtered_options.options.get(*index) { menu.new_selection = Some(option.clone()); } shell.capture_event(); shell.request_redraw(); } (key::Named::ArrowUp, _) | (key::Named::Tab, true) => { if let Some(index) = &mut menu.hovered_option { if *index == 0 { *index = state.filtered_options.options.len().saturating_sub(1); } else { *index = index.saturating_sub(1); } } else { menu.hovered_option = Some(0); } if let Some(on_option_hovered) = &mut self.on_option_hovered && let Some(option) = menu .hovered_option .and_then(|index| state.filtered_options.options.get(index)) { // Notify the selection shell.publish((on_option_hovered)(option.clone())); published_message_to_shell = true; } shell.capture_event(); shell.request_redraw(); } (key::Named::ArrowDown, _) | (key::Named::Tab, false) if !modifiers.shift() => { if let Some(index) = &mut menu.hovered_option { if *index >= state.filtered_options.options.len().saturating_sub(1) { *index = 0; } else { *index = index.saturating_add(1).min( state.filtered_options.options.len().saturating_sub(1), ); } } else { menu.hovered_option = Some(0); } if let Some(on_option_hovered) = &mut self.on_option_hovered && let Some(option) = menu .hovered_option .and_then(|index| state.filtered_options.options.get(index)) { // Notify the selection shell.publish((on_option_hovered)(option.clone())); published_message_to_shell = true; } shell.capture_event(); shell.request_redraw(); } _ => {} } } }); } // If the overlay menu has selected something self.state.with_inner_mut(|state| { if let Some(selection) = menu.new_selection.take() { // Clear the value and reset the options and menu state.value = String::new(); state.filtered_options.update(self.state.options.clone()); menu.menu = menu::State::default(); // Notify the selection shell.publish((self.on_selected)(selection)); published_message_to_shell = true; // Unfocus the input let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); self.text_input.update( &mut tree.children[0], &Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)), layout, mouse::Cursor::Unavailable, renderer, clipboard, &mut local_shell, viewport, ); shell.request_input_method(local_shell.input_method()); } }); let is_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; if started_focused != is_focused { // Focus changed, invalidate widget tree to force a fresh `view` shell.invalidate_widgets(); if !published_message_to_shell { if is_focused { if let Some(on_open) = self.on_open.take() { shell.publish(on_open); } } else if let Some(on_close) = self.on_close.take() { shell.publish(on_close); } } } } fn mouse_interaction( &self, tree: &widget::Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.text_input .mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer) } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let is_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; let selection = if is_focused || self.selection.is_empty() { None } else { Some(&self.selection) }; self.text_input.draw( &tree.children[0], renderer, theme, layout, cursor, selection, viewport, ); } fn overlay<'b>( &'b mut self, tree: &'b mut widget::Tree, layout: Layout<'_>, _renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { let is_focused = { let text_input_state = tree.children[0] .state .downcast_ref::<text_input::State<Renderer::Paragraph>>(); text_input_state.is_focused() }; if is_focused { let Menu { menu, filtered_options, hovered_option, .. } = tree.state.downcast_mut::<Menu<T>>(); self.state.sync_filtered_options(filtered_options); if filtered_options.options.is_empty() { None } else { let bounds = layout.bounds(); let mut menu = menu::Menu::new( menu, &filtered_options.options, hovered_option, |selection| { self.state.with_inner_mut(|state| { state.value = String::new(); state.filtered_options.update(self.state.options.clone()); }); tree.children[0] .state .downcast_mut::<text_input::State<Renderer::Paragraph>>() .unfocus(); (self.on_selected)(selection) }, self.on_option_hovered.as_deref(), &self.menu_class, ) .width(bounds.width) .padding(self.padding) .text_shaping(self.text_shaping); if let Some(font) = self.font { menu = menu.font(font); } if let Some(size) = self.size { menu = menu.text_size(size); } Some(menu.overlay( layout.position() + translation, *viewport, bounds.height, self.menu_height, )) } } else { None } } } impl<'a, T, Message, Theme, Renderer> From<ComboBox<'a, T, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where T: Display + Clone + 'static, Message: Clone + 'a, Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn from(combo_box: ComboBox<'a, T, Message, Theme, Renderer>) -> Self { Self::new(combo_box) } } /// The theme catalog of a [`ComboBox`]. pub trait Catalog: text_input::Catalog + menu::Catalog { /// The default class for the text input of the [`ComboBox`]. fn default_input<'a>() -> <Self as text_input::Catalog>::Class<'a> { <Self as text_input::Catalog>::default() } /// The default class for the menu of the [`ComboBox`]. fn default_menu<'a>() -> <Self as menu::Catalog>::Class<'a> { <Self as menu::Catalog>::default() } } impl Catalog for Theme {} fn search<'a, T, A>( options: impl IntoIterator<Item = T> + 'a, option_matchers: impl IntoIterator<Item = &'a A> + 'a, query: &'a str, ) -> impl Iterator<Item = T> + 'a where A: AsRef<str> + 'a, { let query: Vec<String> = query .to_lowercase() .split(|c: char| !c.is_ascii_alphanumeric()) .map(String::from) .collect(); options .into_iter() .zip(option_matchers) // Make sure each part of the query is found in the option .filter_map(move |(option, matcher)| { if query.iter().all(|part| matcher.as_ref().contains(part)) { Some(option) } else { None } }) } fn build_matchers<'a, T>(options: impl IntoIterator<Item = T> + 'a) -> Vec<String> where T: Display + 'a, { options.into_iter().map(build_matcher).collect() } fn build_matcher<T>(option: T) -> String where T: Display, { let mut matcher = option.to_string(); matcher.retain(|c| c.is_ascii_alphanumeric()); matcher.to_lowercase() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/grid.rs
widget/src/grid.rs
//! Distribute content on a grid. use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ Clipboard, Element, Event, Length, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents on a responsive grid. pub struct Grid<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { spacing: f32, columns: Constraint, width: Option<Pixels>, height: Sizing, children: Vec<Element<'a, Message, Theme, Renderer>>, } enum Constraint { MaxWidth(Pixels), Amount(usize), } impl<'a, Message, Theme, Renderer> Grid<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Creates an empty [`Grid`]. pub fn new() -> Self { Self::from_vec(Vec::new()) } /// Creates a [`Grid`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { Self::from_vec(Vec::with_capacity(capacity)) } /// Creates a [`Grid`] with the given elements. pub fn with_children( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { let iterator = children.into_iter(); Self::with_capacity(iterator.size_hint().0).extend(iterator) } /// Creates a [`Grid`] from an already allocated [`Vec`]. pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self { Self { spacing: 0.0, columns: Constraint::Amount(3), width: None, height: Sizing::AspectRatio(1.0), children, } } /// Sets the spacing _between_ cells in the [`Grid`]. pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self { self.spacing = amount.into().0; self } /// Sets the width of the [`Grid`] in [`Pixels`]. /// /// By default, a [`Grid`] will [`Fill`] its parent. /// /// [`Fill`]: Length::Fill pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = Some(width.into()); self } /// Sets the height of the [`Grid`]. /// /// By default, a [`Grid`] uses a cell aspect ratio of `1.0` (i.e. squares). pub fn height(mut self, height: impl Into<Sizing>) -> Self { self.height = height.into(); self } /// Sets the amount of columns in the [`Grid`]. pub fn columns(mut self, column: usize) -> Self { self.columns = Constraint::Amount(column); self } /// Makes the amount of columns dynamic in the [`Grid`], never /// exceeding the provided `max_width`. pub fn fluid(mut self, max_width: impl Into<Pixels>) -> Self { self.columns = Constraint::MaxWidth(max_width.into()); self } /// Adds an [`Element`] to the [`Grid`]. pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { self.children.push(child.into()); self } /// Adds an element to the [`Grid`], if `Some`. pub fn push_maybe( self, child: Option<impl Into<Element<'a, Message, Theme, Renderer>>>, ) -> Self { if let Some(child) = child { self.push(child) } else { self } } /// Extends the [`Grid`] with the given children. pub fn extend( self, children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { children.into_iter().fold(self, Self::push) } } impl<Message, Renderer> Default for Grid<'_, Message, Renderer> where Renderer: crate::core::Renderer, { fn default() -> Self { Self::new() } } impl<'a, Message, Theme, Renderer: crate::core::Renderer> FromIterator<Element<'a, Message, Theme, Renderer>> for Grid<'a, Message, Theme, Renderer> { fn from_iter<T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>>(iter: T) -> Self { Self::with_children(iter) } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Grid<'_, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.children.iter().map(Tree::new).collect() } fn diff(&self, tree: &mut Tree) { tree.diff_children(&self.children); } fn size(&self) -> Size<Length> { Size { width: self .width .map(|pixels| Length::Fixed(pixels.0)) .unwrap_or(Length::Fill), height: match self.height { Sizing::AspectRatio(_) => Length::Shrink, Sizing::EvenlyDistribute(length) => length, }, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let size = self.size(); let limits = limits.width(size.width).height(size.height); let available = limits.max(); let cells_per_row = match self.columns { // width = n * (cell + spacing) - spacing, given n > 0 Constraint::MaxWidth(pixels) => { ((available.width + self.spacing) / (pixels.0 + self.spacing)).ceil() as usize } Constraint::Amount(amount) => amount, }; if self.children.is_empty() || cells_per_row == 0 { return layout::Node::new(limits.resolve(size.width, size.height, Size::ZERO)); } let cell_width = (available.width - self.spacing * (cells_per_row - 1) as f32) / cells_per_row as f32; let cell_height = match self.height { Sizing::AspectRatio(ratio) => Some(cell_width / ratio), Sizing::EvenlyDistribute(Length::Shrink) => None, Sizing::EvenlyDistribute(_) => { let total_rows = self.children.len().div_ceil(cells_per_row); Some( (available.height - self.spacing * (total_rows - 1) as f32) / total_rows as f32, ) } }; let cell_limits = layout::Limits::new( Size::new(cell_width, cell_height.unwrap_or(0.0)), Size::new(cell_width, cell_height.unwrap_or(available.height)), ); let mut nodes = Vec::with_capacity(self.children.len()); let mut x = 0.0; let mut y = 0.0; let mut row_height = 0.0f32; for (i, (child, tree)) in self.children.iter_mut().zip(&mut tree.children).enumerate() { let node = child .as_widget_mut() .layout(tree, renderer, &cell_limits) .move_to((x, y)); let size = node.size(); x += size.width + self.spacing; row_height = row_height.max(size.height); if (i + 1) % cells_per_row == 0 { y += cell_height.unwrap_or(row_height) + self.spacing; x = 0.0; row_height = 0.0; } nodes.push(node); } if x == 0.0 { y -= self.spacing; } else { y += cell_height.unwrap_or(row_height); } layout::Node::with_children(Size::new(available.width, y), nodes) } 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.children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, 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, ) { for ((child, tree), layout) in self .children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { child.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .zip(&tree.children) .zip(layout.children()) .map(|((child, tree), layout)| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if let Some(viewport) = layout.bounds().intersection(viewport) { for ((child, tree), layout) in self .children .iter() .zip(&tree.children) .zip(layout.children()) .filter(|(_, layout)| layout.bounds().intersects(&viewport)) { child .as_widget() .draw(tree, renderer, theme, style, layout, cursor, &viewport); } } } 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>> { overlay::from_children( &mut self.children, tree, layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Grid<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(row: Grid<'a, Message, Theme, Renderer>) -> Self { Self::new(row) } } /// The sizing strategy of a [`Grid`]. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Sizing { /// The [`Grid`] will ensure each cell follows the given aspect ratio and the /// total size will be the sum of the cells and the spacing between them. /// /// The ratio is the amount of horizontal pixels per each vertical pixel of a cell /// in the [`Grid`]. AspectRatio(f32), /// The [`Grid`] will evenly distribute the space available in the given [`Length`] /// for each cell. EvenlyDistribute(Length), } impl From<f32> for Sizing { fn from(height: f32) -> Self { Self::EvenlyDistribute(Length::from(height)) } } impl From<Length> for Sizing { fn from(height: Length) -> Self { Self::EvenlyDistribute(height) } } /// Creates a new [`Sizing`] strategy that maintains the given aspect ratio. pub fn aspect_ratio(width: impl Into<Pixels>, height: impl Into<Pixels>) -> Sizing { Sizing::AspectRatio(width.into().0 / height.into().0) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pick_list.rs
widget/src/pick_list.rs
//! Pick lists display a dropdown list of selectable options. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::pick_list; //! //! struct State { //! favorite: Option<Fruit>, //! } //! //! #[derive(Debug, Clone, Copy, PartialEq, Eq)] //! enum Fruit { //! Apple, //! Orange, //! Strawberry, //! Tomato, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! FruitSelected(Fruit), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! let fruits = [ //! Fruit::Apple, //! Fruit::Orange, //! Fruit::Strawberry, //! Fruit::Tomato, //! ]; //! //! pick_list( //! fruits, //! state.favorite, //! Message::FruitSelected, //! ) //! .placeholder("Select your favorite fruit...") //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::FruitSelected(fruit) => { //! state.favorite = Some(fruit); //! } //! } //! } //! //! impl std::fmt::Display for Fruit { //! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { //! f.write_str(match self { //! Self::Apple => "Apple", //! Self::Orange => "Orange", //! Self::Strawberry => "Strawberry", //! Self::Tomato => "Tomato", //! }) //! } //! } //! ``` use crate::core::alignment; use crate::core::keyboard; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::text::paragraph; use crate::core::text::{self, Text}; use crate::core::touch; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Border, Clipboard, Color, Element, Event, Layout, Length, Padding, Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget, }; use crate::overlay::menu::{self, Menu}; use std::borrow::Borrow; use std::f32; /// A widget for selecting a single value from a list of options. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::pick_list; /// /// struct State { /// favorite: Option<Fruit>, /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Fruit { /// Apple, /// Orange, /// Strawberry, /// Tomato, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// FruitSelected(Fruit), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// let fruits = [ /// Fruit::Apple, /// Fruit::Orange, /// Fruit::Strawberry, /// Fruit::Tomato, /// ]; /// /// pick_list( /// fruits, /// state.favorite, /// Message::FruitSelected, /// ) /// .placeholder("Select your favorite fruit...") /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::FruitSelected(fruit) => { /// state.favorite = Some(fruit); /// } /// } /// } /// /// impl std::fmt::Display for Fruit { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// f.write_str(match self { /// Self::Apple => "Apple", /// Self::Orange => "Orange", /// Self::Strawberry => "Strawberry", /// Self::Tomato => "Tomato", /// }) /// } /// } /// ``` pub struct PickList<'a, T, L, V, Message, Theme = crate::Theme, Renderer = crate::Renderer> where T: ToString + PartialEq + Clone, L: Borrow<[T]> + 'a, V: Borrow<T> + 'a, Theme: Catalog, Renderer: text::Renderer, { on_select: Box<dyn Fn(T) -> Message + 'a>, on_open: Option<Message>, on_close: Option<Message>, options: L, placeholder: Option<String>, selected: Option<V>, width: Length, padding: Padding, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_shaping: text::Shaping, font: Option<Renderer::Font>, handle: Handle<Renderer::Font>, class: <Theme as Catalog>::Class<'a>, menu_class: <Theme as menu::Catalog>::Class<'a>, last_status: Option<Status>, menu_height: Length, } impl<'a, T, L, V, Message, Theme, Renderer> PickList<'a, T, L, V, Message, Theme, Renderer> where T: ToString + PartialEq + Clone, L: Borrow<[T]> + 'a, V: Borrow<T> + 'a, Message: Clone, Theme: Catalog, Renderer: text::Renderer, { /// Creates a new [`PickList`] with the given list of options, the current /// selected value, and the message to produce when an option is selected. pub fn new(options: L, selected: Option<V>, on_select: impl Fn(T) -> Message + 'a) -> Self { Self { on_select: Box::new(on_select), on_open: None, on_close: None, options, placeholder: None, selected, width: Length::Shrink, padding: crate::button::DEFAULT_PADDING, text_size: None, text_line_height: text::LineHeight::default(), text_shaping: text::Shaping::default(), font: None, handle: Handle::default(), class: <Theme as Catalog>::default(), menu_class: <Theme as Catalog>::default_menu(), last_status: None, menu_height: Length::Shrink, } } /// Sets the placeholder of the [`PickList`]. pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self { self.placeholder = Some(placeholder.into()); self } /// Sets the width of the [`PickList`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Menu`]. pub fn menu_height(mut self, menu_height: impl Into<Length>) -> Self { self.menu_height = menu_height.into(); self } /// Sets the [`Padding`] of the [`PickList`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the text size of the [`PickList`]. pub fn text_size(mut self, size: impl Into<Pixels>) -> Self { self.text_size = Some(size.into()); self } /// Sets the text [`text::LineHeight`] of the [`PickList`]. pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.text_line_height = line_height.into(); self } /// Sets the [`text::Shaping`] strategy of the [`PickList`]. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the font of the [`PickList`]. pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the [`Handle`] of the [`PickList`]. pub fn handle(mut self, handle: Handle<Renderer::Font>) -> Self { self.handle = handle; self } /// Sets the message that will be produced when the [`PickList`] is opened. pub fn on_open(mut self, on_open: Message) -> Self { self.on_open = Some(on_open); self } /// Sets the message that will be produced when the [`PickList`] is closed. pub fn on_close(mut self, on_close: Message) -> Self { self.on_close = Some(on_close); self } /// Sets the style of the [`PickList`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where <Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style of the [`Menu`]. #[must_use] pub fn menu_style(mut self, style: impl Fn(&Theme) -> menu::Style + 'a) -> Self where <Theme as menu::Catalog>::Class<'a>: From<menu::StyleFn<'a, Theme>>, { self.menu_class = (Box::new(style) as menu::StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`PickList`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<<Theme as Catalog>::Class<'a>>) -> Self { self.class = class.into(); self } /// Sets the style class of the [`Menu`]. #[cfg(feature = "advanced")] #[must_use] pub fn menu_class(mut self, class: impl Into<<Theme as menu::Catalog>::Class<'a>>) -> Self { self.menu_class = class.into(); self } } impl<'a, T, L, V, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for PickList<'a, T, L, V, Message, Theme, Renderer> where T: Clone + ToString + PartialEq + 'a, L: Borrow<[T]>, V: Borrow<T>, Message: Clone + 'a, Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(State::<Renderer::Paragraph>::new()) } fn size(&self) -> Size<Length> { Size { width: self.width, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); let font = self.font.unwrap_or_else(|| renderer.default_font()); let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); let options = self.options.borrow(); state.options.resize_with(options.len(), Default::default); let option_text = Text { content: "", bounds: Size::new( f32::INFINITY, self.text_line_height.to_absolute(text_size).into(), ), size: text_size, line_height: self.text_line_height, font, align_x: text::Alignment::Default, align_y: alignment::Vertical::Center, shaping: self.text_shaping, wrapping: text::Wrapping::default(), hint_factor: renderer.scale_factor(), }; for (option, paragraph) in options.iter().zip(state.options.iter_mut()) { let label = option.to_string(); let _ = paragraph.update(Text { content: &label, ..option_text }); } if let Some(placeholder) = &self.placeholder { let _ = state.placeholder.update(Text { content: placeholder, ..option_text }); } let max_width = match self.width { Length::Shrink => { let labels_width = state.options.iter().fold(0.0, |width, paragraph| { f32::max(width, paragraph.min_width()) }); labels_width.max( self.placeholder .as_ref() .map(|_| state.placeholder.min_width()) .unwrap_or(0.0), ) } _ => 0.0, }; let size = { let intrinsic = Size::new( max_width + text_size.0 + self.padding.left, f32::from(self.text_line_height.to_absolute(text_size)), ); limits .width(self.width) .shrink(self.padding) .resolve(self.width, Length::Shrink, intrinsic) .expand(self.padding) }; layout::Node::new(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<Renderer::Paragraph>>(); match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if state.is_open { // Event wasn't processed by overlay, so cursor was clicked either outside its // bounds or on the drop-down, either way we close the overlay. state.is_open = false; if let Some(on_close) = &self.on_close { shell.publish(on_close.clone()); } shell.capture_event(); } else if cursor.is_over(layout.bounds()) { let selected = self.selected.as_ref().map(Borrow::borrow); state.is_open = true; state.hovered_option = self .options .borrow() .iter() .position(|option| Some(option) == selected); if let Some(on_open) = &self.on_open { shell.publish(on_open.clone()); } shell.capture_event(); } } Event::Mouse(mouse::Event::WheelScrolled { delta: mouse::ScrollDelta::Lines { y, .. }, }) => { if state.keyboard_modifiers.command() && cursor.is_over(layout.bounds()) && !state.is_open { fn find_next<'a, T: PartialEq>( selected: &'a T, mut options: impl Iterator<Item = &'a T>, ) -> Option<&'a T> { let _ = options.find(|&option| option == selected); options.next() } let options = self.options.borrow(); let selected = self.selected.as_ref().map(Borrow::borrow); let next_option = if *y < 0.0 { if let Some(selected) = selected { find_next(selected, options.iter()) } else { options.first() } } else if *y > 0.0 { if let Some(selected) = selected { find_next(selected, options.iter().rev()) } else { options.last() } } else { None }; if let Some(next_option) = next_option { shell.publish((self.on_select)(next_option.clone())); } shell.capture_event(); } } Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => { state.keyboard_modifiers = *modifiers; } _ => {} }; let status = { let is_hovered = cursor.is_over(layout.bounds()); if state.is_open { Status::Opened { is_hovered } } else if is_hovered { Status::Hovered } else { Status::Active } }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.last_status = Some(status); } else if self .last_status .is_some_and(|last_status| last_status != status) { shell.request_redraw(); } } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let bounds = layout.bounds(); let is_mouse_over = cursor.is_over(bounds); if is_mouse_over { mouse::Interaction::Pointer } else { mouse::Interaction::default() } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let font = self.font.unwrap_or_else(|| renderer.default_font()); let selected = self.selected.as_ref().map(Borrow::borrow); let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>(); let bounds = layout.bounds(); let style = Catalog::style( theme, &self.class, self.last_status.unwrap_or(Status::Active), ); renderer.fill_quad( renderer::Quad { bounds, border: style.border, ..renderer::Quad::default() }, style.background, ); let handle = match &self.handle { Handle::Arrow { size } => Some(( Renderer::ICON_FONT, Renderer::ARROW_DOWN_ICON, *size, text::LineHeight::default(), text::Shaping::Basic, )), Handle::Static(Icon { font, code_point, size, line_height, shaping, }) => Some((*font, *code_point, *size, *line_height, *shaping)), Handle::Dynamic { open, closed } => { if state.is_open { Some(( open.font, open.code_point, open.size, open.line_height, open.shaping, )) } else { Some(( closed.font, closed.code_point, closed.size, closed.line_height, closed.shaping, )) } } Handle::None => None, }; if let Some((font, code_point, size, line_height, shaping)) = handle { let size = size.unwrap_or_else(|| renderer.default_size()); renderer.fill_text( Text { content: code_point.to_string(), size, line_height, font, bounds: Size::new(bounds.width, f32::from(line_height.to_absolute(size))), align_x: text::Alignment::Right, align_y: alignment::Vertical::Center, shaping, wrapping: text::Wrapping::default(), hint_factor: None, }, Point::new( bounds.x + bounds.width - self.padding.right, bounds.center_y(), ), style.handle_color, *viewport, ); } let label = selected.map(ToString::to_string); if let Some(label) = label.or_else(|| self.placeholder.clone()) { let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); renderer.fill_text( Text { content: label, size: text_size, line_height: self.text_line_height, font, bounds: Size::new( bounds.width - self.padding.x(), f32::from(self.text_line_height.to_absolute(text_size)), ), align_x: text::Alignment::Default, align_y: alignment::Vertical::Center, shaping: self.text_shaping, wrapping: text::Wrapping::default(), hint_factor: renderer.scale_factor(), }, Point::new(bounds.x + self.padding.left, bounds.center_y()), if selected.is_some() { style.text_color } else { style.placeholder_color }, *viewport, ); } } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'_>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); let font = self.font.unwrap_or_else(|| renderer.default_font()); if state.is_open { let bounds = layout.bounds(); let on_select = &self.on_select; let mut menu = Menu::new( &mut state.menu, self.options.borrow(), &mut state.hovered_option, |option| { state.is_open = false; (on_select)(option) }, None, &self.menu_class, ) .width(bounds.width) .padding(self.padding) .font(font) .text_shaping(self.text_shaping); if let Some(text_size) = self.text_size { menu = menu.text_size(text_size); } Some(menu.overlay( layout.position() + translation, *viewport, bounds.height, self.menu_height, )) } else { None } } } impl<'a, T, L, V, Message, Theme, Renderer> From<PickList<'a, T, L, V, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where T: Clone + ToString + PartialEq + 'a, L: Borrow<[T]> + 'a, V: Borrow<T> + 'a, Message: Clone + 'a, Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { fn from(pick_list: PickList<'a, T, L, V, Message, Theme, Renderer>) -> Self { Self::new(pick_list) } } #[derive(Debug)] struct State<P: text::Paragraph> { menu: menu::State, keyboard_modifiers: keyboard::Modifiers, is_open: bool, hovered_option: Option<usize>, options: Vec<paragraph::Plain<P>>, placeholder: paragraph::Plain<P>, } impl<P: text::Paragraph> State<P> { /// Creates a new [`State`] for a [`PickList`]. fn new() -> Self { Self { menu: menu::State::default(), keyboard_modifiers: keyboard::Modifiers::default(), is_open: bool::default(), hovered_option: Option::default(), options: Vec::new(), placeholder: paragraph::Plain::default(), } } } impl<P: text::Paragraph> Default for State<P> { fn default() -> Self { Self::new() } } /// The handle to the right side of the [`PickList`]. #[derive(Debug, Clone, PartialEq)] pub enum Handle<Font> { /// Displays an arrow icon (▼). /// /// This is the default. Arrow { /// Font size of the content. size: Option<Pixels>, }, /// A custom static handle. Static(Icon<Font>), /// A custom dynamic handle. Dynamic { /// The [`Icon`] used when [`PickList`] is closed. closed: Icon<Font>, /// The [`Icon`] used when [`PickList`] is open. open: Icon<Font>, }, /// No handle will be shown. None, } impl<Font> Default for Handle<Font> { fn default() -> Self { Self::Arrow { size: None } } } /// The icon of a [`Handle`]. #[derive(Debug, Clone, PartialEq)] pub struct Icon<Font> { /// Font that will be used to display the `code_point`, pub font: Font, /// The unicode code point that will be used as the icon. pub code_point: char, /// Font size of the content. pub size: Option<Pixels>, /// Line height of the content. pub line_height: text::LineHeight, /// The shaping strategy of the icon. pub shaping: text::Shaping, } /// The possible status of a [`PickList`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`PickList`] can be interacted with. Active, /// The [`PickList`] is being hovered. Hovered, /// The [`PickList`] is open. Opened { /// Whether the [`PickList`] is hovered, while open. is_hovered: bool, }, } /// The appearance of a pick list. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The text [`Color`] of the pick list. pub text_color: Color, /// The placeholder [`Color`] of the pick list. pub placeholder_color: Color, /// The handle [`Color`] of the pick list. pub handle_color: Color, /// The [`Background`] of the pick list. pub background: Background, /// The [`Border`] of the pick list. pub border: Border, } /// The theme catalog of a [`PickList`]. pub trait Catalog: menu::Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> <Self as Catalog>::Class<'a>; /// The default class for the menu of the [`PickList`]. fn default_menu<'a>() -> <Self as menu::Catalog>::Class<'a> { <Self as menu::Catalog>::default() } /// The [`Style`] of a class with the given status. fn style(&self, class: &<Self as Catalog>::Class<'_>, status: Status) -> Style; } /// A styling function for a [`PickList`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> StyleFn<'a, Self> { Box::new(default) } fn style(&self, class: &StyleFn<'_, Self>, status: Status) -> Style { class(self, status) } } /// The default style of the field of a [`PickList`]. pub fn default(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let active = Style { text_color: palette.background.weak.text, background: palette.background.weak.color.into(), placeholder_color: palette.secondary.base.color, handle_color: palette.background.weak.text, border: Border { radius: 2.0.into(), width: 1.0, color: palette.background.strong.color, }, }; match status { Status::Active => active, Status::Hovered | Status::Opened { .. } => Style { border: Border { color: palette.primary.strong.color, ..active.border }, ..active }, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/keyed.rs
widget/src/keyed.rs
//! Keyed widgets can provide hints to ensure continuity. //! //! # What is continuity? //! Continuity is the feeling of persistence of state. //! //! In a graphical user interface, users expect widgets to have a //! certain degree of continuous state. For instance, a text input //! that is focused should stay focused even if the widget tree //! changes slightly. //! //! Continuity is tricky in `iced` and the Elm Architecture because //! the whole widget tree is rebuilt during every `view` call. This is //! very convenient from a developer perspective because you can build //! extremely dynamic interfaces without worrying about changing state. //! //! However, the tradeoff is that determining what changed becomes hard //! for `iced`. If you have a list of things, adding an element at the //! top may cause a loss of continuity on every element on the list! //! //! # How can we keep continuity? //! The good news is that user interfaces generally have a static widget //! structure. This structure can be relied on to ensure some degree of //! continuity. `iced` already does this. //! //! However, sometimes you have a certain part of your interface that is //! quite dynamic. For instance, a list of things where items may be added //! or removed at any place. //! //! There are different ways to mitigate this during the reconciliation //! stage, but they involve comparing trees at certain depths and //! backtracking... Quite computationally expensive. //! //! One approach that is cheaper consists in letting the user provide some hints //! about the identities of the different widgets so that they can be compared //! directly without going deeper. //! //! The widgets in this module will all ask for a "hint" of some sort. In order //! to help them keep continuity, you need to make sure the hint stays the same //! for the same items in your user interface between `view` calls. pub mod column; pub use column::Column; /// Creates a keyed [`Column`] with the given children. /// /// Keyed columns distribute content vertically while keeping continuity. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::keyed_column; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// keyed_column![ /// (0, "Item 0"), /// (1, "Item 1"), /// (2, "Item 2"), /// ].into() /// } /// ``` #[macro_export] macro_rules! keyed_column { () => ( $crate::keyed::Column::new() ); ($(($key:expr, $x:expr)),+ $(,)?) => ( $crate::keyed::Column::with_children(vec![$(($key, $crate::core::Element::from($x))),+]) ); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/progress_bar.rs
widget/src/progress_bar.rs
//! Progress bars visualize the progression of an extended computer operation, such as a download, file transfer, or installation. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::progress_bar; //! //! struct State { //! progress: f32, //! } //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! progress_bar(0.0..=100.0, state.progress).into() //! } //! ``` use crate::core::border::{self, Border}; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::Tree; use crate::core::{ self, Background, Color, Element, Layout, Length, Rectangle, Size, Theme, Widget, }; use std::ops::RangeInclusive; /// A bar that displays progress. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::progress_bar; /// /// struct State { /// progress: f32, /// } /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// progress_bar(0.0..=100.0, state.progress).into() /// } /// ``` pub struct ProgressBar<'a, Theme = crate::Theme> where Theme: Catalog, { range: RangeInclusive<f32>, value: f32, length: Length, girth: Length, is_vertical: bool, class: Theme::Class<'a>, } impl<'a, Theme> ProgressBar<'a, Theme> where Theme: Catalog, { /// The default girth of a [`ProgressBar`]. pub const DEFAULT_GIRTH: f32 = 30.0; /// Creates a new [`ProgressBar`]. /// /// It expects: /// * an inclusive range of possible values /// * the current value of the [`ProgressBar`] pub fn new(range: RangeInclusive<f32>, value: f32) -> Self { ProgressBar { value: value.clamp(*range.start(), *range.end()), range, length: Length::Fill, girth: Length::from(Self::DEFAULT_GIRTH), is_vertical: false, class: Theme::default(), } } /// Sets the width of the [`ProgressBar`]. pub fn length(mut self, length: impl Into<Length>) -> Self { self.length = length.into(); self } /// Sets the height of the [`ProgressBar`]. pub fn girth(mut self, girth: impl Into<Length>) -> Self { self.girth = girth.into(); self } /// Turns the [`ProgressBar`] into a vertical [`ProgressBar`]. /// /// By default, a [`ProgressBar`] is horizontal. pub fn vertical(mut self) -> Self { self.is_vertical = true; self } /// Sets the style of the [`ProgressBar`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`ProgressBar`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } fn width(&self) -> Length { if self.is_vertical { self.girth } else { self.length } } fn height(&self) -> Length { if self.is_vertical { self.length } else { self.girth } } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for ProgressBar<'_, Theme> where Theme: Catalog, Renderer: core::Renderer, { 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 draw( &self, _tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { let bounds = layout.bounds(); let (range_start, range_end) = self.range.clone().into_inner(); let length = if self.is_vertical { bounds.height } else { bounds.width }; let active_progress_length = if range_start >= range_end { 0.0 } else { length * (self.value - range_start) / (range_end - range_start) }; let style = theme.style(&self.class); renderer.fill_quad( renderer::Quad { bounds: Rectangle { ..bounds }, border: style.border, ..renderer::Quad::default() }, style.background, ); if active_progress_length > 0.0 { let bounds = if self.is_vertical { Rectangle { y: bounds.y + bounds.height - active_progress_length, height: active_progress_length, ..bounds } } else { Rectangle { width: active_progress_length, ..bounds } }; renderer.fill_quad( renderer::Quad { bounds, border: Border { color: Color::TRANSPARENT, ..style.border }, ..renderer::Quad::default() }, style.bar, ); } } } impl<'a, Message, Theme, Renderer> From<ProgressBar<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a + Catalog, Renderer: 'a + core::Renderer, { fn from(progress_bar: ProgressBar<'a, Theme>) -> Element<'a, Message, Theme, Renderer> { Element::new(progress_bar) } } /// The appearance of a progress bar. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Background`] of the progress bar. pub background: Background, /// The [`Background`] of the bar of the progress bar. pub bar: Background, /// The [`Border`] of the progress bar. pub border: Border, } /// The theme catalog of a [`ProgressBar`]. pub trait Catalog: Sized { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`ProgressBar`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(primary) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The primary style of a [`ProgressBar`]. pub fn primary(theme: &Theme) -> Style { let palette = theme.extended_palette(); styled(palette.background.strong.color, palette.primary.base.color) } /// The secondary style of a [`ProgressBar`]. pub fn secondary(theme: &Theme) -> Style { let palette = theme.extended_palette(); styled( palette.background.strong.color, palette.secondary.base.color, ) } /// The success style of a [`ProgressBar`]. pub fn success(theme: &Theme) -> Style { let palette = theme.extended_palette(); styled(palette.background.strong.color, palette.success.base.color) } /// The warning style of a [`ProgressBar`]. pub fn warning(theme: &Theme) -> Style { let palette = theme.extended_palette(); styled(palette.background.strong.color, palette.warning.base.color) } /// The danger style of a [`ProgressBar`]. pub fn danger(theme: &Theme) -> Style { let palette = theme.extended_palette(); styled(palette.background.strong.color, palette.danger.base.color) } fn styled(background: impl Into<Background>, bar: impl Into<Background>) -> Style { Style { background: background.into(), bar: bar.into(), border: border::rounded(2), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/qr_code.rs
widget/src/qr_code.rs
//! QR codes display information in a type of two-dimensional matrix barcode. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::qr_code; //! //! struct State { //! data: qr_code::Data, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! qr_code(&state.data).into() //! } //! ``` use crate::Renderer; use crate::canvas; use crate::core::layout; use crate::core::mouse; use crate::core::renderer::{self, Renderer as _}; use crate::core::widget::tree::{self, Tree}; use crate::core::{ Color, Element, Layout, Length, Pixels, Point, Rectangle, Size, Theme, Vector, Widget, }; use std::cell::RefCell; use thiserror::Error; const DEFAULT_CELL_SIZE: f32 = 4.0; const QUIET_ZONE: usize = 2; /// A type of matrix barcode consisting of squares arranged in a grid which /// can be read by an imaging device, such as a camera. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::qr_code; /// /// struct State { /// data: qr_code::Data, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// qr_code(&state.data).into() /// } /// ``` pub struct QRCode<'a, Theme = crate::Theme> where Theme: Catalog, { data: &'a Data, cell_size: f32, class: Theme::Class<'a>, } impl<'a, Theme> QRCode<'a, Theme> where Theme: Catalog, { /// Creates a new [`QRCode`] with the provided [`Data`]. pub fn new(data: &'a Data) -> Self { Self { data, cell_size: DEFAULT_CELL_SIZE, class: Theme::default(), } } /// Sets the size of the squares of the grid cell of the [`QRCode`]. pub fn cell_size(mut self, cell_size: impl Into<Pixels>) -> Self { self.cell_size = cell_size.into().0; self } /// Sets the size of the entire [`QRCode`]. pub fn total_size(mut self, total_size: impl Into<Pixels>) -> Self { self.cell_size = total_size.into().0 / (self.data.width + 2 * QUIET_ZONE) as f32; self } /// Sets the style of the [`QRCode`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`QRCode`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme> Widget<Message, Theme, Renderer> for QRCode<'_, Theme> where Theme: Catalog, { 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::Shrink, height: Length::Shrink, } } fn layout( &mut self, _tree: &mut Tree, _renderer: &Renderer, _limits: &layout::Limits, ) -> layout::Node { let side_length = (self.data.width + 2 * QUIET_ZONE) as f32 * self.cell_size; layout::Node::new(Size::new(side_length, side_length)) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { let state = tree.state.downcast_ref::<State>(); let bounds = layout.bounds(); let side_length = self.data.width + 2 * QUIET_ZONE; let style = theme.style(&self.class); let mut last_style = state.last_style.borrow_mut(); if Some(style) != *last_style { self.data.cache.clear(); *last_style = Some(style); } // Reuse cache if possible let geometry = self.data.cache.draw(renderer, bounds.size(), |frame| { // Scale units to cell size frame.scale(self.cell_size); // Draw background frame.fill_rectangle( Point::ORIGIN, Size::new(side_length as f32, side_length as f32), style.background, ); // Avoid drawing on the quiet zone frame.translate(Vector::new(QUIET_ZONE as f32, QUIET_ZONE as f32)); // Draw contents self.data .contents .iter() .enumerate() .filter(|(_, value)| **value == qrcode::Color::Dark) .for_each(|(index, _)| { let row = index / self.data.width; let column = index % self.data.width; frame.fill_rectangle( Point::new(column as f32, row as f32), Size::UNIT, style.cell, ); }); }); renderer.with_translation(bounds.position() - Point::ORIGIN, |renderer| { use crate::graphics::geometry::Renderer as _; renderer.draw_geometry(geometry); }); } } impl<'a, Message, Theme> From<QRCode<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Theme: Catalog + 'a, { fn from(qr_code: QRCode<'a, Theme>) -> Self { Self::new(qr_code) } } /// The data of a [`QRCode`]. /// /// It stores the contents that will be displayed. #[derive(Debug)] pub struct Data { contents: Vec<qrcode::Color>, width: usize, cache: canvas::Cache<Renderer>, } impl Data { /// Creates a new [`Data`] with the provided data. /// /// This method uses an [`ErrorCorrection::Medium`] and chooses the smallest /// size to display the data. pub fn new(data: impl AsRef<[u8]>) -> Result<Self, Error> { let encoded = qrcode::QrCode::new(data)?; Ok(Self::build(encoded)) } /// Creates a new [`Data`] with the provided [`ErrorCorrection`]. pub fn with_error_correction( data: impl AsRef<[u8]>, error_correction: ErrorCorrection, ) -> Result<Self, Error> { let encoded = qrcode::QrCode::with_error_correction_level(data, error_correction.into())?; Ok(Self::build(encoded)) } /// Creates a new [`Data`] with the provided [`Version`] and /// [`ErrorCorrection`]. pub fn with_version( data: impl AsRef<[u8]>, version: Version, error_correction: ErrorCorrection, ) -> Result<Self, Error> { let encoded = qrcode::QrCode::with_version(data, version.into(), error_correction.into())?; Ok(Self::build(encoded)) } fn build(encoded: qrcode::QrCode) -> Self { let width = encoded.width(); let contents = encoded.into_colors(); Self { contents, width, cache: canvas::Cache::new(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// The size of a [`QRCode`]. /// /// The higher the version the larger the grid of cells, and therefore the more /// information the [`QRCode`] can carry. pub enum Version { /// A normal QR code version. It should be between 1 and 40. Normal(u8), /// A micro QR code version. It should be between 1 and 4. Micro(u8), } impl From<Version> for qrcode::Version { fn from(version: Version) -> Self { match version { Version::Normal(v) => qrcode::Version::Normal(i16::from(v)), Version::Micro(v) => qrcode::Version::Micro(i16::from(v)), } } } /// The error correction level. /// /// It controls the amount of data that can be damaged while still being able /// to recover the original information. /// /// A higher error correction level allows for more corrupted data. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorCorrection { /// Low error correction. 7% of the data can be restored. Low, /// Medium error correction. 15% of the data can be restored. Medium, /// Quartile error correction. 25% of the data can be restored. Quartile, /// High error correction. 30% of the data can be restored. High, } impl From<ErrorCorrection> for qrcode::EcLevel { fn from(ec_level: ErrorCorrection) -> Self { match ec_level { ErrorCorrection::Low => qrcode::EcLevel::L, ErrorCorrection::Medium => qrcode::EcLevel::M, ErrorCorrection::Quartile => qrcode::EcLevel::Q, ErrorCorrection::High => qrcode::EcLevel::H, } } } /// An error that occurred when building a [`Data`] for a [`QRCode`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] pub enum Error { /// The data is too long to encode in a QR code for the chosen [`Version`]. #[error("The data is too long to encode in a QR code for the chosen version")] DataTooLong, /// The chosen [`Version`] and [`ErrorCorrection`] combination is invalid. #[error("The chosen version and error correction level combination is invalid.")] InvalidVersion, /// One or more characters in the provided data are not supported by the /// chosen [`Version`]. #[error( "One or more characters in the provided data are not supported by the \ chosen version" )] UnsupportedCharacterSet, /// The chosen ECI designator is invalid. A valid designator should be /// between 0 and 999999. #[error( "The chosen ECI designator is invalid. A valid designator should be \ between 0 and 999999." )] InvalidEciDesignator, /// A character that does not belong to the character set was found. #[error("A character that does not belong to the character set was found")] InvalidCharacter, } impl From<qrcode::types::QrError> for Error { fn from(error: qrcode::types::QrError) -> Self { use qrcode::types::QrError; match error { QrError::DataTooLong => Error::DataTooLong, QrError::InvalidVersion => Error::InvalidVersion, QrError::UnsupportedCharacterSet => Error::UnsupportedCharacterSet, QrError::InvalidEciDesignator => Error::InvalidEciDesignator, QrError::InvalidCharacter => Error::InvalidCharacter, } } } #[derive(Default)] struct State { last_style: RefCell<Option<Style>>, } /// The appearance of a QR code. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The color of the QR code data cells pub cell: Color, /// The color of the QR code background pub background: Color, } /// The theme catalog of a [`QRCode`]. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`QRCode`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The default style of a [`QRCode`]. pub fn default(theme: &Theme) -> Style { let palette = theme.palette(); Style { cell: palette.text, background: palette.background, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/responsive.rs
widget/src/responsive.rs
use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::widget::Tree; use crate::core::{ self, Clipboard, Element, Event, Length, Rectangle, Shell, Size, Vector, Widget, }; use crate::space; /// A widget that is aware of its dimensions. /// /// A [`Responsive`] widget will always try to fill all the available space of /// its parent. pub struct Responsive<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { view: Box<dyn Fn(Size) -> Element<'a, Message, Theme, Renderer> + 'a>, width: Length, height: Length, content: Element<'a, Message, Theme, Renderer>, } impl<'a, Message, Theme, Renderer> Responsive<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { /// Creates a new [`Responsive`] widget with a closure that produces its /// contents. /// /// The `view` closure will receive the maximum available space for /// the [`Responsive`] during layout. You can use this [`Size`] to /// conditionally build the contents. pub fn new(view: impl Fn(Size) -> Element<'a, Message, Theme, Renderer> + 'a) -> Self { Self { view: Box::new(view), width: Length::Fill, height: Length::Fill, content: Element::new(space()), } } /// Sets the width of the [`Responsive`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Responsive`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Responsive<'_, Message, Theme, Renderer> where Renderer: core::Renderer, { fn diff(&self, _tree: &mut Tree) { // Diff is deferred to layout } 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 { let limits = limits.width(self.width).height(self.height); let size = limits.max(); self.content = (self.view)(size); tree.diff_children(std::slice::from_ref(&self.content)); let node = self.content .as_widget_mut() .layout(&mut tree.children[0], renderer, &limits.loose()); let size = limits.resolve(self.width, self.height, node.size()); layout::Node::with_children(size, vec![node]) } 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.children().next().unwrap(), 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.children().next().unwrap(), 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.children().next().unwrap(), cursor, viewport, renderer, ) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content.as_widget_mut().operate( &mut tree.children[0], layout.children().next().unwrap(), renderer, operation, ); } fn overlay<'a>( &'a mut self, tree: &'a mut Tree, layout: Layout<'a>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( &mut tree.children[0], layout.children().next().unwrap(), renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Responsive<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { fn from(responsive: Responsive<'a, Message, Theme, Renderer>) -> Self { Self::new(responsive) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/markdown.rs
widget/src/markdown.rs
//! Markdown widgets can parse and display Markdown. //! //! You can enable the `highlighter` feature for syntax highlighting //! in code blocks. //! //! Only the variants of [`Item`] are currently supported. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::markdown; //! use iced::Theme; //! //! struct State { //! markdown: Vec<markdown::Item>, //! } //! //! enum Message { //! LinkClicked(markdown::Uri), //! } //! //! impl State { //! pub fn new() -> Self { //! Self { //! markdown: markdown::parse("This is some **Markdown**!").collect(), //! } //! } //! //! fn view(&self) -> Element<'_, Message> { //! markdown::view(&self.markdown, Theme::TokyoNight) //! .map(Message::LinkClicked) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::LinkClicked(url) => { //! println!("The following url was clicked: {url}"); //! } //! } //! } //! } //! ``` use crate::core::alignment; use crate::core::border; use crate::core::font::{self, Font}; use crate::core::padding; use crate::core::theme; use crate::core::{self, Color, Element, Length, Padding, Pixels, Theme, color}; use crate::{checkbox, column, container, rich_text, row, rule, scrollable, span, text}; use std::borrow::BorrowMut; use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::mem; use std::ops::Range; use std::rc::Rc; use std::sync::Arc; pub use core::text::Highlight; pub use pulldown_cmark::HeadingLevel; /// A [`String`] representing a [URI] in a Markdown document /// /// [URI]: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier pub type Uri = String; /// A bunch of Markdown that has been parsed. #[derive(Debug, Default)] pub struct Content { items: Vec<Item>, incomplete: HashMap<usize, Section>, state: State, } #[derive(Debug)] struct Section { content: String, broken_links: HashSet<String>, } impl Content { /// Creates a new empty [`Content`]. pub fn new() -> Self { Self::default() } /// Creates some new [`Content`] by parsing the given Markdown. pub fn parse(markdown: &str) -> Self { let mut content = Self::new(); content.push_str(markdown); content } /// Pushes more Markdown into the [`Content`]; parsing incrementally! /// /// This is specially useful when you have long streams of Markdown; like /// big files or potentially long replies. pub fn push_str(&mut self, markdown: &str) { if markdown.is_empty() { return; } // Append to last leftover text let mut leftover = std::mem::take(&mut self.state.leftover); leftover.push_str(markdown); let input = if leftover.trim_end().ends_with('|') { leftover.trim_end().trim_end_matches('|') } else { leftover.as_str() }; // Pop the last item let _ = self.items.pop(); // Re-parse last item and new text for (item, source, broken_links) in parse_with(&mut self.state, input) { if !broken_links.is_empty() { let _ = self.incomplete.insert( self.items.len(), Section { content: source.to_owned(), broken_links, }, ); } self.items.push(item); } self.state.leftover.push_str(&leftover[input.len()..]); // Re-parse incomplete sections if new references are available if !self.incomplete.is_empty() { self.incomplete.retain(|index, section| { if self.items.len() <= *index { return false; } let broken_links_before = section.broken_links.len(); section .broken_links .retain(|link| !self.state.references.contains_key(link)); if broken_links_before != section.broken_links.len() { let mut state = State { leftover: String::new(), references: self.state.references.clone(), images: HashSet::new(), #[cfg(feature = "highlighter")] highlighter: None, }; if let Some((item, _source, _broken_links)) = parse_with(&mut state, &section.content).next() { self.items[*index] = item; } self.state.images.extend(state.images.drain()); drop(state); } !section.broken_links.is_empty() }); } } /// Returns the Markdown items, ready to be rendered. /// /// You can use [`view`] to turn them into an [`Element`]. pub fn items(&self) -> &[Item] { &self.items } /// Returns the URLs of the Markdown images present in the [`Content`]. pub fn images(&self) -> &HashSet<Uri> { &self.state.images } } /// A Markdown item. #[derive(Debug, Clone)] pub enum Item { /// A heading. Heading(pulldown_cmark::HeadingLevel, Text), /// A paragraph. Paragraph(Text), /// A code block. /// /// You can enable the `highlighter` feature for syntax highlighting. CodeBlock { /// The language of the code block, if any. language: Option<String>, /// The raw code of the code block. code: String, /// The styled lines of text in the code block. lines: Vec<Text>, }, /// A list. List { /// The first number of the list, if it is ordered. start: Option<u64>, /// The items of the list. bullets: Vec<Bullet>, }, /// An image. Image { /// The destination URL of the image. url: Uri, /// The title of the image. title: String, /// The alternative text of the image. alt: Text, }, /// A quote. Quote(Vec<Item>), /// A horizontal separator. Rule, /// A table. Table { /// The columns of the table. columns: Vec<Column>, /// The rows of the table. rows: Vec<Row>, }, } /// The column of a table. #[derive(Debug, Clone)] pub struct Column { /// The header of the column. pub header: Vec<Item>, /// The alignment of the column. pub alignment: pulldown_cmark::Alignment, } /// The row of a table. #[derive(Debug, Clone)] pub struct Row { /// The cells of the row. cells: Vec<Vec<Item>>, } /// A bunch of parsed Markdown text. #[derive(Debug, Clone)] pub struct Text { spans: Vec<Span>, last_style: Cell<Option<Style>>, last_styled_spans: RefCell<Arc<[text::Span<'static, Uri>]>>, } impl Text { fn new(spans: Vec<Span>) -> Self { Self { spans, last_style: Cell::default(), last_styled_spans: RefCell::default(), } } /// Returns the [`rich_text()`] spans ready to be used for the given style. /// /// This method performs caching for you. It will only reallocate if the [`Style`] /// provided changes. pub fn spans(&self, style: Style) -> Arc<[text::Span<'static, Uri>]> { if Some(style) != self.last_style.get() { *self.last_styled_spans.borrow_mut() = self.spans.iter().map(|span| span.view(&style)).collect(); self.last_style.set(Some(style)); } self.last_styled_spans.borrow().clone() } } #[derive(Debug, Clone)] enum Span { Standard { text: String, strikethrough: bool, link: Option<Uri>, strong: bool, emphasis: bool, code: bool, }, #[cfg(feature = "highlighter")] Highlight { text: String, color: Option<Color>, font: Option<Font>, }, } impl Span { fn view(&self, style: &Style) -> text::Span<'static, Uri> { match self { Span::Standard { text, strikethrough, link, strong, emphasis, code, } => { let span = span(text.clone()).strikethrough(*strikethrough); let span = if *code { span.font(style.inline_code_font) .color(style.inline_code_color) .background(style.inline_code_highlight.background) .border(style.inline_code_highlight.border) .padding(style.inline_code_padding) } else if *strong || *emphasis { span.font(Font { weight: if *strong { font::Weight::Bold } else { font::Weight::Normal }, style: if *emphasis { font::Style::Italic } else { font::Style::Normal }, ..style.font }) } else { span.font(style.font) }; if let Some(link) = link.as_ref() { span.color(style.link_color).link(link.clone()) } else { span } } #[cfg(feature = "highlighter")] Span::Highlight { text, color, font } => { span(text.clone()).color_maybe(*color).font_maybe(*font) } } } } /// The item of a list. #[derive(Debug, Clone)] pub enum Bullet { /// A simple bullet point. Point { /// The contents of the bullet point. items: Vec<Item>, }, /// A task. Task { /// The contents of the task. items: Vec<Item>, /// Whether the task is done or not. done: bool, }, } impl Bullet { fn items(&self) -> &[Item] { match self { Bullet::Point { items } | Bullet::Task { items, .. } => items, } } fn push(&mut self, item: Item) { let (Bullet::Point { items } | Bullet::Task { items, .. }) = self; items.push(item); } } /// Parse the given Markdown content. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::markdown; /// use iced::Theme; /// /// struct State { /// markdown: Vec<markdown::Item>, /// } /// /// enum Message { /// LinkClicked(markdown::Uri), /// } /// /// impl State { /// pub fn new() -> Self { /// Self { /// markdown: markdown::parse("This is some **Markdown**!").collect(), /// } /// } /// /// fn view(&self) -> Element<'_, Message> { /// markdown::view(&self.markdown, Theme::TokyoNight) /// .map(Message::LinkClicked) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::LinkClicked(url) => { /// println!("The following url was clicked: {url}"); /// } /// } /// } /// } /// ``` pub fn parse(markdown: &str) -> impl Iterator<Item = Item> + '_ { parse_with(State::default(), markdown).map(|(item, _source, _broken_links)| item) } #[derive(Debug, Default)] struct State { leftover: String, references: HashMap<String, String>, images: HashSet<Uri>, #[cfg(feature = "highlighter")] highlighter: Option<Highlighter>, } #[cfg(feature = "highlighter")] #[derive(Debug)] struct Highlighter { lines: Vec<(String, Vec<Span>)>, language: String, parser: iced_highlighter::Stream, current: usize, } #[cfg(feature = "highlighter")] impl Highlighter { pub fn new(language: &str) -> Self { Self { lines: Vec::new(), parser: iced_highlighter::Stream::new(&iced_highlighter::Settings { theme: iced_highlighter::Theme::Base16Ocean, token: language.to_owned(), }), language: language.to_owned(), current: 0, } } pub fn prepare(&mut self) { self.current = 0; } pub fn highlight_line(&mut self, text: &str) -> &[Span] { match self.lines.get(self.current) { Some(line) if line.0 == text => {} _ => { if self.current + 1 < self.lines.len() { log::debug!("Resetting highlighter..."); self.parser.reset(); self.lines.truncate(self.current); for line in &self.lines { log::debug!("Refeeding {n} lines", n = self.lines.len()); let _ = self.parser.highlight_line(&line.0); } } log::trace!("Parsing: {text}", text = text.trim_end()); if self.current + 1 < self.lines.len() { self.parser.commit(); } let mut spans = Vec::new(); for (range, highlight) in self.parser.highlight_line(text) { spans.push(Span::Highlight { text: text[range].to_owned(), color: highlight.color(), font: highlight.font(), }); } if self.current + 1 == self.lines.len() { let _ = self.lines.pop(); } self.lines.push((text.to_owned(), spans)); } } self.current += 1; &self .lines .get(self.current - 1) .expect("Line must be parsed") .1 } } fn parse_with<'a>( mut state: impl BorrowMut<State> + 'a, markdown: &'a str, ) -> impl Iterator<Item = (Item, &'a str, HashSet<String>)> + 'a { enum Scope { List(List), Quote(Vec<Item>), Table { alignment: Vec<pulldown_cmark::Alignment>, columns: Vec<Column>, rows: Vec<Row>, current: Vec<Item>, }, } struct List { start: Option<u64>, bullets: Vec<Bullet>, } let broken_links = Rc::new(RefCell::new(HashSet::new())); let mut spans = Vec::new(); let mut code = String::new(); let mut code_language = None; let mut code_lines = Vec::new(); let mut strong = false; let mut emphasis = false; let mut strikethrough = false; let mut metadata = false; let mut code_block = false; let mut link = None; let mut image = None; let mut stack = Vec::new(); #[cfg(feature = "highlighter")] let mut highlighter = None; let parser = pulldown_cmark::Parser::new_with_broken_link_callback( markdown, pulldown_cmark::Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | pulldown_cmark::Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS | pulldown_cmark::Options::ENABLE_TABLES | pulldown_cmark::Options::ENABLE_STRIKETHROUGH | pulldown_cmark::Options::ENABLE_TASKLISTS, { let references = state.borrow().references.clone(); let broken_links = broken_links.clone(); Some(move |broken_link: pulldown_cmark::BrokenLink<'_>| { if let Some(reference) = references.get(broken_link.reference.as_ref()) { Some(( pulldown_cmark::CowStr::from(reference.to_owned()), broken_link.reference.into_static(), )) } else { let _ = RefCell::borrow_mut(&broken_links) .insert(broken_link.reference.into_string()); None } }) }, ); let references = &mut state.borrow_mut().references; for reference in parser.reference_definitions().iter() { let _ = references.insert(reference.0.to_owned(), reference.1.dest.to_string()); } let produce = move |state: &mut State, stack: &mut Vec<Scope>, item, source: Range<usize>| { if let Some(scope) = stack.last_mut() { match scope { Scope::List(list) => { list.bullets.last_mut().expect("item context").push(item); } Scope::Quote(items) => { items.push(item); } Scope::Table { current, .. } => { current.push(item); } } None } else { state.leftover = markdown[source.start..].to_owned(); Some(( item, &markdown[source.start..source.end], broken_links.take(), )) } }; let parser = parser.into_offset_iter(); // We want to keep the `spans` capacity #[allow(clippy::drain_collect)] parser.filter_map(move |(event, source)| match event { pulldown_cmark::Event::Start(tag) => match tag { pulldown_cmark::Tag::Strong if !metadata => { strong = true; None } pulldown_cmark::Tag::Emphasis if !metadata => { emphasis = true; None } pulldown_cmark::Tag::Strikethrough if !metadata => { strikethrough = true; None } pulldown_cmark::Tag::Link { dest_url, .. } if !metadata => { link = Some(dest_url.into_string()); None } pulldown_cmark::Tag::Image { dest_url, title, .. } if !metadata => { image = Some((dest_url.into_string(), title.into_string())); None } pulldown_cmark::Tag::List(first_item) if !metadata => { let prev = if spans.is_empty() { None } else { produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ) }; stack.push(Scope::List(List { start: first_item, bullets: Vec::new(), })); prev } pulldown_cmark::Tag::Item => { if let Some(Scope::List(list)) = stack.last_mut() { list.bullets.push(Bullet::Point { items: Vec::new() }); } None } pulldown_cmark::Tag::BlockQuote(_kind) if !metadata => { let prev = if spans.is_empty() { None } else { produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ) }; stack.push(Scope::Quote(Vec::new())); prev } pulldown_cmark::Tag::CodeBlock(pulldown_cmark::CodeBlockKind::Fenced(language)) if !metadata => { #[cfg(feature = "highlighter")] { highlighter = Some({ let mut highlighter = state .borrow_mut() .highlighter .take() .filter(|highlighter| highlighter.language == language.as_ref()) .unwrap_or_else(|| { Highlighter::new(language.split(',').next().unwrap_or_default()) }); highlighter.prepare(); highlighter }); } code_block = true; code_language = (!language.is_empty()).then(|| language.into_string()); if spans.is_empty() { None } else { produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ) } } pulldown_cmark::Tag::MetadataBlock(_) => { metadata = true; None } pulldown_cmark::Tag::Table(alignment) => { stack.push(Scope::Table { columns: Vec::with_capacity(alignment.len()), alignment, current: Vec::new(), rows: Vec::new(), }); None } pulldown_cmark::Tag::TableHead => { strong = true; None } pulldown_cmark::Tag::TableRow => { let Scope::Table { rows, .. } = stack.last_mut()? else { return None; }; rows.push(Row { cells: Vec::new() }); None } _ => None, }, pulldown_cmark::Event::End(tag) => match tag { pulldown_cmark::TagEnd::Heading(level) if !metadata => produce( state.borrow_mut(), &mut stack, Item::Heading(level, Text::new(spans.drain(..).collect())), source, ), pulldown_cmark::TagEnd::Strong if !metadata => { strong = false; None } pulldown_cmark::TagEnd::Emphasis if !metadata => { emphasis = false; None } pulldown_cmark::TagEnd::Strikethrough if !metadata => { strikethrough = false; None } pulldown_cmark::TagEnd::Link if !metadata => { link = None; None } pulldown_cmark::TagEnd::Paragraph if !metadata => { if spans.is_empty() { None } else { produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ) } } pulldown_cmark::TagEnd::Item if !metadata => { if spans.is_empty() { None } else { produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ) } } pulldown_cmark::TagEnd::List(_) if !metadata => { let scope = stack.pop()?; let Scope::List(list) = scope else { return None; }; produce( state.borrow_mut(), &mut stack, Item::List { start: list.start, bullets: list.bullets, }, source, ) } pulldown_cmark::TagEnd::BlockQuote(_kind) if !metadata => { let scope = stack.pop()?; let Scope::Quote(quote) = scope else { return None; }; produce(state.borrow_mut(), &mut stack, Item::Quote(quote), source) } pulldown_cmark::TagEnd::Image if !metadata => { let (url, title) = image.take()?; let alt = Text::new(spans.drain(..).collect()); let state = state.borrow_mut(); let _ = state.images.insert(url.clone()); produce(state, &mut stack, Item::Image { url, title, alt }, source) } pulldown_cmark::TagEnd::CodeBlock if !metadata => { code_block = false; #[cfg(feature = "highlighter")] { state.borrow_mut().highlighter = highlighter.take(); } produce( state.borrow_mut(), &mut stack, Item::CodeBlock { language: code_language.take(), code: mem::take(&mut code), lines: code_lines.drain(..).collect(), }, source, ) } pulldown_cmark::TagEnd::MetadataBlock(_) => { metadata = false; None } pulldown_cmark::TagEnd::Table => { let scope = stack.pop()?; let Scope::Table { columns, rows, .. } = scope else { return None; }; produce( state.borrow_mut(), &mut stack, Item::Table { columns, rows }, source, ) } pulldown_cmark::TagEnd::TableHead => { strong = false; None } pulldown_cmark::TagEnd::TableCell => { if !spans.is_empty() { let _ = produce( state.borrow_mut(), &mut stack, Item::Paragraph(Text::new(spans.drain(..).collect())), source, ); } let Scope::Table { alignment, columns, rows, current, } = stack.last_mut()? else { return None; }; if columns.len() < alignment.len() { columns.push(Column { header: std::mem::take(current), alignment: alignment[columns.len()], }); } else { rows.last_mut() .expect("table row") .cells .push(std::mem::take(current)); } None } _ => None, }, pulldown_cmark::Event::Text(text) if !metadata => { if code_block { code.push_str(&text); #[cfg(feature = "highlighter")] if let Some(highlighter) = &mut highlighter { for line in text.lines() { code_lines.push(Text::new(highlighter.highlight_line(line).to_vec())); } } #[cfg(not(feature = "highlighter"))] for line in text.lines() { code_lines.push(Text::new(vec![Span::Standard { text: line.to_owned(), strong, emphasis, strikethrough, link: link.clone(), code: false, }])); } return None; } let span = Span::Standard { text: text.into_string(), strong, emphasis, strikethrough, link: link.clone(), code: false, }; spans.push(span); None } pulldown_cmark::Event::Code(code) if !metadata => { let span = Span::Standard { text: code.into_string(), strong, emphasis, strikethrough, link: link.clone(), code: true, }; spans.push(span); None } pulldown_cmark::Event::SoftBreak if !metadata => { spans.push(Span::Standard { text: String::from(" "), strikethrough, strong, emphasis, link: link.clone(), code: false, }); None } pulldown_cmark::Event::HardBreak if !metadata => { spans.push(Span::Standard { text: String::from("\n"), strikethrough, strong, emphasis, link: link.clone(), code: false, }); None } pulldown_cmark::Event::Rule => produce(state.borrow_mut(), &mut stack, Item::Rule, source), pulldown_cmark::Event::TaskListMarker(done) => { if let Some(Scope::List(list)) = stack.last_mut() && let Some(item) = list.bullets.last_mut() && let Bullet::Point { items } = item { *item = Bullet::Task { items: std::mem::take(items), done, }; } None } _ => None, }) } /// Configuration controlling Markdown rendering in [`view`]. #[derive(Debug, Clone, Copy)] pub struct Settings { /// The base text size. pub text_size: Pixels, /// The text size of level 1 heading. pub h1_size: Pixels, /// The text size of level 2 heading. pub h2_size: Pixels, /// The text size of level 3 heading. pub h3_size: Pixels, /// The text size of level 4 heading. pub h4_size: Pixels, /// The text size of level 5 heading. pub h5_size: Pixels, /// The text size of level 6 heading. pub h6_size: Pixels, /// The text size used in code blocks. pub code_size: Pixels, /// The spacing to be used between elements. pub spacing: Pixels, /// The styling of the Markdown. pub style: Style, } impl Settings { /// Creates new [`Settings`] with default text size and the given [`Style`]. pub fn with_style(style: impl Into<Style>) -> Self { Self::with_text_size(16, style) } /// Creates new [`Settings`] with the given base text size in [`Pixels`]. /// /// Heading levels will be adjusted automatically. Specifically, /// the first level will be twice the base size, and then every level /// after that will be 25% smaller. pub fn with_text_size(text_size: impl Into<Pixels>, style: impl Into<Style>) -> Self { let text_size = text_size.into(); Self { text_size, h1_size: text_size * 2.0, h2_size: text_size * 1.75, h3_size: text_size * 1.5, h4_size: text_size * 1.25, h5_size: text_size, h6_size: text_size, code_size: text_size * 0.75, spacing: text_size * 0.875, style: style.into(), } } } impl From<&Theme> for Settings { fn from(theme: &Theme) -> Self { Self::with_style(Style::from(theme)) } } impl From<Theme> for Settings { fn from(theme: Theme) -> Self { Self::with_style(Style::from(theme)) } } /// The text styling of some Markdown rendering in [`view`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Font`] to be applied to basic text. pub font: Font, /// The [`Highlight`] to be applied to the background of inline code. pub inline_code_highlight: Highlight, /// The [`Padding`] to be applied to the background of inline code. pub inline_code_padding: Padding,
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/lazy.rs
widget/src/lazy.rs
#![allow(clippy::await_holding_refcell_ref, clippy::type_complexity)] pub(crate) mod helpers; pub mod component; #[allow(deprecated)] pub use component::Component; mod cache; use crate::core::Element; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::widget::{self, Widget}; use crate::core::{self, Clipboard, Event, Length, Rectangle, Shell, Size, Vector}; use ouroboros::self_referencing; use rustc_hash::FxHasher; use std::cell::RefCell; use std::hash::{Hash, Hasher as H}; use std::rc::Rc; /// A widget that only rebuilds its contents when necessary. #[cfg(feature = "lazy")] pub struct Lazy<'a, Message, Theme, Renderer, Dependency, View> { dependency: Dependency, view: Box<dyn Fn(&Dependency) -> View + 'a>, element: RefCell<Option<Rc<RefCell<Option<Element<'static, Message, Theme, Renderer>>>>>>, } impl<'a, Message, Theme, Renderer, Dependency, View> Lazy<'a, Message, Theme, Renderer, Dependency, View> where Dependency: Hash + 'a, View: Into<Element<'static, Message, Theme, Renderer>>, { /// Creates a new [`Lazy`] widget with the given data `Dependency` and a /// closure that can turn this data into a widget tree. pub fn new(dependency: Dependency, view: impl Fn(&Dependency) -> View + 'a) -> Self { Self { dependency, view: Box::new(view), element: RefCell::new(None), } } fn with_element<T>(&self, f: impl FnOnce(&Element<'_, Message, Theme, Renderer>) -> T) -> T { f(self .element .borrow() .as_ref() .unwrap() .borrow() .as_ref() .unwrap()) } fn with_element_mut<T>( &self, f: impl FnOnce(&mut Element<'_, Message, Theme, Renderer>) -> T, ) -> T { f(self .element .borrow() .as_ref() .unwrap() .borrow_mut() .as_mut() .unwrap()) } } struct Internal<Message, Theme, Renderer> { element: Rc<RefCell<Option<Element<'static, Message, Theme, Renderer>>>>, hash: u64, } impl<'a, Message, Theme, Renderer, Dependency, View> Widget<Message, Theme, Renderer> for Lazy<'a, Message, Theme, Renderer, Dependency, View> where View: Into<Element<'static, Message, Theme, Renderer>> + 'static, Dependency: Hash + 'a, Message: 'static, Theme: 'static, Renderer: core::Renderer + 'static, { fn tag(&self) -> tree::Tag { struct Tag<T>(T); tree::Tag::of::<Tag<View>>() } fn state(&self) -> tree::State { let hash = { let mut hasher = FxHasher::default(); self.dependency.hash(&mut hasher); hasher.finish() }; let element = Rc::new(RefCell::new(Some((self.view)(&self.dependency).into()))); (*self.element.borrow_mut()) = Some(element.clone()); tree::State::new(Internal { element, hash }) } fn children(&self) -> Vec<Tree> { self.with_element(|element| vec![Tree::new(element.as_widget())]) } fn diff(&self, tree: &mut Tree) { let current = tree .state .downcast_mut::<Internal<Message, Theme, Renderer>>(); let new_hash = { let mut hasher = FxHasher::default(); self.dependency.hash(&mut hasher); hasher.finish() }; if current.hash != new_hash { current.hash = new_hash; let element = (self.view)(&self.dependency).into(); current.element = Rc::new(RefCell::new(Some(element))); (*self.element.borrow_mut()) = Some(current.element.clone()); self.with_element(|element| { tree.diff_children(std::slice::from_ref(&element.as_widget())); }); } else { (*self.element.borrow_mut()) = Some(current.element.clone()); } } fn size(&self) -> Size<Length> { self.with_element(|element| element.as_widget().size()) } fn size_hint(&self) -> Size<Length> { Size { width: Length::Shrink, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { self.with_element_mut(|element| { element .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) }) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.with_element_mut(|element| { element .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.with_element_mut(|element| { element.as_widget_mut().update( &mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport, ); }); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.with_element(|element| { element.as_widget().mouse_interaction( &tree.children[0], layout, cursor, viewport, renderer, ) }) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.with_element(|element| { element.as_widget().draw( &tree.children[0], renderer, theme, style, layout, cursor, viewport, ); }); } 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 overlay = InnerBuilder { cell: self.element.borrow().as_ref().unwrap().clone(), element: self .element .borrow() .as_ref() .unwrap() .borrow_mut() .take() .unwrap(), tree: &mut tree.children[0], layout, overlay_builder: |element, tree, layout| { element .as_widget_mut() .overlay(tree, *layout, renderer, viewport, translation) .map(|overlay| RefCell::new(overlay::Nested::new(overlay))) }, } .build(); #[allow(clippy::redundant_closure_for_method_calls)] if overlay.with_overlay(|overlay| overlay.is_some()) { Some(overlay::Element::new(Box::new(Overlay(Some(overlay))))) } else { let heads = overlay.into_heads(); // - You may not like it, but this is what peak performance looks like // - TODO: Get rid of ouroboros, for good // - What?! *self.element.borrow().as_ref().unwrap().borrow_mut() = Some(heads.element); None } } } #[self_referencing] struct Inner<'a, Message: 'a, Theme: 'a, Renderer: 'a> { cell: Rc<RefCell<Option<Element<'static, Message, Theme, Renderer>>>>, element: Element<'static, Message, Theme, Renderer>, tree: &'a mut Tree, layout: Layout<'a>, #[borrows(mut element, mut tree, layout)] #[not_covariant] overlay: Option<RefCell<overlay::Nested<'this, Message, Theme, Renderer>>>, } struct Overlay<'a, Message, Theme, Renderer>(Option<Inner<'a, Message, Theme, Renderer>>); impl<Message, Theme, Renderer> Drop for Overlay<'_, Message, Theme, Renderer> { fn drop(&mut self) { let heads = self.0.take().unwrap().into_heads(); (*heads.cell.borrow_mut()) = Some(heads.element); } } impl<Message, Theme, Renderer> Overlay<'_, Message, Theme, Renderer> { fn with_overlay_maybe<T>( &self, f: impl FnOnce(&mut overlay::Nested<'_, Message, Theme, Renderer>) -> T, ) -> Option<T> { self.0 .as_ref() .unwrap() .with_overlay(|overlay| overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut()))) } fn with_overlay_mut_maybe<T>( &mut self, f: impl FnOnce(&mut overlay::Nested<'_, Message, Theme, Renderer>) -> T, ) -> Option<T> { self.0 .as_mut() .unwrap() .with_overlay_mut(|overlay| overlay.as_mut().map(|nested| (f)(nested.get_mut()))) } } impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer> for Overlay<'_, Message, Theme, Renderer> where Renderer: core::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { self.with_overlay_maybe(|overlay| overlay.layout(renderer, bounds)) .unwrap_or_default() } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { let _ = self.with_overlay_maybe(|overlay| { overlay.draw(renderer, theme, style, layout, cursor); }); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.with_overlay_maybe(|overlay| overlay.mouse_interaction(layout, cursor, renderer)) .unwrap_or_default() } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { let _ = self.with_overlay_mut_maybe(|overlay| { overlay.update(event, layout, cursor, renderer, clipboard, shell); }); } } impl<'a, Message, Theme, Renderer, Dependency, View> From<Lazy<'a, Message, Theme, Renderer, Dependency, View>> for Element<'a, Message, Theme, Renderer> where View: Into<Element<'static, Message, Theme, Renderer>> + 'static, Renderer: core::Renderer + 'static, Message: 'static, Theme: 'static, Dependency: Hash + 'a, { fn from(lazy: Lazy<'a, Message, Theme, Renderer, Dependency, View>) -> Self { Self::new(lazy) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/stack.rs
widget/src/stack.rs
//! Display content on top of other content. use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ Clipboard, Element, Event, Layout, Length, Rectangle, Shell, Size, Vector, Widget, }; /// A container that displays children on top of each other. /// /// The first [`Element`] dictates the intrinsic [`Size`] of a [`Stack`] and /// will be displayed as the base layer. Every consecutive [`Element`] will be /// rendered on top; on its own layer. /// /// You can use [`push_under`](Self::push_under) to push an [`Element`] under /// the current [`Stack`] without affecting its intrinsic [`Size`]. /// /// Keep in mind that too much layering will normally produce bad UX as well as /// introduce certain rendering overhead. Use this widget sparingly! pub struct Stack<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { width: Length, height: Length, children: Vec<Element<'a, Message, Theme, Renderer>>, clip: bool, base_layer: usize, } impl<'a, Message, Theme, Renderer> Stack<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Creates an empty [`Stack`]. pub fn new() -> Self { Self::from_vec(Vec::new()) } /// Creates a [`Stack`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { Self::from_vec(Vec::with_capacity(capacity)) } /// Creates a [`Stack`] with the given elements. pub fn with_children( children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { let iterator = children.into_iter(); Self::with_capacity(iterator.size_hint().0).extend(iterator) } /// Creates a [`Stack`] from an already allocated [`Vec`]. /// /// Keep in mind that the [`Stack`] will not inspect the [`Vec`], which means /// it won't automatically adapt to the sizing strategy of its contents. /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Stack::width`] or [`Stack::height`] accordingly. pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self { Self { width: Length::Shrink, height: Length::Shrink, children, clip: false, base_layer: 0, } } /// Sets the width of the [`Stack`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Stack`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Adds an element on top of the [`Stack`]. pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); if !child_size.is_void() { if self.children.is_empty() { self.width = self.width.enclose(child_size.width); self.height = self.height.enclose(child_size.height); } self.children.push(child); } self } /// Adds an element under the [`Stack`]. pub fn push_under(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { self.children.insert(0, child.into()); self.base_layer += 1; self } /// Extends the [`Stack`] with the given children. pub fn extend( self, children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>, ) -> Self { children.into_iter().fold(self, Self::push) } /// Sets whether the [`Stack`] should clip overflowing content. /// /// It has a slight performance overhead during presentation. /// /// By default, it is set to `false`. pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } } impl<Message, Renderer> Default for Stack<'_, Message, Renderer> where Renderer: crate::core::Renderer, { fn default() -> Self { Self::new() } } impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Stack<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { fn children(&self) -> Vec<Tree> { self.children.iter().map(Tree::new).collect() } fn diff(&self, tree: &mut Tree) { tree.diff_children(&self.children); } 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 { let limits = limits.width(self.width).height(self.height); if self.children.len() <= self.base_layer { return layout::Node::new(limits.resolve(self.width, self.height, Size::ZERO)); } let base = self.children[self.base_layer].as_widget_mut().layout( &mut tree.children[self.base_layer], renderer, &limits, ); let size = limits.resolve(self.width, self.height, base.size()); let limits = layout::Limits::new(Size::ZERO, size); let (under, above) = self.children.split_at_mut(self.base_layer); let (tree_under, tree_above) = tree.children.split_at_mut(self.base_layer); let nodes = under .iter_mut() .zip(tree_under) .map(|(layer, tree)| layer.as_widget_mut().layout(tree, renderer, &limits)) .chain(std::iter::once(base)) .chain( above[1..] .iter_mut() .zip(&mut tree_above[1..]) .map(|(layer, tree)| layer.as_widget_mut().layout(tree, renderer, &limits)), ) .collect(); layout::Node::with_children(size, nodes) } 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.children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, layout, renderer, operation); }); }); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, mut cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { if self.children.is_empty() { return; } let is_over = cursor.is_over(layout.bounds()); let end = self.children.len() - 1; for (i, ((child, tree), layout)) in self .children .iter_mut() .rev() .zip(tree.children.iter_mut().rev()) .zip(layout.children().rev()) .enumerate() { child.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); if shell.is_event_captured() { return; } if i < end && is_over && !cursor.is_levitating() { let interaction = child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer); if interaction != mouse::Interaction::None { cursor = cursor.levitate(); } } } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .rev() .zip(tree.children.iter().rev()) .zip(layout.children().rev()) .map(|((child, tree), layout)| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .find(|&interaction| interaction != mouse::Interaction::None) .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if let Some(clipped_viewport) = layout.bounds().intersection(viewport) { let viewport = if self.clip { &clipped_viewport } else { viewport }; let layers_under = if cursor.is_over(layout.bounds()) { self.children .iter() .rev() .zip(tree.children.iter().rev()) .zip(layout.children().rev()) .position(|((layer, tree), layout)| { let interaction = layer .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer); interaction != mouse::Interaction::None }) .map(|i| self.children.len() - i - 1) .unwrap_or_default() } else { 0 }; let mut layers = self .children .iter() .zip(&tree.children) .zip(layout.children()) .enumerate(); let layers = layers.by_ref(); let mut draw_layer = |i, layer: &Element<'a, Message, Theme, Renderer>, tree, layout, cursor| { if i > 0 { renderer.with_layer(*viewport, |renderer| { layer .as_widget() .draw(tree, renderer, theme, style, layout, cursor, viewport); }); } else { layer .as_widget() .draw(tree, renderer, theme, style, layout, cursor, viewport); } }; for (i, ((layer, tree), layout)) in layers.take(layers_under) { draw_layer(i, layer, tree, layout, mouse::Cursor::Unavailable); } for (i, ((layer, tree), layout)) in layers { draw_layer(i, layer, tree, layout, cursor); } } } 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>> { overlay::from_children( &mut self.children, tree, layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Stack<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(stack: Stack<'a, Message, Theme, Renderer>) -> Self { Self::new(stack) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/radio.rs
widget/src/radio.rs
//! Radio buttons let users choose a single option from a bunch of options. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::{column, radio}; //! //! struct State { //! selection: Option<Choice>, //! } //! //! #[derive(Debug, Clone, Copy)] //! enum Message { //! RadioSelected(Choice), //! } //! //! #[derive(Debug, Clone, Copy, PartialEq, Eq)] //! enum Choice { //! A, //! B, //! C, //! All, //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! let a = radio( //! "A", //! Choice::A, //! state.selection, //! Message::RadioSelected, //! ); //! //! let b = radio( //! "B", //! Choice::B, //! state.selection, //! Message::RadioSelected, //! ); //! //! let c = radio( //! "C", //! Choice::C, //! state.selection, //! Message::RadioSelected, //! ); //! //! let all = radio( //! "All of the above", //! Choice::All, //! state.selection, //! Message::RadioSelected //! ); //! //! column![a, b, c, all].into() //! } //! ``` use crate::core::alignment; use crate::core::border::{self, Border}; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::text; use crate::core::touch; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Clipboard, Color, Element, Event, Layout, Length, Pixels, Rectangle, Shell, Size, Theme, Widget, }; /// A circular button representing a choice. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::{column, radio}; /// /// struct State { /// selection: Option<Choice>, /// } /// /// #[derive(Debug, Clone, Copy)] /// enum Message { /// RadioSelected(Choice), /// } /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// enum Choice { /// A, /// B, /// C, /// All, /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// let a = radio( /// "A", /// Choice::A, /// state.selection, /// Message::RadioSelected, /// ); /// /// let b = radio( /// "B", /// Choice::B, /// state.selection, /// Message::RadioSelected, /// ); /// /// let c = radio( /// "C", /// Choice::C, /// state.selection, /// Message::RadioSelected, /// ); /// /// let all = radio( /// "All of the above", /// Choice::All, /// state.selection, /// Message::RadioSelected /// ); /// /// column![a, b, c, all].into() /// } /// ``` pub struct Radio<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, { is_selected: bool, on_click: Message, label: String, width: Length, size: f32, spacing: f32, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_shaping: text::Shaping, text_wrapping: text::Wrapping, font: Option<Renderer::Font>, class: Theme::Class<'a>, last_status: Option<Status>, } impl<'a, Message, Theme, Renderer> Radio<'a, Message, Theme, Renderer> where Message: Clone, Theme: Catalog, Renderer: text::Renderer, { /// The default size of a [`Radio`] button. pub const DEFAULT_SIZE: f32 = 16.0; /// The default spacing of a [`Radio`] button. pub const DEFAULT_SPACING: f32 = 8.0; /// Creates a new [`Radio`] button. /// /// It expects: /// * the value related to the [`Radio`] button /// * the label of the [`Radio`] button /// * the current selected value /// * a function that will be called when the [`Radio`] is selected. It /// receives the value of the radio and must produce a `Message`. pub fn new<F, V>(label: impl Into<String>, value: V, selected: Option<V>, f: F) -> Self where V: Eq + Copy, F: FnOnce(V) -> Message, { Radio { is_selected: Some(value) == selected, on_click: f(value), label: label.into(), width: Length::Shrink, size: Self::DEFAULT_SIZE, spacing: Self::DEFAULT_SPACING, text_size: None, text_line_height: text::LineHeight::default(), text_shaping: text::Shaping::default(), text_wrapping: text::Wrapping::default(), font: None, class: Theme::default(), last_status: None, } } /// Sets the size of the [`Radio`] button. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = size.into().0; self } /// Sets the width of the [`Radio`] button. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the spacing between the [`Radio`] button and the text. pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self { self.spacing = spacing.into().0; self } /// Sets the text size of the [`Radio`] button. pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self { self.text_size = Some(text_size.into()); self } /// Sets the text [`text::LineHeight`] of the [`Radio`] button. pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.text_line_height = line_height.into(); self } /// Sets the [`text::Shaping`] strategy of the [`Radio`] button. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the [`text::Wrapping`] strategy of the [`Radio`] button. pub fn text_wrapping(mut self, wrapping: text::Wrapping) -> Self { self.text_wrapping = wrapping; self } /// Sets the text font of the [`Radio`] button. pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the style of the [`Radio`] button. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Radio`] button. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Radio<'_, Message, Theme, Renderer> where Message: Clone, Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<widget::text::State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(widget::text::State::<Renderer::Paragraph>::default()) } fn size(&self) -> Size<Length> { Size { width: self.width, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { layout::next_to_each_other( &limits.width(self.width), self.spacing, |_| layout::Node::new(Size::new(self.size, self.size)), |limits| { let state = tree .state .downcast_mut::<widget::text::State<Renderer::Paragraph>>(); widget::text::layout( state, renderer, limits, &self.label, widget::text::Format { width: self.width, height: Length::Shrink, line_height: self.text_line_height, size: self.text_size, font: self.font, align_x: text::Alignment::Default, align_y: alignment::Vertical::Top, shaping: self.text_shaping, wrapping: self.text_wrapping, }, ) }, ) } 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, ) { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if cursor.is_over(layout.bounds()) { shell.publish(self.on_click.clone()); shell.capture_event(); } } _ => {} } let current_status = { let is_mouse_over = cursor.is_over(layout.bounds()); let is_selected = self.is_selected; if is_mouse_over { Status::Hovered { is_selected } } else { Status::Active { is_selected } } }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.last_status = Some(current_status); } else if self .last_status .is_some_and(|last_status| last_status != current_status) { shell.request_redraw(); } } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { if cursor.is_over(layout.bounds()) { mouse::Interaction::Pointer } else { mouse::Interaction::default() } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let mut children = layout.children(); let style = theme.style( &self.class, self.last_status.unwrap_or(Status::Active { is_selected: self.is_selected, }), ); { let layout = children.next().unwrap(); let bounds = layout.bounds(); let size = bounds.width; let dot_size = size / 2.0; renderer.fill_quad( renderer::Quad { bounds, border: Border { radius: (size / 2.0).into(), width: style.border_width, color: style.border_color, }, ..renderer::Quad::default() }, style.background, ); if self.is_selected { renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x + dot_size / 2.0, y: bounds.y + dot_size / 2.0, width: bounds.width - dot_size, height: bounds.height - dot_size, }, border: border::rounded(dot_size / 2.0), ..renderer::Quad::default() }, style.dot_color, ); } } { let label_layout = children.next().unwrap(); let state: &widget::text::State<Renderer::Paragraph> = tree.state.downcast_ref(); crate::text::draw( renderer, defaults, label_layout.bounds(), state.raw(), crate::text::Style { color: style.text_color, }, viewport, ); } } } impl<'a, Message, Theme, Renderer> From<Radio<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a + Clone, Theme: 'a + Catalog, Renderer: 'a + text::Renderer, { fn from(radio: Radio<'a, Message, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> { Element::new(radio) } } /// The possible status of a [`Radio`] button. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Radio`] button can be interacted with. Active { /// Indicates whether the [`Radio`] button is currently selected. is_selected: bool, }, /// The [`Radio`] button is being hovered. Hovered { /// Indicates whether the [`Radio`] button is currently selected. is_selected: bool, }, } /// The appearance of a radio button. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Background`] of the radio button. pub background: Background, /// The [`Color`] of the dot of the radio button. pub dot_color: Color, /// The border width of the radio button. pub border_width: f32, /// The border [`Color`] of the radio button. pub border_color: Color, /// The text [`Color`] of the radio button. pub text_color: Option<Color>, } /// The theme catalog of a [`Radio`]. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } /// A styling function for a [`Radio`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// The default style of a [`Radio`] button. pub fn default(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); let active = Style { background: Color::TRANSPARENT.into(), dot_color: palette.primary.strong.color, border_width: 1.0, border_color: palette.primary.strong.color, text_color: None, }; match status { Status::Active { .. } => active, Status::Hovered { .. } => Style { dot_color: palette.primary.strong.color, background: palette.primary.weak.color.into(), ..active }, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/float.rs
widget/src/float.rs
//! Make elements float! use crate::core; use crate::core::border; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::widget::tree; use crate::core::{ Clipboard, Element, Event, Layout, Length, Rectangle, Shadow, Shell, Size, Transformation, Vector, Widget, }; /// A widget that can make its contents float over other widgets. pub struct Float<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, { content: Element<'a, Message, Theme, Renderer>, scale: f32, translate: Option<Box<dyn Fn(Rectangle, Rectangle) -> Vector + 'a>>, class: Theme::Class<'a>, } impl<'a, Message, Theme, Renderer> Float<'a, Message, Theme, Renderer> where Theme: Catalog, { /// Creates a new [`Float`] widget with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { content: content.into(), scale: 1.0, translate: None, class: Theme::default(), } } /// Sets the scale to be applied to the contents of the [`Float`]. pub fn scale(mut self, scale: f32) -> Self { self.scale = scale; self } /// Sets the translation logic to be applied to the contents of the [`Float`]. /// /// The logic takes the original (non-scaled) bounds of the contents and the /// viewport bounds. These bounds can be useful to ensure the floating elements /// always stay on screen. pub fn translate(mut self, translate: impl Fn(Rectangle, Rectangle) -> Vector + 'a) -> Self { self.translate = Some(Box::new(translate)); self } /// Sets the style of the [`Float`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Float`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } fn is_floating(&self, bounds: Rectangle, viewport: Rectangle) -> bool { self.scale > 1.0 || self .translate .as_ref() .is_some_and(|translate| translate(bounds, viewport) != Vector::ZERO) } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Float<'_, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { self.content.as_widget().tag() } fn state(&self) -> tree::State { self.content.as_widget().state() } fn children(&self) -> Vec<tree::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 size_hint(&self) -> Size<Length> { self.content.as_widget().size_hint() } 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 update( &mut self, tree: &mut widget::Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { if self.is_floating(layout.bounds(), *viewport) { return; } self.content.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { if self.is_floating(layout.bounds(), *viewport) { return; } { let style = theme.style(&self.class); if style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds: layout.bounds().shrink(1.0), shadow: style.shadow, border: border::rounded(style.shadow_border_radius), snap: false, }, style.shadow.color, ); } } 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 self.is_floating(layout.bounds(), *viewport) { return mouse::Interaction::None; } self.content .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) } fn operate( &mut self, tree: &mut widget::Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content .as_widget_mut() .operate(tree, layout, renderer, operation); } fn overlay<'a>( &'a mut self, state: &'a mut widget::Tree, layout: Layout<'a>, renderer: &Renderer, viewport: &Rectangle, offset: Vector, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { let bounds = layout.bounds(); let translation = self .translate .as_ref() .map(|translate| translate(bounds + offset, *viewport)) .unwrap_or(Vector::ZERO); if self.scale > 1.0 || translation != Vector::ZERO { let translation = translation + offset; let transformation = Transformation::translate( bounds.x + bounds.width / 2.0 + translation.x, bounds.y + bounds.height / 2.0 + translation.y, ) * Transformation::scale(self.scale) * Transformation::translate( -bounds.x - bounds.width / 2.0, -bounds.y - bounds.height / 2.0, ); Some(overlay::Element::new(Box::new(Overlay { float: self, state, layout, viewport: *viewport, transformation, }))) } else { self.content .as_widget_mut() .overlay(state, layout, renderer, viewport, offset) } } } impl<'a, Message, Theme, Renderer> From<Float<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from(float: Float<'a, Message, Theme, Renderer>) -> Self { Element::new(float) } } struct Overlay<'a, 'b, Message, Theme, Renderer> where Theme: Catalog, { float: &'a mut Float<'b, Message, Theme, Renderer>, state: &'a mut widget::Tree, layout: Layout<'a>, viewport: Rectangle, transformation: Transformation, } impl<Message, Theme, Renderer> core::Overlay<Message, Theme, Renderer> for Overlay<'_, '_, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { fn layout(&mut self, _renderer: &Renderer, _bounds: Size) -> layout::Node { let bounds = self.layout.bounds() * self.transformation; layout::Node::new(bounds.size()).move_to(bounds.position()) } fn update( &mut self, event: &Event, _layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { let inverse = self.transformation.inverse(); self.float.content.as_widget_mut().update( self.state, event, self.layout, cursor * inverse, renderer, clipboard, shell, &(self.viewport * inverse), ); } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, _layout: Layout<'_>, cursor: mouse::Cursor, ) { let bounds = self.layout.bounds(); let inverse = self.transformation.inverse(); renderer.with_layer(self.viewport, |renderer| { renderer.with_transformation(self.transformation, |renderer| { { let style = theme.style(&self.float.class); if style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds: bounds.shrink(1.0), shadow: style.shadow, border: border::rounded(style.shadow_border_radius), snap: false, }, style.shadow.color, ); } } self.float.content.as_widget().draw( self.state, renderer, theme, style, self.layout, cursor * inverse, &(self.viewport * inverse), ); }); }); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { if !cursor.is_over(layout.bounds()) { return mouse::Interaction::None; } let inverse = self.transformation.inverse(); self.float.content.as_widget().mouse_interaction( self.state, self.layout, cursor * inverse, &(self.viewport * inverse), renderer, ) } fn index(&self) -> f32 { self.float.scale * 0.5 } fn overlay<'a>( &'a mut self, _layout: Layout<'_>, renderer: &Renderer, ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { self.float.content.as_widget_mut().overlay( self.state, self.layout, renderer, &(self.viewport * self.transformation.inverse()), self.transformation.translation(), ) } } /// The theme catalog of a [`Float`]. /// /// All themes that can be used with [`Float`] /// must implement this trait. pub trait Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`Float`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for crate::Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(|_| Style::default()) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The style of a [`Float`]. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Style { /// The [`Shadow`] of the [`Float`]. pub shadow: Shadow, /// The border radius of the shadow. pub shadow_border_radius: border::Radius, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/checkbox.rs
widget/src/checkbox.rs
//! Checkboxes can be used to let users make binary choices. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::checkbox; //! //! struct State { //! is_checked: bool, //! } //! //! enum Message { //! CheckboxToggled(bool), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! checkbox(state.is_checked) //! .label("Toggle me!") //! .on_toggle(Message::CheckboxToggled) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::CheckboxToggled(is_checked) => { //! state.is_checked = is_checked; //! } //! } //! } //! ``` //! ![Checkbox drawn by `iced_wgpu`](https://github.com/iced-rs/iced/blob/7760618fb112074bc40b148944521f312152012a/docs/images/checkbox.png?raw=true) use crate::core::alignment; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::text; use crate::core::theme::palette; use crate::core::touch; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Border, Clipboard, Color, Element, Event, Layout, Length, Pixels, Rectangle, Shell, Size, Theme, Widget, }; /// A box that can be checked. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::checkbox; /// /// struct State { /// is_checked: bool, /// } /// /// enum Message { /// CheckboxToggled(bool), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// checkbox(state.is_checked) /// .label("Toggle me!") /// .on_toggle(Message::CheckboxToggled) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::CheckboxToggled(is_checked) => { /// state.is_checked = is_checked; /// } /// } /// } /// ``` /// ![Checkbox drawn by `iced_wgpu`](https://github.com/iced-rs/iced/blob/7760618fb112074bc40b148944521f312152012a/docs/images/checkbox.png?raw=true) pub struct Checkbox<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Renderer: text::Renderer, Theme: Catalog, { is_checked: bool, on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>, label: Option<text::Fragment<'a>>, width: Length, size: f32, spacing: f32, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_shaping: text::Shaping, text_wrapping: text::Wrapping, font: Option<Renderer::Font>, icon: Icon<Renderer::Font>, class: Theme::Class<'a>, last_status: Option<Status>, } impl<'a, Message, Theme, Renderer> Checkbox<'a, Message, Theme, Renderer> where Renderer: text::Renderer, Theme: Catalog, { /// The default size of a [`Checkbox`]. const DEFAULT_SIZE: f32 = 16.0; /// Creates a new [`Checkbox`]. /// /// It expects: /// * a boolean describing whether the [`Checkbox`] is checked or not pub fn new(is_checked: bool) -> Self { Checkbox { is_checked, on_toggle: None, label: None, width: Length::Shrink, size: Self::DEFAULT_SIZE, spacing: Self::DEFAULT_SIZE / 2.0, text_size: None, text_line_height: text::LineHeight::default(), text_shaping: text::Shaping::default(), text_wrapping: text::Wrapping::default(), font: None, icon: Icon { font: Renderer::ICON_FONT, code_point: Renderer::CHECKMARK_ICON, size: None, line_height: text::LineHeight::default(), shaping: text::Shaping::Basic, }, class: Theme::default(), last_status: None, } } /// Sets the label of the [`Checkbox`]. pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self { self.label = Some(label.into_fragment()); self } /// Sets the function that will be called when the [`Checkbox`] is toggled. /// It will receive the new state of the [`Checkbox`] and must produce a /// `Message`. /// /// Unless `on_toggle` is called, the [`Checkbox`] will be disabled. pub fn on_toggle<F>(mut self, f: F) -> Self where F: 'a + Fn(bool) -> Message, { self.on_toggle = Some(Box::new(f)); self } /// Sets the function that will be called when the [`Checkbox`] is toggled, /// if `Some`. /// /// If `None`, the checkbox will be disabled. pub fn on_toggle_maybe<F>(mut self, f: Option<F>) -> Self where F: Fn(bool) -> Message + 'a, { self.on_toggle = f.map(|f| Box::new(f) as _); self } /// Sets the size of the [`Checkbox`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = size.into().0; self } /// Sets the width of the [`Checkbox`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the spacing between the [`Checkbox`] and the text. pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self { self.spacing = spacing.into().0; self } /// Sets the text size of the [`Checkbox`]. pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self { self.text_size = Some(text_size.into()); self } /// Sets the text [`text::LineHeight`] of the [`Checkbox`]. pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.text_line_height = line_height.into(); self } /// Sets the [`text::Shaping`] strategy of the [`Checkbox`]. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the [`text::Wrapping`] strategy of the [`Checkbox`]. pub fn text_wrapping(mut self, wrapping: text::Wrapping) -> Self { self.text_wrapping = wrapping; self } /// Sets the [`Renderer::Font`] of the text of the [`Checkbox`]. /// /// [`Renderer::Font`]: crate::core::text::Renderer pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the [`Icon`] of the [`Checkbox`]. pub fn icon(mut self, icon: Icon<Renderer::Font>) -> Self { self.icon = icon; self } /// Sets the style of the [`Checkbox`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Checkbox`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Checkbox<'_, Message, Theme, Renderer> where Renderer: text::Renderer, Theme: Catalog, { fn tag(&self) -> tree::Tag { tree::Tag::of::<widget::text::State<Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(widget::text::State::<Renderer::Paragraph>::default()) } fn size(&self) -> Size<Length> { Size { width: self.width, height: Length::Shrink, } } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { layout::next_to_each_other( &limits.width(self.width), if self.label.is_some() { self.spacing } else { 0.0 }, |_| layout::Node::new(Size::new(self.size, self.size)), |limits| { if let Some(label) = self.label.as_deref() { let state = tree .state .downcast_mut::<widget::text::State<Renderer::Paragraph>>(); widget::text::layout( state, renderer, limits, label, widget::text::Format { width: self.width, height: Length::Shrink, line_height: self.text_line_height, size: self.text_size, font: self.font, align_x: text::Alignment::Default, align_y: alignment::Vertical::Top, shaping: self.text_shaping, wrapping: self.text_wrapping, }, ) } else { layout::Node::new(Size::ZERO) } }, ) } 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, ) { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let mouse_over = cursor.is_over(layout.bounds()); if mouse_over && let Some(on_toggle) = &self.on_toggle { shell.publish((on_toggle)(!self.is_checked)); shell.capture_event(); } } _ => {} } let current_status = { let is_mouse_over = cursor.is_over(layout.bounds()); let is_disabled = self.on_toggle.is_none(); let is_checked = self.is_checked; if is_disabled { Status::Disabled { is_checked } } else if is_mouse_over { Status::Hovered { is_checked } } else { Status::Active { is_checked } } }; if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.last_status = Some(current_status); } else if self .last_status .is_some_and(|status| status != current_status) { shell.request_redraw(); } } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { if cursor.is_over(layout.bounds()) && self.on_toggle.is_some() { mouse::Interaction::Pointer } else { mouse::Interaction::default() } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let mut children = layout.children(); let style = theme.style( &self.class, self.last_status.unwrap_or(Status::Disabled { is_checked: self.is_checked, }), ); { let layout = children.next().unwrap(); let bounds = layout.bounds(); renderer.fill_quad( renderer::Quad { bounds, border: style.border, ..renderer::Quad::default() }, style.background, ); let Icon { font, code_point, size, line_height, shaping, } = &self.icon; let size = size.unwrap_or(Pixels(bounds.height * 0.7)); if self.is_checked { renderer.fill_text( text::Text { content: code_point.to_string(), font: *font, size, line_height: *line_height, bounds: bounds.size(), align_x: text::Alignment::Center, align_y: alignment::Vertical::Center, shaping: *shaping, wrapping: text::Wrapping::default(), hint_factor: None, }, bounds.center(), style.icon_color, *viewport, ); } } if self.label.is_none() { return; } { let label_layout = children.next().unwrap(); let state: &widget::text::State<Renderer::Paragraph> = tree.state.downcast_ref(); crate::text::draw( renderer, defaults, label_layout.bounds(), state.raw(), crate::text::Style { color: style.text_color, }, viewport, ); } } fn operate( &mut self, _tree: &mut Tree, layout: Layout<'_>, _renderer: &Renderer, operation: &mut dyn widget::Operation, ) { if let Some(label) = self.label.as_deref() { operation.text(None, layout.bounds(), label); } } } impl<'a, Message, Theme, Renderer> From<Checkbox<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a + Catalog, Renderer: 'a + text::Renderer, { fn from( checkbox: Checkbox<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(checkbox) } } /// The icon in a [`Checkbox`]. #[derive(Debug, Clone, PartialEq)] pub struct Icon<Font> { /// Font that will be used to display the `code_point`, pub font: Font, /// The unicode code point that will be used as the icon. pub code_point: char, /// Font size of the content. pub size: Option<Pixels>, /// The line height of the icon. pub line_height: text::LineHeight, /// The shaping strategy of the icon. pub shaping: text::Shaping, } /// The possible status of a [`Checkbox`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// The [`Checkbox`] can be interacted with. Active { /// Indicates if the [`Checkbox`] is currently checked. is_checked: bool, }, /// The [`Checkbox`] can be interacted with and it is being hovered. Hovered { /// Indicates if the [`Checkbox`] is currently checked. is_checked: bool, }, /// The [`Checkbox`] cannot be interacted with. Disabled { /// Indicates if the [`Checkbox`] is currently checked. is_checked: bool, }, } /// The style of a checkbox. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Background`] of the checkbox. pub background: Background, /// The icon [`Color`] of the checkbox. pub icon_color: Color, /// The [`Border`] of the checkbox. pub border: Border, /// The text [`Color`] of the checkbox. pub text_color: Option<Color>, } /// The theme catalog of a [`Checkbox`]. pub trait Catalog: Sized { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; } /// A styling function for a [`Checkbox`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(primary) } fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { class(self, status) } } /// A primary checkbox; denoting a main toggle. pub fn primary(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); match status { Status::Active { is_checked } => styled( palette.background.strong.color, palette.background.base, palette.primary.base.text, palette.primary.base, is_checked, ), Status::Hovered { is_checked } => styled( palette.background.strong.color, palette.background.weak, palette.primary.base.text, palette.primary.strong, is_checked, ), Status::Disabled { is_checked } => styled( palette.background.weak.color, palette.background.weaker, palette.primary.base.text, palette.background.strong, is_checked, ), } } /// A secondary checkbox; denoting a complementary toggle. pub fn secondary(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); match status { Status::Active { is_checked } => styled( palette.background.strong.color, palette.background.base, palette.background.base.text, palette.background.strong, is_checked, ), Status::Hovered { is_checked } => styled( palette.background.strong.color, palette.background.weak, palette.background.base.text, palette.background.strong, is_checked, ), Status::Disabled { is_checked } => styled( palette.background.weak.color, palette.background.weak, palette.background.base.text, palette.background.weak, is_checked, ), } } /// A success checkbox; denoting a positive toggle. pub fn success(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); match status { Status::Active { is_checked } => styled( palette.background.weak.color, palette.background.base, palette.success.base.text, palette.success.base, is_checked, ), Status::Hovered { is_checked } => styled( palette.background.strong.color, palette.background.weak, palette.success.base.text, palette.success.strong, is_checked, ), Status::Disabled { is_checked } => styled( palette.background.weak.color, palette.background.weak, palette.success.base.text, palette.success.weak, is_checked, ), } } /// A danger checkbox; denoting a negative toggle. pub fn danger(theme: &Theme, status: Status) -> Style { let palette = theme.extended_palette(); match status { Status::Active { is_checked } => styled( palette.background.strong.color, palette.background.base, palette.danger.base.text, palette.danger.base, is_checked, ), Status::Hovered { is_checked } => styled( palette.background.strong.color, palette.background.weak, palette.danger.base.text, palette.danger.strong, is_checked, ), Status::Disabled { is_checked } => styled( palette.background.weak.color, palette.background.weak, palette.danger.base.text, palette.danger.weak, is_checked, ), } } fn styled( border_color: Color, base: palette::Pair, icon_color: Color, accent: palette::Pair, is_checked: bool, ) -> Style { let (background, border) = if is_checked { (accent, accent.color) } else { (base, border_color) }; Style { background: Background::Color(background.color), icon_color, border: Border { radius: 2.0.into(), width: 1.0, color: border, }, text_color: None, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text_editor.rs
widget/src/text_editor.rs
//! Text editors display a multi-line text input for text editing. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::text_editor; //! //! struct State { //! content: text_editor::Content, //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! Edit(text_editor::Action) //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! text_editor(&state.content) //! .placeholder("Type something here...") //! .on_action(Message::Edit) //! .into() //! } //! //! fn update(state: &mut State, message: Message) { //! match message { //! Message::Edit(action) => { //! state.content.perform(action); //! } //! } //! } //! ``` use crate::core::alignment; use crate::core::clipboard::{self, Clipboard}; use crate::core::input_method; use crate::core::keyboard; use crate::core::keyboard::key; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::text::editor::Editor as _; use crate::core::text::highlighter::{self, Highlighter}; use crate::core::text::{self, LineHeight, Text, Wrapping}; use crate::core::theme; use crate::core::time::{Duration, Instant}; use crate::core::widget::operation; use crate::core::widget::{self, Widget}; use crate::core::window; use crate::core::{ Background, Border, Color, Element, Event, InputMethod, Length, Padding, Pixels, Point, Rectangle, Shell, Size, SmolStr, Theme, Vector, }; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::ops; use std::ops::DerefMut; use std::sync::Arc; pub use text::editor::{Action, Cursor, Edit, Line, LineEnding, Motion, Position, Selection}; /// A multi-line text input. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::text_editor; /// /// struct State { /// content: text_editor::Content, /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// Edit(text_editor::Action) /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// text_editor(&state.content) /// .placeholder("Type something here...") /// .on_action(Message::Edit) /// .into() /// } /// /// fn update(state: &mut State, message: Message) { /// match message { /// Message::Edit(action) => { /// state.content.perform(action); /// } /// } /// } /// ``` pub struct TextEditor<'a, Highlighter, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Highlighter: text::Highlighter, Theme: Catalog, Renderer: text::Renderer, { id: Option<widget::Id>, content: &'a Content<Renderer>, placeholder: Option<text::Fragment<'a>>, font: Option<Renderer::Font>, text_size: Option<Pixels>, line_height: LineHeight, width: Length, height: Length, min_height: f32, max_height: f32, padding: Padding, wrapping: Wrapping, class: Theme::Class<'a>, key_binding: Option<Box<dyn Fn(KeyPress) -> Option<Binding<Message>> + 'a>>, on_edit: Option<Box<dyn Fn(Action) -> Message + 'a>>, highlighter_settings: Highlighter::Settings, highlighter_format: fn(&Highlighter::Highlight, &Theme) -> highlighter::Format<Renderer::Font>, last_status: Option<Status>, } impl<'a, Message, Theme, Renderer> TextEditor<'a, highlighter::PlainText, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { /// Creates new [`TextEditor`] with the given [`Content`]. pub fn new(content: &'a Content<Renderer>) -> Self { Self { id: None, content, placeholder: None, font: None, text_size: None, line_height: LineHeight::default(), width: Length::Fill, height: Length::Shrink, min_height: 0.0, max_height: f32::INFINITY, padding: Padding::new(5.0), wrapping: Wrapping::default(), class: <Theme as Catalog>::default(), key_binding: None, on_edit: None, highlighter_settings: (), highlighter_format: |_highlight, _theme| highlighter::Format::default(), last_status: None, } } /// Sets the [`Id`](widget::Id) of the [`TextEditor`]. pub fn id(mut self, id: impl Into<widget::Id>) -> Self { self.id = Some(id.into()); self } } impl<'a, Highlighter, Message, Theme, Renderer> TextEditor<'a, Highlighter, Message, Theme, Renderer> where Highlighter: text::Highlighter, Theme: Catalog, Renderer: text::Renderer, { /// Sets the placeholder of the [`TextEditor`]. pub fn placeholder(mut self, placeholder: impl text::IntoFragment<'a>) -> Self { self.placeholder = Some(placeholder.into_fragment()); self } /// Sets the width of the [`TextEditor`]. pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = Length::from(width.into()); self } /// Sets the height of the [`TextEditor`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the minimum height of the [`TextEditor`]. pub fn min_height(mut self, min_height: impl Into<Pixels>) -> Self { self.min_height = min_height.into().0; self } /// Sets the maximum height of the [`TextEditor`]. pub fn max_height(mut self, max_height: impl Into<Pixels>) -> Self { self.max_height = max_height.into().0; self } /// Sets the message that should be produced when some action is performed in /// the [`TextEditor`]. /// /// If this method is not called, the [`TextEditor`] will be disabled. pub fn on_action(mut self, on_edit: impl Fn(Action) -> Message + 'a) -> Self { self.on_edit = Some(Box::new(on_edit)); self } /// Sets the [`Font`] of the [`TextEditor`]. /// /// [`Font`]: text::Renderer::Font pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the text size of the [`TextEditor`]. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.text_size = Some(size.into()); self } /// Sets the [`text::LineHeight`] of the [`TextEditor`]. pub fn line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.line_height = line_height.into(); self } /// Sets the [`Padding`] of the [`TextEditor`]. pub fn padding(mut self, padding: impl Into<Padding>) -> Self { self.padding = padding.into(); self } /// Sets the [`Wrapping`] strategy of the [`TextEditor`]. pub fn wrapping(mut self, wrapping: Wrapping) -> Self { self.wrapping = wrapping; self } /// Highlights the [`TextEditor`] using the given syntax and theme. #[cfg(feature = "highlighter")] pub fn highlight( self, syntax: &str, theme: iced_highlighter::Theme, ) -> TextEditor<'a, iced_highlighter::Highlighter, Message, Theme, Renderer> where Renderer: text::Renderer<Font = crate::core::Font>, { self.highlight_with::<iced_highlighter::Highlighter>( iced_highlighter::Settings { theme, token: syntax.to_owned(), }, |highlight, _theme| highlight.to_format(), ) } /// Highlights the [`TextEditor`] with the given [`Highlighter`] and /// a strategy to turn its highlights into some text format. pub fn highlight_with<H: text::Highlighter>( self, settings: H::Settings, to_format: fn(&H::Highlight, &Theme) -> highlighter::Format<Renderer::Font>, ) -> TextEditor<'a, H, Message, Theme, Renderer> { TextEditor { id: self.id, content: self.content, placeholder: self.placeholder, font: self.font, text_size: self.text_size, line_height: self.line_height, width: self.width, height: self.height, min_height: self.min_height, max_height: self.max_height, padding: self.padding, wrapping: self.wrapping, class: self.class, key_binding: self.key_binding, on_edit: self.on_edit, highlighter_settings: settings, highlighter_format: to_format, last_status: self.last_status, } } /// Sets the closure to produce key bindings on key presses. /// /// See [`Binding`] for the list of available bindings. pub fn key_binding( mut self, key_binding: impl Fn(KeyPress) -> Option<Binding<Message>> + 'a, ) -> Self { self.key_binding = Some(Box::new(key_binding)); self } /// Sets the style of the [`TextEditor`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`TextEditor`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } fn input_method<'b>( &self, state: &'b State<Highlighter>, renderer: &Renderer, layout: Layout<'_>, ) -> InputMethod<&'b str> { let Some(Focus { is_window_focused: true, .. }) = &state.focus else { return InputMethod::Disabled; }; let bounds = layout.bounds(); let internal = self.content.0.borrow_mut(); let text_bounds = bounds.shrink(self.padding); let translation = text_bounds.position() - Point::ORIGIN; let cursor = match internal.editor.selection() { Selection::Caret(position) => position, Selection::Range(ranges) => ranges.first().cloned().unwrap_or_default().position(), }; let line_height = self .line_height .to_absolute(self.text_size.unwrap_or_else(|| renderer.default_size())); let position = cursor + translation; InputMethod::Enabled { cursor: Rectangle::new(position, Size::new(1.0, f32::from(line_height))), purpose: input_method::Purpose::Normal, preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref), } } } /// The content of a [`TextEditor`]. pub struct Content<R = crate::Renderer>(RefCell<Internal<R>>) where R: text::Renderer; struct Internal<R> where R: text::Renderer, { editor: R::Editor, } impl<R> Content<R> where R: text::Renderer, { /// Creates an empty [`Content`]. pub fn new() -> Self { Self::with_text("") } /// Creates a [`Content`] with the given text. pub fn with_text(text: &str) -> Self { Self(RefCell::new(Internal { editor: R::Editor::with_text(text), })) } /// Performs an [`Action`] on the [`Content`]. pub fn perform(&mut self, action: Action) { let internal = self.0.get_mut(); internal.editor.perform(action); } /// Moves the current cursor to reflect the given one. pub fn move_to(&mut self, cursor: Cursor) { let internal = self.0.get_mut(); internal.editor.move_to(cursor); } /// Returns the current cursor position of the [`Content`]. pub fn cursor(&self) -> Cursor { self.0.borrow().editor.cursor() } /// Returns the amount of lines of the [`Content`]. pub fn line_count(&self) -> usize { self.0.borrow().editor.line_count() } /// Returns the text of the line at the given index, if it exists. pub fn line(&self, index: usize) -> Option<Line<'_>> { let internal = self.0.borrow(); let line = internal.editor.line(index)?; Some(Line { text: Cow::Owned(line.text.into_owned()), ending: line.ending, }) } /// Returns an iterator of the text of the lines in the [`Content`]. pub fn lines(&self) -> impl Iterator<Item = Line<'_>> { (0..) .map(|i| self.line(i)) .take_while(Option::is_some) .flatten() } /// Returns the text of the [`Content`]. pub fn text(&self) -> String { let mut contents = String::new(); let mut lines = self.lines().peekable(); while let Some(line) = lines.next() { contents.push_str(&line.text); if lines.peek().is_some() { contents.push_str(if line.ending == LineEnding::None { LineEnding::default().as_str() } else { line.ending.as_str() }); } } contents } /// Returns the selected text of the [`Content`]. pub fn selection(&self) -> Option<String> { self.0.borrow().editor.copy() } /// Returns the kind of [`LineEnding`] used for separating lines in the [`Content`]. pub fn line_ending(&self) -> Option<LineEnding> { Some(self.line(0)?.ending) } /// Returns whether or not the the [`Content`] is empty. pub fn is_empty(&self) -> bool { self.0.borrow().editor.is_empty() } } impl<Renderer> Clone for Content<Renderer> where Renderer: text::Renderer, { fn clone(&self) -> Self { Self::with_text(&self.text()) } } impl<Renderer> Default for Content<Renderer> where Renderer: text::Renderer, { fn default() -> Self { Self::new() } } impl<Renderer> fmt::Debug for Content<Renderer> where Renderer: text::Renderer, Renderer::Editor: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let internal = self.0.borrow(); f.debug_struct("Content") .field("editor", &internal.editor) .finish() } } /// The state of a [`TextEditor`]. #[derive(Debug)] pub struct State<Highlighter: text::Highlighter> { focus: Option<Focus>, preedit: Option<input_method::Preedit>, last_click: Option<mouse::Click>, drag_click: Option<mouse::click::Kind>, partial_scroll: f32, last_theme: RefCell<Option<String>>, highlighter: RefCell<Highlighter>, highlighter_settings: Highlighter::Settings, highlighter_format_address: usize, } #[derive(Debug, Clone)] struct Focus { updated_at: Instant, now: Instant, is_window_focused: bool, } impl Focus { const CURSOR_BLINK_INTERVAL_MILLIS: u128 = 500; fn now() -> Self { let now = Instant::now(); Self { updated_at: now, now, is_window_focused: true, } } fn is_cursor_visible(&self) -> bool { self.is_window_focused && ((self.now - self.updated_at).as_millis() / Self::CURSOR_BLINK_INTERVAL_MILLIS) .is_multiple_of(2) } } impl<Highlighter: text::Highlighter> State<Highlighter> { /// Returns whether the [`TextEditor`] is currently focused or not. pub fn is_focused(&self) -> bool { self.focus.is_some() } } impl<Highlighter: text::Highlighter> operation::Focusable for State<Highlighter> { fn is_focused(&self) -> bool { self.focus.is_some() } fn focus(&mut self) { self.focus = Some(Focus::now()); } fn unfocus(&mut self) { self.focus = None; } } impl<Highlighter, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for TextEditor<'_, Highlighter, Message, Theme, Renderer> where Highlighter: text::Highlighter, Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> widget::tree::Tag { widget::tree::Tag::of::<State<Highlighter>>() } fn state(&self) -> widget::tree::State { widget::tree::State::new(State { focus: None, preedit: None, last_click: None, drag_click: None, partial_scroll: 0.0, last_theme: RefCell::default(), highlighter: RefCell::new(Highlighter::new(&self.highlighter_settings)), highlighter_settings: self.highlighter_settings.clone(), highlighter_format_address: self.highlighter_format as usize, }) } fn size(&self) -> Size<Length> { Size { width: self.width, height: self.height, } } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> iced_renderer::core::layout::Node { let mut internal = self.content.0.borrow_mut(); let state = tree.state.downcast_mut::<State<Highlighter>>(); if state.highlighter_format_address != self.highlighter_format as usize { state.highlighter.borrow_mut().change_line(0); state.highlighter_format_address = self.highlighter_format as usize; } if state.highlighter_settings != self.highlighter_settings { state .highlighter .borrow_mut() .update(&self.highlighter_settings); state.highlighter_settings = self.highlighter_settings.clone(); } let limits = limits .width(self.width) .height(self.height) .min_height(self.min_height) .max_height(self.max_height); internal.editor.update( limits.shrink(self.padding).max(), self.font.unwrap_or_else(|| renderer.default_font()), self.text_size.unwrap_or_else(|| renderer.default_size()), self.line_height, self.wrapping, renderer.scale_factor(), state.highlighter.borrow_mut().deref_mut(), ); match self.height { Length::Fill | Length::FillPortion(_) | Length::Fixed(_) => { layout::Node::new(limits.max()) } Length::Shrink => { let min_bounds = internal.editor.min_bounds(); layout::Node::new( limits .height(min_bounds.height) .max() .expand(Size::new(0.0, self.padding.y())), ) } } } fn update( &mut self, tree: &mut widget::Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, _viewport: &Rectangle, ) { let Some(on_edit) = self.on_edit.as_ref() else { return; }; let state = tree.state.downcast_mut::<State<Highlighter>>(); let is_redraw = matches!(event, Event::Window(window::Event::RedrawRequested(_now)),); match event { Event::Window(window::Event::Unfocused) => { if let Some(focus) = &mut state.focus { focus.is_window_focused = false; } } Event::Window(window::Event::Focused) => { if let Some(focus) = &mut state.focus { focus.is_window_focused = true; focus.updated_at = Instant::now(); shell.request_redraw(); } } Event::Window(window::Event::RedrawRequested(now)) => { if let Some(focus) = &mut state.focus && focus.is_window_focused { focus.now = *now; let millis_until_redraw = Focus::CURSOR_BLINK_INTERVAL_MILLIS - (focus.now - focus.updated_at).as_millis() % Focus::CURSOR_BLINK_INTERVAL_MILLIS; shell.request_redraw_at( focus.now + Duration::from_millis(millis_until_redraw as u64), ); } } _ => {} } if let Some(update) = Update::from_event( event, state, layout.bounds(), self.padding, cursor, self.key_binding.as_deref(), ) { match update { Update::Click(click) => { let action = match click.kind() { mouse::click::Kind::Single => Action::Click(click.position()), mouse::click::Kind::Double => Action::SelectWord, mouse::click::Kind::Triple => Action::SelectLine, }; state.focus = Some(Focus::now()); state.last_click = Some(click); state.drag_click = Some(click.kind()); shell.publish(on_edit(action)); shell.capture_event(); } Update::Drag(position) => { shell.publish(on_edit(Action::Drag(position))); } Update::Release => { state.drag_click = None; } Update::Scroll(lines) => { let bounds = self.content.0.borrow().editor.bounds(); if bounds.height >= i32::MAX as f32 { return; } let lines = lines + state.partial_scroll; state.partial_scroll = lines.fract(); shell.publish(on_edit(Action::Scroll { lines: lines as i32, })); shell.capture_event(); } Update::InputMethod(update) => match update { Ime::Toggle(is_open) => { state.preedit = is_open.then(input_method::Preedit::new); shell.request_redraw(); } Ime::Preedit { content, selection } => { state.preedit = Some(input_method::Preedit { content, selection, text_size: self.text_size, }); shell.request_redraw(); } Ime::Commit(text) => { shell.publish(on_edit(Action::Edit(Edit::Paste(Arc::new(text))))); } }, Update::Binding(binding) => { fn apply_binding<H: text::Highlighter, R: text::Renderer, Message>( binding: Binding<Message>, content: &Content<R>, state: &mut State<H>, on_edit: &dyn Fn(Action) -> Message, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { let mut publish = |action| shell.publish(on_edit(action)); match binding { Binding::Unfocus => { state.focus = None; state.drag_click = None; } Binding::Copy => { if let Some(selection) = content.selection() { clipboard.write(clipboard::Kind::Standard, selection); } } Binding::Cut => { if let Some(selection) = content.selection() { clipboard.write(clipboard::Kind::Standard, selection); publish(Action::Edit(Edit::Delete)); } } Binding::Paste => { if let Some(contents) = clipboard.read(clipboard::Kind::Standard) { publish(Action::Edit(Edit::Paste(Arc::new(contents)))); } } Binding::Move(motion) => { publish(Action::Move(motion)); } Binding::Select(motion) => { publish(Action::Select(motion)); } Binding::SelectWord => { publish(Action::SelectWord); } Binding::SelectLine => { publish(Action::SelectLine); } Binding::SelectAll => { publish(Action::SelectAll); } Binding::Insert(c) => { publish(Action::Edit(Edit::Insert(c))); } Binding::Enter => { publish(Action::Edit(Edit::Enter)); } Binding::Backspace => { publish(Action::Edit(Edit::Backspace)); } Binding::Delete => { publish(Action::Edit(Edit::Delete)); } Binding::Sequence(sequence) => { for binding in sequence { apply_binding( binding, content, state, on_edit, clipboard, shell, ); } } Binding::Custom(message) => { shell.publish(message); } } } if !matches!(binding, Binding::Unfocus) { shell.capture_event(); } apply_binding(binding, self.content, state, on_edit, clipboard, shell); if let Some(focus) = &mut state.focus { focus.updated_at = Instant::now(); } } } } let status = { let is_disabled = self.on_edit.is_none(); let is_hovered = cursor.is_over(layout.bounds()); if is_disabled { Status::Disabled } else if state.focus.is_some() { Status::Focused { is_hovered } } else if is_hovered { Status::Hovered } else { Status::Active } }; if is_redraw { self.last_status = Some(status); shell.request_input_method(&self.input_method(state, renderer, layout)); } else if self .last_status .is_some_and(|last_status| status != last_status) { shell.request_redraw(); } } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, theme: &Theme, _defaults: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { let bounds = layout.bounds(); let mut internal = self.content.0.borrow_mut(); let state = tree.state.downcast_ref::<State<Highlighter>>(); let font = self.font.unwrap_or_else(|| renderer.default_font()); let theme_name = theme.name(); if state .last_theme .borrow() .as_ref() .is_none_or(|last_theme| last_theme != theme_name) { state.highlighter.borrow_mut().change_line(0); let _ = state.last_theme.borrow_mut().replace(theme_name.to_owned()); } internal.editor.highlight( font, state.highlighter.borrow_mut().deref_mut(), |highlight| (self.highlighter_format)(highlight, theme), ); let style = theme.style(&self.class, self.last_status.unwrap_or(Status::Active)); renderer.fill_quad( renderer::Quad { bounds, border: style.border, ..renderer::Quad::default() }, style.background, ); let text_bounds = bounds.shrink(self.padding); if internal.editor.is_empty() { if let Some(placeholder) = self.placeholder.clone() { renderer.fill_text( Text { content: placeholder.into_owned(), bounds: text_bounds.size(), size: self.text_size.unwrap_or_else(|| renderer.default_size()), line_height: self.line_height, font, align_x: text::Alignment::Default, align_y: alignment::Vertical::Top, shaping: text::Shaping::Advanced, wrapping: self.wrapping, hint_factor: renderer.scale_factor(), }, text_bounds.position(), style.placeholder, text_bounds, ); } } else { renderer.fill_editor( &internal.editor, text_bounds.position(), style.value, text_bounds, ); } let translation = text_bounds.position() - Point::ORIGIN; if let Some(focus) = state.focus.as_ref() { match internal.editor.selection() { Selection::Caret(position) if focus.is_cursor_visible() => { let cursor = Rectangle::new( position + translation, Size::new( if renderer::CRISP { (1.0 / renderer.scale_factor().unwrap_or(1.0)).max(1.0) } else { 1.0 }, self.line_height .to_absolute( self.text_size.unwrap_or_else(|| renderer.default_size()), ) .into(), ), ); if let Some(clipped_cursor) = text_bounds.intersection(&cursor) { renderer.fill_quad( renderer::Quad { bounds: clipped_cursor, ..renderer::Quad::default() }, style.value, ); } } Selection::Range(ranges) => { for range in ranges .into_iter() .filter_map(|range| text_bounds.intersection(&(range + translation))) { renderer.fill_quad( renderer::Quad { bounds: range, ..renderer::Quad::default() }, style.selection, ); } } Selection::Caret(_) => {} } } } fn mouse_interaction( &self, _tree: &widget::Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction {
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/overlay.rs
widget/src/overlay.rs
//! Display interactive elements on top of other widgets. pub mod menu;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/themer.rs
widget/src/themer.rs
use crate::container; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::theme; use crate::core::widget::Operation; use crate::core::widget::tree::{self, Tree}; use crate::core::{ Background, Clipboard, Color, Element, Event, Layout, Length, Rectangle, Shell, Size, Vector, Widget, }; /// A widget that applies any `Theme` to its contents. /// /// This widget can be useful to leverage multiple `Theme` /// types in an application. pub struct Themer<'a, Message, Theme, Renderer = crate::Renderer> where Renderer: crate::core::Renderer, { content: Element<'a, Message, Theme, Renderer>, theme: Option<Theme>, text_color: Option<fn(&Theme) -> Color>, background: Option<fn(&Theme) -> Background>, } impl<'a, Message, Theme, Renderer> Themer<'a, Message, Theme, Renderer> where Renderer: crate::core::Renderer, { /// Creates an empty [`Themer`] that applies the given `Theme` /// to the provided `content`. pub fn new( theme: Option<Theme>, content: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Self { Self { content: content.into(), theme, text_color: None, background: None, } } /// Sets the default text [`Color`] of the [`Themer`]. pub fn text_color(mut self, f: fn(&Theme) -> Color) -> Self { self.text_color = Some(f); self } /// Sets the [`Background`] of the [`Themer`]. pub fn background(mut self, f: fn(&Theme) -> Background) -> Self { self.background = Some(f); self } } impl<Message, Theme, Renderer, AnyTheme> Widget<Message, AnyTheme, Renderer> for Themer<'_, Message, Theme, Renderer> where Theme: theme::Base, AnyTheme: theme::Base, Renderer: crate::core::Renderer, { fn tag(&self) -> tree::Tag { self.content.as_widget().tag() } fn state(&self) -> tree::State { self.content.as_widget().state() } fn children(&self) -> Vec<Tree> { self.content.as_widget().children() } fn diff(&self, tree: &mut Tree) { self.content.as_widget().diff(tree); } 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(tree, renderer, limits) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { self.content .as_widget_mut() .operate(tree, layout, renderer, operation); } fn update( &mut self, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { self.content.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, 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, layout, cursor, viewport, renderer) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &AnyTheme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let default_theme = theme::Base::default(theme.mode()); let theme = self.theme.as_ref().unwrap_or(&default_theme); if let Some(background) = self.background { container::draw_background( renderer, &container::Style { background: Some(background(theme)), ..container::Style::default() }, layout.bounds(), ); } let style = if let Some(text_color) = self.text_color { renderer::Style { text_color: text_color(theme), } } else { *style }; self.content .as_widget() .draw(tree, renderer, theme, &style, layout, cursor, viewport); } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, AnyTheme, Renderer>> { struct Overlay<'a, Message, Theme, Renderer> { theme: &'a Option<Theme>, content: overlay::Element<'a, Message, Theme, Renderer>, } impl<Message, Theme, Renderer, AnyTheme> overlay::Overlay<Message, AnyTheme, Renderer> for Overlay<'_, Message, Theme, Renderer> where Theme: theme::Base, AnyTheme: theme::Base, Renderer: crate::core::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { self.content.as_overlay_mut().layout(renderer, bounds) } fn draw( &self, renderer: &mut Renderer, theme: &AnyTheme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { let default_theme = theme::Base::default(theme.mode()); let theme = self.theme.as_ref().unwrap_or(&default_theme); self.content .as_overlay() .draw(renderer, theme, style, layout, cursor); } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { self.content .as_overlay_mut() .update(event, layout, cursor, renderer, clipboard, shell); } fn operate( &mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { self.content .as_overlay_mut() .operate(layout, renderer, operation); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.content .as_overlay() .mouse_interaction(layout, cursor, renderer) } fn overlay<'b>( &'b mut self, layout: Layout<'b>, renderer: &Renderer, ) -> Option<overlay::Element<'b, Message, AnyTheme, Renderer>> { self.content .as_overlay_mut() .overlay(layout, renderer) .map(|content| Overlay { theme: self.theme, content, }) .map(|overlay| overlay::Element::new(Box::new(overlay))) } } self.content .as_widget_mut() .overlay(tree, layout, renderer, viewport, translation) .map(|content| Overlay { theme: &self.theme, content, }) .map(|overlay| overlay::Element::new(Box::new(overlay))) } } impl<'a, Message, Theme, Renderer, AnyTheme> From<Themer<'a, Message, Theme, Renderer>> for Element<'a, Message, AnyTheme, Renderer> where Message: 'a, Theme: theme::Base + 'a, AnyTheme: theme::Base, Renderer: 'a + crate::core::Renderer, { fn from( themer: Themer<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, AnyTheme, Renderer> { Element::new(themer) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/action.rs
widget/src/action.rs
use crate::core::event; use crate::core::time::Instant; use crate::core::window; /// A runtime action that can be performed by some widgets. #[derive(Debug, Clone)] pub struct Action<Message> { message_to_publish: Option<Message>, redraw_request: window::RedrawRequest, event_status: event::Status, } impl<Message> Action<Message> { fn new() -> Self { Self { message_to_publish: None, redraw_request: window::RedrawRequest::Wait, event_status: event::Status::Ignored, } } /// Creates a new "capturing" [`Action`]. A capturing [`Action`] /// will make other widgets consider it final and prevent further /// processing. /// /// Prevents "event bubbling". pub fn capture() -> Self { Self { event_status: event::Status::Captured, ..Self::new() } } /// Creates a new [`Action`] that publishes the given `Message` for /// the application to handle. /// /// Publishing a `Message` always produces a redraw. pub fn publish(message: Message) -> Self { Self { message_to_publish: Some(message), ..Self::new() } } /// Creates a new [`Action`] that requests a redraw to happen as /// soon as possible; without publishing any `Message`. pub fn request_redraw() -> Self { Self { redraw_request: window::RedrawRequest::NextFrame, ..Self::new() } } /// Creates a new [`Action`] that requests a redraw to happen at /// the given [`Instant`]; without publishing any `Message`. /// /// This can be useful to efficiently animate content, like a /// blinking caret on a text input. pub fn request_redraw_at(at: Instant) -> Self { Self { redraw_request: window::RedrawRequest::At(at), ..Self::new() } } /// Marks the [`Action`] as "capturing". See [`Self::capture`]. pub fn and_capture(mut self) -> Self { self.event_status = event::Status::Captured; self } /// Converts the [`Action`] into its internal parts. /// /// This method is meant to be used by runtimes, libraries, or internal /// widget implementations. pub fn into_inner(self) -> (Option<Message>, window::RedrawRequest, event::Status) { ( self.message_to_publish, self.redraw_request, self.event_status, ) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/space.rs
widget/src/space.rs
//! Add some explicit spacing between elements. use crate::core; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::Tree; use crate::core::{Element, Layout, Length, Rectangle, Size, Widget}; /// Creates a new [`Space`] widget that fills the available /// horizontal space. /// /// This can be useful to separate widgets in a [`Row`](crate::Row). pub fn horizontal() -> Space { Space::new().width(Length::Fill) } /// Creates a new [`Space`] widget that fills the available /// vertical space. /// /// This can be useful to separate widgets in a [`Column`](crate::Column). pub fn vertical() -> Space { Space::new().height(Length::Fill) } /// An amount of empty space. /// /// It can be useful if you want to fill some space with nothing. #[derive(Debug)] pub struct Space { width: Length, height: Length, } impl Space { /// Creates some empty [`Space`] with no size. pub fn new() -> Self { Space { width: Length::Shrink, height: Length::Shrink, } } /// Sets the width of the [`Space`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Space`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } } impl Default for Space { fn default() -> Self { Space::new() } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Space where Renderer: core::Renderer, { 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 draw( &self, _tree: &Tree, _renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, _layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, ) { } } impl<'a, Message, Theme, Renderer> From<Space> for Element<'a, Message, Theme, Renderer> where Renderer: core::Renderer, Message: 'a, { fn from(space: Space) -> Element<'a, Message, Theme, Renderer> { Element::new(space) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pin.rs
widget/src/pin.rs
//! A pin widget positions a widget at some fixed coordinates inside its boundaries. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::Length::Fill; } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::pin; //! use iced::Fill; //! //! enum Message { //! // ... //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! pin("This text is displayed at coordinates (50, 50)!") //! .x(50) //! .y(50) //! .into() //! } //! ``` use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::{ self, Clipboard, Element, Event, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Vector, Widget, }; /// A widget that positions its contents at some fixed coordinates inside of its boundaries. /// /// By default, a [`Pin`] widget will try to fill its parent. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::Length::Fill; } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::pin; /// use iced::Fill; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// pin("This text is displayed at coordinates (50, 50)!") /// .x(50) /// .y(50) /// .into() /// } /// ``` pub struct Pin<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Renderer: core::Renderer, { content: Element<'a, Message, Theme, Renderer>, width: Length, height: Length, position: Point, } impl<'a, Message, Theme, Renderer> Pin<'a, Message, Theme, Renderer> where Renderer: core::Renderer, { /// Creates a [`Pin`] widget with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { content: content.into(), width: Length::Fill, height: Length::Fill, position: Point::ORIGIN, } } /// Sets the width of the [`Pin`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Pin`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the position of the [`Pin`]; where the pinned widget will be displayed. pub fn position(mut self, position: impl Into<Point>) -> Self { self.position = position.into(); self } /// Sets the X coordinate of the [`Pin`]. pub fn x(mut self, x: impl Into<Pixels>) -> Self { self.position.x = x.into().0; self } /// Sets the Y coordinate of the [`Pin`]. pub fn y(mut self, y: impl Into<Pixels>) -> Self { self.position.y = y.into().0; self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Pin<'_, Message, Theme, Renderer> where Renderer: core::Renderer, { 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> { Size { width: self.width, height: self.height, } } fn layout( &mut self, tree: &mut widget::Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let limits = limits.width(self.width).height(self.height); let available = limits.max() - Size::new(self.position.x, self.position.y); let node = self .content .as_widget_mut() .layout(tree, renderer, &layout::Limits::new(Size::ZERO, available)) .move_to(self.position); let size = limits.resolve(self.width, self.height, node.size()); layout::Node::with_children(size, vec![node]) } fn operate( &mut self, tree: &mut widget::Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content.as_widget_mut().operate( tree, layout.children().next().unwrap(), renderer, operation, ); } fn update( &mut self, tree: &mut widget::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( tree, event, layout.children().next().unwrap(), cursor, renderer, clipboard, shell, viewport, ); } fn mouse_interaction( &self, tree: &widget::Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.content.as_widget().mouse_interaction( tree, layout.children().next().unwrap(), cursor, viewport, renderer, ) } 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(clipped_viewport) = bounds.intersection(viewport) { self.content.as_widget().draw( tree, renderer, theme, style, layout.children().next().unwrap(), cursor, &clipped_viewport, ); } } fn overlay<'b>( &'b mut self, tree: &'b mut widget::Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( tree, layout.children().next().unwrap(), renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<Pin<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { fn from(pin: Pin<'a, Message, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> { Element::new(pin) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/rule.rs
widget/src/rule.rs
//! Rules divide space horizontally or vertically. //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } } //! # pub type State = (); //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! use iced::widget::rule; //! //! #[derive(Clone)] //! enum Message { //! // ..., //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! rule::horizontal(2).into() //! } //! ``` use crate::core; use crate::core::border; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::Tree; use crate::core::{Color, Element, Layout, Length, Pixels, Rectangle, Size, Theme, Widget}; /// Creates a new horizontal [`Rule`] with the given height. pub fn horizontal<'a, Theme>(height: impl Into<Pixels>) -> Rule<'a, Theme> where Theme: Catalog, { Rule { thickness: Length::Fixed(height.into().0), is_vertical: false, class: Theme::default(), } } /// Creates a new vertical [`Rule`] with the given width. pub fn vertical<'a, Theme>(width: impl Into<Pixels>) -> Rule<'a, Theme> where Theme: Catalog, { Rule { thickness: Length::Fixed(width.into().0), is_vertical: true, class: Theme::default(), } } /// Display a horizontal or vertical rule for dividing content. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::rule; /// /// #[derive(Clone)] /// enum Message { /// // ..., /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// rule::horizontal(2).into() /// } /// ``` pub struct Rule<'a, Theme = crate::Theme> where Theme: Catalog, { thickness: Length, is_vertical: bool, class: Theme::Class<'a>, } impl<'a, Theme> Rule<'a, Theme> where Theme: Catalog, { /// Sets the style of the [`Rule`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Rule`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Rule<'_, Theme> where Renderer: core::Renderer, Theme: Catalog, { fn size(&self) -> Size<Length> { if self.is_vertical { Size { width: self.thickness, height: Length::Fill, } } else { Size { width: Length::Fill, height: self.thickness, } } } fn layout( &mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let size = <Self as Widget<(), Theme, Renderer>>::size(self); layout::atomic(limits, size.width, size.height) } 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 style = theme.style(&self.class); let mut bounds = if self.is_vertical { let line_x = bounds.x; let (offset, line_height) = style.fill_mode.fill(bounds.height); let line_y = bounds.y + offset; Rectangle { x: line_x, y: line_y, width: bounds.width, height: line_height, } } else { let line_y = bounds.y; let (offset, line_width) = style.fill_mode.fill(bounds.width); let line_x = bounds.x + offset; Rectangle { x: line_x, y: line_y, width: line_width, height: bounds.height, } }; if style.snap { let unit = 1.0 / renderer.scale_factor().unwrap_or(1.0); bounds.width = bounds.width.max(unit); bounds.height = bounds.height.max(unit); } renderer.fill_quad( renderer::Quad { bounds, border: border::rounded(style.radius), snap: style.snap, ..renderer::Quad::default() }, style.color, ); } } impl<'a, Message, Theme, Renderer> From<Rule<'a, Theme>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a + Catalog, Renderer: 'a + core::Renderer, { fn from(rule: Rule<'a, Theme>) -> Element<'a, Message, Theme, Renderer> { Element::new(rule) } } /// The appearance of a rule. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The color of the rule. pub color: Color, /// The radius of the line corners. pub radius: border::Radius, /// The [`FillMode`] of the rule. pub fill_mode: FillMode, /// Whether the rule should be snapped to the pixel grid. pub snap: bool, } /// The fill mode of a rule. #[derive(Debug, Clone, Copy, PartialEq)] pub enum FillMode { /// Fill the whole length of the container. Full, /// Fill a percent of the length of the container. The rule /// will be centered in that container. /// /// The range is `[0.0, 100.0]`. Percent(f32), /// Uniform offset from each end, length units. Padded(u16), /// Different offset on each end of the rule, length units. /// First = top or left. AsymmetricPadding(u16, u16), } impl FillMode { /// Return the starting offset and length of the rule. /// /// * `space` - The space to fill. /// /// # Returns /// /// * (`starting_offset`, `length`) pub fn fill(&self, space: f32) -> (f32, f32) { match *self { FillMode::Full => (0.0, space), FillMode::Percent(percent) => { if percent >= 100.0 { (0.0, space) } else { let percent_width = (space * percent / 100.0).round(); (((space - percent_width) / 2.0).round(), percent_width) } } FillMode::Padded(padding) => { if padding == 0 { (0.0, space) } else { let padding = padding as f32; let mut line_width = space - (padding * 2.0); if line_width < 0.0 { line_width = 0.0; } (padding, line_width) } } FillMode::AsymmetricPadding(first_pad, second_pad) => { let first_pad = first_pad as f32; let second_pad = second_pad as f32; let mut line_width = space - first_pad - second_pad; if line_width < 0.0 { line_width = 0.0; } (first_pad, line_width) } } } } /// The theme catalog of a [`Rule`]. pub trait Catalog: Sized { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> Self::Class<'a>; /// The [`Style`] of a class with the given status. fn style(&self, class: &Self::Class<'_>) -> Style; } /// A styling function for a [`Rule`]. /// /// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> Self::Class<'a> { Box::new(default) } fn style(&self, class: &Self::Class<'_>) -> Style { class(self) } } /// The default styling of a [`Rule`]. pub fn default(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { color: palette.background.strong.color, radius: 0.0.into(), fill_mode: FillMode::Full, snap: true, } } /// A [`Rule`] styling using the weak background color. pub fn weak(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { color: palette.background.weak.color, radius: 0.0.into(), fill_mode: FillMode::Full, snap: true, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/shader.rs
widget/src/shader.rs
//! A custom shader widget for wgpu applications. mod program; pub use program::Program; use crate::core::event; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::widget::{self, Widget}; use crate::core::{Clipboard, Element, Event, Length, Rectangle, Shell, Size}; use crate::renderer::wgpu::primitive; use std::marker::PhantomData; pub use crate::Action; pub use crate::graphics::Viewport; pub use primitive::{Pipeline, Primitive, Storage}; /// A widget which can render custom shaders with Iced's `wgpu` backend. /// /// Must be initialized with a [`Program`], which describes the internal widget state & how /// its [`Program::Primitive`]s are drawn. pub struct Shader<Message, P: Program<Message>> { width: Length, height: Length, program: P, _message: PhantomData<Message>, } impl<Message, P: Program<Message>> Shader<Message, P> { /// Create a new custom [`Shader`]. pub fn new(program: P) -> Self { Self { width: Length::Fixed(100.0), height: Length::Fixed(100.0), program, _message: PhantomData, } } /// Set the `width` of the custom [`Shader`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Set the `height` of the custom [`Shader`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } } impl<P, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Shader<Message, P> where P: Program<Message>, Renderer: primitive::Renderer, { fn tag(&self) -> tree::Tag { struct Tag<T>(T); tree::Tag::of::<Tag<P::State>>() } fn state(&self) -> tree::State { tree::State::new(P::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 bounds = layout.bounds(); let state = tree.state.downcast_mut::<P::State>(); if let Some(action) = self.program.update(state, event, bounds, cursor) { let (message, redraw_request, event_status) = action.into_inner(); shell.request_redraw_at(redraw_request); if let Some(message) = message { shell.publish(message); } if event_status == event::Status::Captured { shell.capture_event(); } } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let bounds = layout.bounds(); let state = tree.state.downcast_ref::<P::State>(); self.program.mouse_interaction(state, bounds, cursor) } fn draw( &self, tree: &widget::Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, cursor_position: mouse::Cursor, _viewport: &Rectangle, ) { let bounds = layout.bounds(); let state = tree.state.downcast_ref::<P::State>(); renderer.draw_primitive(bounds, self.program.draw(state, cursor_position, bounds)); } } impl<'a, Message, Theme, Renderer, P> From<Shader<Message, P>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Renderer: primitive::Renderer, P: Program<Message> + 'a, { fn from(custom: Shader<Message, P>) -> Element<'a, Message, Theme, Renderer> { Element::new(custom) } } impl<Message, T> Program<Message> for &T where T: Program<Message>, { type State = T::State; type Primitive = T::Primitive; fn update( &self, state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<Action<Message>> { T::update(self, state, event, bounds, cursor) } fn draw( &self, state: &Self::State, cursor: mouse::Cursor, bounds: Rectangle, ) -> Self::Primitive { T::draw(self, state, cursor, bounds) } fn mouse_interaction( &self, state: &Self::State, bounds: Rectangle, cursor: mouse::Cursor, ) -> mouse::Interaction { T::mouse_interaction(self, state, bounds, cursor) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/mouse_area.rs
widget/src/mouse_area.rs
//! A container for capturing mouse events. use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::touch; use crate::core::widget::{Operation, Tree, tree}; use crate::core::{ Clipboard, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget, }; /// Emit messages on mouse events. pub struct MouseArea<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { content: Element<'a, Message, Theme, Renderer>, on_press: Option<Message>, on_release: Option<Message>, on_double_click: Option<Message>, on_right_press: Option<Message>, on_right_release: Option<Message>, on_middle_press: Option<Message>, on_middle_release: Option<Message>, on_scroll: Option<Box<dyn Fn(mouse::ScrollDelta) -> Message + 'a>>, on_enter: Option<Message>, on_move: Option<Box<dyn Fn(Point) -> Message + 'a>>, on_exit: Option<Message>, interaction: Option<mouse::Interaction>, } impl<'a, Message, Theme, Renderer> MouseArea<'a, Message, Theme, Renderer> { /// The message to emit on a left button press. #[must_use] pub fn on_press(mut self, message: Message) -> Self { self.on_press = Some(message); self } /// The message to emit on a left button release. #[must_use] pub fn on_release(mut self, message: Message) -> Self { self.on_release = Some(message); self } /// The message to emit on a double click. /// /// If you use this with [`on_press`]/[`on_release`], those /// event will be emit as normal. /// /// The events stream will be: on_press -> on_release -> on_press /// -> on_double_click -> on_release -> on_press ... /// /// [`on_press`]: Self::on_press /// [`on_release`]: Self::on_release #[must_use] pub fn on_double_click(mut self, message: Message) -> Self { self.on_double_click = Some(message); self } /// The message to emit on a right button press. #[must_use] pub fn on_right_press(mut self, message: Message) -> Self { self.on_right_press = Some(message); self } /// The message to emit on a right button release. #[must_use] pub fn on_right_release(mut self, message: Message) -> Self { self.on_right_release = Some(message); self } /// The message to emit on a middle button press. #[must_use] pub fn on_middle_press(mut self, message: Message) -> Self { self.on_middle_press = Some(message); self } /// The message to emit on a middle button release. #[must_use] pub fn on_middle_release(mut self, message: Message) -> Self { self.on_middle_release = Some(message); self } /// The message to emit when scroll wheel is used #[must_use] pub fn on_scroll(mut self, on_scroll: impl Fn(mouse::ScrollDelta) -> Message + 'a) -> Self { self.on_scroll = Some(Box::new(on_scroll)); self } /// The message to emit when the mouse enters the area. #[must_use] pub fn on_enter(mut self, message: Message) -> Self { self.on_enter = Some(message); self } /// The message to emit when the mouse moves in the area. #[must_use] pub fn on_move(mut self, on_move: impl Fn(Point) -> Message + 'a) -> Self { self.on_move = Some(Box::new(on_move)); self } /// The message to emit when the mouse exits the area. #[must_use] pub fn on_exit(mut self, message: Message) -> Self { self.on_exit = Some(message); self } /// The [`mouse::Interaction`] to use when hovering the area. #[must_use] pub fn interaction(mut self, interaction: mouse::Interaction) -> Self { self.interaction = Some(interaction); self } } /// Local state of the [`MouseArea`]. #[derive(Default)] struct State { is_hovered: bool, bounds: Rectangle, cursor_position: Option<Point>, previous_click: Option<mouse::Click>, } impl<'a, Message, Theme, Renderer> MouseArea<'a, Message, Theme, Renderer> { /// Creates a [`MouseArea`] with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { MouseArea { content: content.into(), on_press: None, on_release: None, on_double_click: None, on_right_press: None, on_right_release: None, on_middle_press: None, on_middle_release: None, on_scroll: None, on_enter: None, on_move: None, on_exit: None, interaction: None, } } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for MouseArea<'_, Message, Theme, Renderer> where Renderer: renderer::Renderer, Message: Clone, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::default()) } fn children(&self) -> Vec<Tree> { vec![Tree::new(&self.content)] } fn diff(&self, tree: &mut Tree) { tree.diff_children(std::slice::from_ref(&self.content)); } 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 operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn 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, ); if shell.is_event_captured() { return; } update(self, tree, event, layout, cursor, shell); } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { let content_interaction = self.content.as_widget().mouse_interaction( &tree.children[0], layout, cursor, viewport, renderer, ); match (self.interaction, content_interaction) { (Some(interaction), mouse::Interaction::None) if cursor.is_over(layout.bounds()) => { interaction } _ => content_interaction, } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, renderer_style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.content.as_widget().draw( &tree.children[0], renderer, theme, renderer_style, layout, cursor, viewport, ); } fn overlay<'b>( &'b mut self, tree: &'b mut Tree, layout: Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( &mut tree.children[0], layout, renderer, viewport, translation, ) } } impl<'a, Message, Theme, Renderer> From<MouseArea<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a + Clone, Theme: 'a, Renderer: 'a + renderer::Renderer, { fn from( area: MouseArea<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(area) } } /// Processes the given [`Event`] and updates the [`State`] of an [`MouseArea`] /// accordingly. fn update<Message: Clone, Theme, Renderer>( widget: &mut MouseArea<'_, Message, Theme, Renderer>, tree: &mut Tree, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, shell: &mut Shell<'_, Message>, ) { let state: &mut State = tree.state.downcast_mut(); let cursor_position = cursor.position(); let bounds = layout.bounds(); if state.cursor_position != cursor_position || state.bounds != bounds { let was_hovered = state.is_hovered; state.is_hovered = cursor.is_over(layout.bounds()); state.cursor_position = cursor_position; state.bounds = bounds; match ( widget.on_enter.as_ref(), widget.on_move.as_ref(), widget.on_exit.as_ref(), ) { (Some(on_enter), _, _) if state.is_hovered && !was_hovered => { shell.publish(on_enter.clone()); } (_, Some(on_move), _) if state.is_hovered => { if let Some(position) = cursor.position_in(layout.bounds()) { shell.publish(on_move(position)); } } (_, _, Some(on_exit)) if !state.is_hovered && was_hovered => { shell.publish(on_exit.clone()); } _ => {} } } if !cursor.is_over(layout.bounds()) { return; } match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { if let Some(message) = widget.on_press.as_ref() { shell.publish(message.clone()); shell.capture_event(); } if let Some(position) = cursor_position && let Some(message) = widget.on_double_click.as_ref() { let new_click = mouse::Click::new(position, mouse::Button::Left, state.previous_click); if new_click.kind() == mouse::click::Kind::Double { shell.publish(message.clone()); } state.previous_click = Some(new_click); // Even if this is not a double click, but the press is nevertheless // processed by us and should not be popup to parent widgets. shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) => { if let Some(message) = widget.on_release.as_ref() { shell.publish(message.clone()); } } Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)) => { if let Some(message) = widget.on_right_press.as_ref() { shell.publish(message.clone()); shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right)) => { if let Some(message) = widget.on_right_release.as_ref() { shell.publish(message.clone()); } } Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) => { if let Some(message) = widget.on_middle_press.as_ref() { shell.publish(message.clone()); shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)) => { if let Some(message) = widget.on_middle_release.as_ref() { shell.publish(message.clone()); } } Event::Mouse(mouse::Event::WheelScrolled { delta }) => { if let Some(on_scroll) = widget.on_scroll.as_ref() { shell.publish(on_scroll(*delta)); shell.capture_event(); } } _ => {} } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid.rs
widget/src/pane_grid.rs
//! Pane grids let your users split regions of your application and organize layout dynamically. //! //! ![Pane grid - Iced](https://iced.rs/examples/pane_grid.gif) //! //! This distribution of space is common in tiling window managers (like //! [`awesome`](https://awesomewm.org/), [`i3`](https://i3wm.org/), or even //! [`tmux`](https://github.com/tmux/tmux)). //! //! A [`PaneGrid`] supports: //! //! * Vertical and horizontal splits //! * Tracking of the last active pane //! * Mouse-based resizing //! * Drag and drop to reorganize panes //! * Hotkey support //! * Configurable modifier keys //! * [`State`] API to perform actions programmatically (`split`, `swap`, `resize`, etc.) //! //! # Example //! ```no_run //! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } //! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; //! # //! use iced::widget::{pane_grid, text}; //! //! struct State { //! panes: pane_grid::State<Pane>, //! } //! //! enum Pane { //! SomePane, //! AnotherKindOfPane, //! } //! //! enum Message { //! PaneDragged(pane_grid::DragEvent), //! PaneResized(pane_grid::ResizeEvent), //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! pane_grid(&state.panes, |pane, state, is_maximized| { //! pane_grid::Content::new(match state { //! Pane::SomePane => text("This is some pane"), //! Pane::AnotherKindOfPane => text("This is another kind of pane"), //! }) //! }) //! .on_drag(Message::PaneDragged) //! .on_resize(10, Message::PaneResized) //! .into() //! } //! ``` //! The [`pane_grid` example] showcases how to use a [`PaneGrid`] with resizing, //! drag and drop, and hotkey support. //! //! [`pane_grid` example]: https://github.com/iced-rs/iced/tree/master/examples/pane_grid mod axis; mod configuration; mod content; mod controls; mod direction; mod draggable; mod node; mod pane; mod split; mod title_bar; pub mod state; pub use axis::Axis; pub use configuration::Configuration; pub use content::Content; pub use controls::Controls; pub use direction::Direction; pub use draggable::Draggable; pub use node::Node; pub use pane::Pane; pub use split::Split; pub use state::State; pub use title_bar::TitleBar; use crate::container; use crate::core::layout; use crate::core::mouse; use crate::core::overlay::{self, Group}; use crate::core::renderer; use crate::core::touch; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ self, Background, Border, Clipboard, Color, Element, Event, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget, }; const DRAG_DEADBAND_DISTANCE: f32 = 10.0; const THICKNESS_RATIO: f32 = 25.0; /// A collection of panes distributed using either vertical or horizontal splits /// to completely fill the space available. /// /// ![Pane grid - Iced](https://iced.rs/examples/pane_grid.gif) /// /// This distribution of space is common in tiling window managers (like /// [`awesome`](https://awesomewm.org/), [`i3`](https://i3wm.org/), or even /// [`tmux`](https://github.com/tmux/tmux)). /// /// A [`PaneGrid`] supports: /// /// * Vertical and horizontal splits /// * Tracking of the last active pane /// * Mouse-based resizing /// * Drag and drop to reorganize panes /// * Hotkey support /// * Configurable modifier keys /// * [`State`] API to perform actions programmatically (`split`, `swap`, `resize`, etc.) /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// # /// use iced::widget::{pane_grid, text}; /// /// struct State { /// panes: pane_grid::State<Pane>, /// } /// /// enum Pane { /// SomePane, /// AnotherKindOfPane, /// } /// /// enum Message { /// PaneDragged(pane_grid::DragEvent), /// PaneResized(pane_grid::ResizeEvent), /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// pane_grid(&state.panes, |pane, state, is_maximized| { /// pane_grid::Content::new(match state { /// Pane::SomePane => text("This is some pane"), /// Pane::AnotherKindOfPane => text("This is another kind of pane"), /// }) /// }) /// .on_drag(Message::PaneDragged) /// .on_resize(10, Message::PaneResized) /// .into() /// } /// ``` pub struct PaneGrid<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: core::Renderer, { internal: &'a state::Internal, panes: Vec<Pane>, contents: Vec<Content<'a, Message, Theme, Renderer>>, width: Length, height: Length, spacing: f32, min_size: f32, on_click: Option<Box<dyn Fn(Pane) -> Message + 'a>>, on_drag: Option<Box<dyn Fn(DragEvent) -> Message + 'a>>, on_resize: Option<(f32, Box<dyn Fn(ResizeEvent) -> Message + 'a>)>, class: <Theme as Catalog>::Class<'a>, last_mouse_interaction: Option<mouse::Interaction>, } impl<'a, Message, Theme, Renderer> PaneGrid<'a, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { /// Creates a [`PaneGrid`] with the given [`State`] and view function. /// /// The view function will be called to display each [`Pane`] present in the /// [`State`]. [`bool`] is set if the pane is maximized. pub fn new<T>( state: &'a State<T>, view: impl Fn(Pane, &'a T, bool) -> Content<'a, Message, Theme, Renderer>, ) -> Self { let panes = state.panes.keys().copied().collect(); let contents = state .panes .iter() .map(|(pane, pane_state)| match state.maximized() { Some(p) if *pane == p => view(*pane, pane_state, true), _ => view(*pane, pane_state, false), }) .collect(); Self { internal: &state.internal, panes, contents, width: Length::Fill, height: Length::Fill, spacing: 0.0, min_size: 50.0, on_click: None, on_drag: None, on_resize: None, class: <Theme as Catalog>::default(), last_mouse_interaction: None, } } /// Sets the width of the [`PaneGrid`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`PaneGrid`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the spacing _between_ the panes of the [`PaneGrid`]. pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self { self.spacing = amount.into().0; self } /// Sets the minimum size of a [`Pane`] in the [`PaneGrid`] on both axes. pub fn min_size(mut self, min_size: impl Into<Pixels>) -> Self { self.min_size = min_size.into().0; self } /// Sets the message that will be produced when a [`Pane`] of the /// [`PaneGrid`] is clicked. pub fn on_click<F>(mut self, f: F) -> Self where F: 'a + Fn(Pane) -> Message, { self.on_click = Some(Box::new(f)); self } /// Enables the drag and drop interactions of the [`PaneGrid`], which will /// use the provided function to produce messages. pub fn on_drag<F>(mut self, f: F) -> Self where F: 'a + Fn(DragEvent) -> Message, { if self.internal.maximized().is_none() { self.on_drag = Some(Box::new(f)); } self } /// Enables the resize interactions of the [`PaneGrid`], which will /// use the provided function to produce messages. /// /// The `leeway` describes the amount of space around a split that can be /// used to grab it. /// /// The grabbable area of a split will have a length of `spacing + leeway`, /// properly centered. In other words, a length of /// `(spacing + leeway) / 2.0` on either side of the split line. pub fn on_resize<F>(mut self, leeway: impl Into<Pixels>, f: F) -> Self where F: 'a + Fn(ResizeEvent) -> Message, { if self.internal.maximized().is_none() { self.on_resize = Some((leeway.into().0, Box::new(f))); } self } /// Sets the style of the [`PaneGrid`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where <Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`PaneGrid`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<<Theme as Catalog>::Class<'a>>) -> Self { self.class = class.into(); self } fn drag_enabled(&self) -> bool { if self.internal.maximized().is_none() { self.on_drag.is_some() } else { Default::default() } } fn grid_interaction( &self, action: &state::Action, layout: Layout<'_>, cursor: mouse::Cursor, ) -> Option<mouse::Interaction> { if action.picked_pane().is_some() { return Some(mouse::Interaction::Grabbing); } let resize_leeway = self.on_resize.as_ref().map(|(leeway, _)| *leeway); let node = self.internal.layout(); let resize_axis = action.picked_split().map(|(_, axis)| axis).or_else(|| { resize_leeway.and_then(|leeway| { let cursor_position = cursor.position()?; let bounds = layout.bounds(); let splits = node.split_regions(self.spacing, self.min_size, bounds.size()); let relative_cursor = Point::new(cursor_position.x - bounds.x, cursor_position.y - bounds.y); hovered_split(splits.iter(), self.spacing + leeway, relative_cursor) .map(|(_, axis, _)| axis) }) }); if let Some(resize_axis) = resize_axis { return Some(match resize_axis { Axis::Horizontal => mouse::Interaction::ResizingVertically, Axis::Vertical => mouse::Interaction::ResizingHorizontally, }); } None } } #[derive(Default)] struct Memory { action: state::Action, order: Vec<Pane>, } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for PaneGrid<'_, Message, Theme, Renderer> where Theme: Catalog, Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<Memory>() } fn state(&self) -> tree::State { tree::State::new(Memory::default()) } fn children(&self) -> Vec<Tree> { self.contents.iter().map(Content::state).collect() } fn diff(&self, tree: &mut Tree) { let Memory { order, .. } = tree.state.downcast_ref(); // `Pane` always increments and is iterated by Ord so new // states are always added at the end. We can simply remove // states which no longer exist and `diff_children` will // diff the remaining values in the correct order and // add new states at the end let mut i = 0; let mut j = 0; tree.children.retain(|_| { let retain = self.panes.get(i) == order.get(j); if retain { i += 1; } j += 1; retain }); tree.diff_children_custom( &self.contents, |state, content| content.diff(state), Content::state, ); let Memory { order, .. } = tree.state.downcast_mut(); order.clone_from(&self.panes); } 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 { let bounds = limits.resolve(self.width, self.height, Size::ZERO); let regions = self .internal .layout() .pane_regions(self.spacing, self.min_size, bounds); let children = self .panes .iter_mut() .zip(&mut self.contents) .zip(tree.children.iter_mut()) .filter_map(|((pane, content), tree)| { if self .internal .maximized() .is_some_and(|maximized| maximized != *pane) { return Some(layout::Node::new(Size::ZERO)); } let region = regions.get(pane)?; let size = Size::new(region.width, region.height); let node = content.layout(tree, renderer, &layout::Limits::new(size, size)); Some(node.move_to(Point::new(region.x, region.y))) }) .collect(); layout::Node::with_children(bounds, children) } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { operation.container(None, layout.bounds()); operation.traverse(&mut |operation| { self.panes .iter_mut() .zip(&mut self.contents) .zip(&mut tree.children) .zip(layout.children()) .filter(|(((pane, _), _), _)| { self.internal .maximized() .is_none_or(|maximized| **pane == maximized) }) .for_each(|(((_, content), state), layout)| { content.operate(state, 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, ) { let Memory { action, .. } = tree.state.downcast_mut(); let node = self.internal.layout(); let on_drag = if self.drag_enabled() { &self.on_drag } else { &None }; let picked_pane = action.picked_pane().map(|(pane, _)| pane); for (((pane, content), tree), layout) in self .panes .iter() .copied() .zip(&mut self.contents) .zip(&mut tree.children) .zip(layout.children()) .filter(|(((pane, _), _), _)| { self.internal .maximized() .is_none_or(|maximized| *pane == maximized) }) { let is_picked = picked_pane == Some(pane); content.update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, is_picked, ); } match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) | Event::Touch(touch::Event::FingerPressed { .. }) => { let bounds = layout.bounds(); if let Some(cursor_position) = cursor.position_over(bounds) { shell.capture_event(); match &self.on_resize { Some((leeway, _)) => { let relative_cursor = Point::new( cursor_position.x - bounds.x, cursor_position.y - bounds.y, ); let splits = node.split_regions(self.spacing, self.min_size, bounds.size()); let clicked_split = hovered_split( splits.iter(), self.spacing + leeway, relative_cursor, ); if let Some((split, axis, _)) = clicked_split { if action.picked_pane().is_none() { *action = state::Action::Resizing { split, axis }; } } else { click_pane( action, layout, cursor_position, shell, self.panes.iter().copied().zip(&self.contents), &self.on_click, on_drag, ); } } None => { click_pane( action, layout, cursor_position, shell, self.panes.iter().copied().zip(&self.contents), &self.on_click, on_drag, ); } } } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) | Event::Touch(touch::Event::FingerLifted { .. }) | Event::Touch(touch::Event::FingerLost { .. }) => { if let Some((pane, origin)) = action.picked_pane() && let Some(on_drag) = on_drag && let Some(cursor_position) = cursor.position() { if cursor_position.distance(origin) > DRAG_DEADBAND_DISTANCE { let event = if let Some(edge) = in_edge(layout, cursor_position) { DragEvent::Dropped { pane, target: Target::Edge(edge), } } else { let dropped_region = self .panes .iter() .copied() .zip(&self.contents) .zip(layout.children()) .find_map(|(target, layout)| { layout_region(layout, cursor_position) .map(|region| (target, region)) }); match dropped_region { Some(((target, _), region)) if pane != target => { DragEvent::Dropped { pane, target: Target::Pane(target, region), } } _ => DragEvent::Canceled { pane }, } }; shell.publish(on_drag(event)); } else { shell.publish(on_drag(DragEvent::Canceled { pane })); } } *action = state::Action::Idle; } Event::Mouse(mouse::Event::CursorMoved { .. }) | Event::Touch(touch::Event::FingerMoved { .. }) => { if let Some((_, on_resize)) = &self.on_resize { if let Some((split, _)) = action.picked_split() { let bounds = layout.bounds(); let splits = node.split_regions(self.spacing, self.min_size, bounds.size()); if let Some((axis, rectangle, _)) = splits.get(&split) && let Some(cursor_position) = cursor.position() { let ratio = match axis { Axis::Horizontal => { let position = cursor_position.y - bounds.y - rectangle.y; (position / rectangle.height).clamp(0.0, 1.0) } Axis::Vertical => { let position = cursor_position.x - bounds.x - rectangle.x; (position / rectangle.width).clamp(0.0, 1.0) } }; shell.publish(on_resize(ResizeEvent { split, ratio })); shell.capture_event(); } } else if action.picked_pane().is_some() { shell.request_redraw(); } } } _ => {} } if shell.redraw_request() != window::RedrawRequest::NextFrame { let interaction = self .grid_interaction(action, layout, cursor) .or_else(|| { self.panes .iter() .zip(&self.contents) .zip(layout.children()) .filter(|((pane, _content), _layout)| { self.internal .maximized() .is_none_or(|maximized| **pane == maximized) }) .find_map(|((_pane, content), layout)| { content.grid_interaction(layout, cursor, on_drag.is_some()) }) }) .unwrap_or(mouse::Interaction::None); if let Event::Window(window::Event::RedrawRequested(_now)) = event { self.last_mouse_interaction = Some(interaction); } else if self .last_mouse_interaction .is_some_and(|last_mouse_interaction| last_mouse_interaction != interaction) { shell.request_redraw(); } } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { let Memory { action, .. } = tree.state.downcast_ref(); if let Some(grid_interaction) = self.grid_interaction(action, layout, cursor) { return grid_interaction; } self.panes .iter() .copied() .zip(&self.contents) .zip(&tree.children) .zip(layout.children()) .filter(|(((pane, _), _), _)| { self.internal .maximized() .is_none_or(|maximized| *pane == maximized) }) .map(|(((_, content), tree), layout)| { content.mouse_interaction( tree, layout, cursor, viewport, renderer, self.drag_enabled(), ) }) .max() .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let Memory { action, .. } = tree.state.downcast_ref(); let node = self.internal.layout(); let resize_leeway = self.on_resize.as_ref().map(|(leeway, _)| *leeway); let picked_pane = action.picked_pane().filter(|(_, origin)| { cursor .position() .map(|position| position.distance(*origin)) .unwrap_or_default() > DRAG_DEADBAND_DISTANCE }); let picked_split = action .picked_split() .and_then(|(split, axis)| { let bounds = layout.bounds(); let splits = node.split_regions(self.spacing, self.min_size, bounds.size()); let (_axis, region, ratio) = splits.get(&split)?; let region = axis.split_line_bounds(*region, *ratio, self.spacing); Some((axis, region + Vector::new(bounds.x, bounds.y), true)) }) .or_else(|| match resize_leeway { Some(leeway) => { let cursor_position = cursor.position()?; let bounds = layout.bounds(); let relative_cursor = Point::new(cursor_position.x - bounds.x, cursor_position.y - bounds.y); let splits = node.split_regions(self.spacing, self.min_size, bounds.size()); let (_split, axis, region) = hovered_split(splits.iter(), self.spacing + leeway, relative_cursor)?; Some((axis, region + Vector::new(bounds.x, bounds.y), false)) } None => None, }); let pane_cursor = if picked_pane.is_some() { mouse::Cursor::Unavailable } else { cursor }; let mut render_picked_pane = None; let pane_in_edge = if picked_pane.is_some() { cursor .position() .and_then(|cursor_position| in_edge(layout, cursor_position)) } else { None }; let style = Catalog::style(theme, &self.class); for (((id, content), tree), pane_layout) in self .panes .iter() .copied() .zip(&self.contents) .zip(&tree.children) .zip(layout.children()) .filter(|(((pane, _), _), _)| { self.internal .maximized() .is_none_or(|maximized| maximized == *pane) }) { match picked_pane { Some((dragging, origin)) if id == dragging => { render_picked_pane = Some(((content, tree), origin, pane_layout)); } Some((dragging, _)) if id != dragging => { content.draw( tree, renderer, theme, defaults, pane_layout, pane_cursor, viewport, ); if picked_pane.is_some() && pane_in_edge.is_none() && let Some(region) = cursor .position() .and_then(|cursor_position| layout_region(pane_layout, cursor_position)) { let bounds = layout_region_bounds(pane_layout, region); renderer.fill_quad( renderer::Quad { bounds, border: style.hovered_region.border, ..renderer::Quad::default() }, style.hovered_region.background, ); } } _ => { content.draw( tree, renderer, theme, defaults, pane_layout, pane_cursor, viewport, ); } } } if let Some(edge) = pane_in_edge { let bounds = edge_bounds(layout, edge); renderer.fill_quad( renderer::Quad { bounds, border: style.hovered_region.border, ..renderer::Quad::default() }, style.hovered_region.background, ); } // Render picked pane last if let Some(((content, tree), origin, layout)) = render_picked_pane && let Some(cursor_position) = cursor.position() { let bounds = layout.bounds(); let translation = cursor_position - Point::new(origin.x, origin.y); renderer.with_translation(translation, |renderer| { renderer.with_layer(bounds, |renderer| { content.draw( tree, renderer, theme, defaults, layout, pane_cursor, viewport, ); }); }); } if picked_pane.is_none() && let Some((axis, split_region, is_picked)) = picked_split { let highlight = if is_picked { style.picked_split } else { style.hovered_split }; renderer.fill_quad( renderer::Quad { bounds: match axis { Axis::Horizontal => Rectangle { x: split_region.x, y: (split_region.y + (split_region.height - highlight.width) / 2.0) .round(), width: split_region.width, height: highlight.width, }, Axis::Vertical => Rectangle { x: (split_region.x + (split_region.width - highlight.width) / 2.0) .round(), y: split_region.y, width: highlight.width, height: split_region.height, }, }, ..renderer::Quad::default() }, highlight.color, ); } } 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 children = self .panes .iter() .copied() .zip(&mut self.contents) .zip(&mut tree.children) .zip(layout.children()) .filter_map(|(((pane, content), state), layout)| { if self .internal .maximized() .is_some_and(|maximized| maximized != pane) { return None; } content.overlay(state, layout, renderer, viewport, translation) }) .collect::<Vec<_>>(); (!children.is_empty()).then(|| Group::with_children(children).overlay()) } } impl<'a, Message, Theme, Renderer> From<PaneGrid<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + 'a, Renderer: core::Renderer + 'a, { fn from( pane_grid: PaneGrid<'a, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(pane_grid) } } fn layout_region(layout: Layout<'_>, cursor_position: Point) -> Option<Region> { let bounds = layout.bounds(); if !bounds.contains(cursor_position) { return None; } let region = if cursor_position.x < (bounds.x + bounds.width / 3.0) { Region::Edge(Edge::Left) } else if cursor_position.x > (bounds.x + 2.0 * bounds.width / 3.0) { Region::Edge(Edge::Right) } else if cursor_position.y < (bounds.y + bounds.height / 3.0) { Region::Edge(Edge::Top) } else if cursor_position.y > (bounds.y + 2.0 * bounds.height / 3.0) { Region::Edge(Edge::Bottom) } else { Region::Center };
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/sensor.rs
widget/src/sensor.rs
//! Generate messages when content pops in and out of view. use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::time::{Duration, Instant}; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ self, Clipboard, Element, Event, Layout, Length, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A widget that can generate messages when its content pops in and out of view. /// /// It can even notify you with anticipation at a given distance! pub struct Sensor<'a, Key, Message, Theme = crate::Theme, Renderer = crate::Renderer> { content: Element<'a, Message, Theme, Renderer>, key: Key, on_show: Option<Box<dyn Fn(Size) -> Message + 'a>>, on_resize: Option<Box<dyn Fn(Size) -> Message + 'a>>, on_hide: Option<Message>, anticipate: Pixels, delay: Duration, } impl<'a, Message, Theme, Renderer> Sensor<'a, (), Message, Theme, Renderer> where Renderer: core::Renderer, { /// Creates a new [`Sensor`] widget with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { content: content.into(), key: (), on_show: None, on_resize: None, on_hide: None, anticipate: Pixels::ZERO, delay: Duration::ZERO, } } } impl<'a, Key, Message, Theme, Renderer> Sensor<'a, Key, Message, Theme, Renderer> where Key: self::Key, Renderer: core::Renderer, { /// Sets the message to be produced when the content pops into view. /// /// The closure will receive the [`Size`] of the content in that moment. pub fn on_show(mut self, on_show: impl Fn(Size) -> Message + 'a) -> Self { self.on_show = Some(Box::new(on_show)); self } /// Sets the message to be produced when the content changes [`Size`] once its in view. /// /// The closure will receive the new [`Size`] of the content. pub fn on_resize(mut self, on_resize: impl Fn(Size) -> Message + 'a) -> Self { self.on_resize = Some(Box::new(on_resize)); self } /// Sets the message to be produced when the content pops out of view. pub fn on_hide(mut self, on_hide: Message) -> Self { self.on_hide = Some(on_hide); self } /// Sets the key of the [`Sensor`] widget, for continuity. /// /// If the key changes, the [`Sensor`] widget will trigger again. pub fn key<K>(self, key: K) -> Sensor<'a, impl self::Key, Message, Theme, Renderer> where K: Clone + PartialEq + 'static, { Sensor { content: self.content, key: OwnedKey(key), on_show: self.on_show, on_resize: self.on_resize, on_hide: self.on_hide, anticipate: self.anticipate, delay: self.delay, } } /// Sets the key of the [`Sensor`], for continuity; using a reference. /// /// If the key changes, the [`Sensor`] will trigger again. pub fn key_ref<K>(self, key: &'a K) -> Sensor<'a, &'a K, Message, Theme, Renderer> where K: ToOwned + PartialEq<K::Owned> + ?Sized, K::Owned: 'static, { Sensor { content: self.content, key, on_show: self.on_show, on_resize: self.on_resize, on_hide: self.on_hide, anticipate: self.anticipate, delay: self.delay, } } /// Sets the distance in [`Pixels`] to use in anticipation of the /// content popping into view. /// /// This can be quite useful to lazily load items in a long scrollable /// behind the scenes before the user can notice it! pub fn anticipate(mut self, distance: impl Into<Pixels>) -> Self { self.anticipate = distance.into(); self } /// Sets the amount of time to wait before firing an [`on_show`] or /// [`on_hide`] event; after the content is shown or hidden. /// /// When combined with [`key`], this can be useful to debounce key changes. /// /// [`on_show`]: Self::on_show /// [`on_hide`]: Self::on_hide /// [`key`]: Self::key pub fn delay(mut self, delay: impl Into<Duration>) -> Self { self.delay = delay.into(); self } } #[derive(Debug, Clone)] struct State<Key> { has_popped_in: bool, should_notify_at: Option<(bool, Instant)>, last_size: Option<Size>, last_key: Key, } impl<Key, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Sensor<'_, Key, Message, Theme, Renderer> where Key: self::Key, Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Key::Owned>>() } fn state(&self) -> tree::State { tree::State::new(State { has_popped_in: false, should_notify_at: None, last_size: None, last_key: self.key.to_owned(), }) } fn children(&self) -> Vec<Tree> { vec![Tree::new(&self.content)] } fn diff(&self, tree: &mut Tree) { tree.diff_children(&[&self.content]); } 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, ) { if let Event::Window(window::Event::RedrawRequested(now)) = &event { let state = tree.state.downcast_mut::<State<Key::Owned>>(); if state.has_popped_in && !self.key.eq(&state.last_key) { state.has_popped_in = false; state.should_notify_at = None; state.last_key = self.key.to_owned(); } let bounds = layout.bounds(); let top_left_distance = viewport.distance(bounds.position()); let bottom_right_distance = viewport.distance(bounds.position() + Vector::from(bounds.size())); let distance = top_left_distance.min(bottom_right_distance); if self.on_show.is_none() { if let Some(on_resize) = &self.on_resize { let size = bounds.size(); if Some(size) != state.last_size { state.last_size = Some(size); shell.publish(on_resize(size)); } } } else if state.has_popped_in { if distance <= self.anticipate.0 { if let Some(on_resize) = &self.on_resize { let size = bounds.size(); if Some(size) != state.last_size { state.last_size = Some(size); shell.publish(on_resize(size)); } } } else if self.on_hide.is_some() { state.has_popped_in = false; state.should_notify_at = Some((false, *now + self.delay)); } } else if distance <= self.anticipate.0 { let size = bounds.size(); state.has_popped_in = true; state.should_notify_at = Some((true, *now + self.delay)); state.last_size = Some(size); } match &state.should_notify_at { Some((has_popped_in, at)) if at <= now => { if *has_popped_in { if let Some(on_show) = &self.on_show { shell.publish(on_show(layout.bounds().size())); } } else if let Some(on_hide) = self.on_hide.take() { shell.publish(on_hide); } state.should_notify_at = None; } Some((_, at)) => { shell.request_redraw_at(*at); } None => {} } } self.content.as_widget_mut().update( &mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport, ); } fn size(&self) -> Size<Length> { self.content.as_widget().size() } fn size_hint(&self) -> Size<Length> { self.content.as_widget().size_hint() } 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 draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: layout::Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { self.content.as_widget().draw( &tree.children[0], renderer, theme, style, layout, cursor, viewport, ); } fn operate( &mut self, tree: &mut Tree, layout: core::Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.content .as_widget_mut() .operate(&mut tree.children[0], layout, renderer, operation); } fn mouse_interaction( &self, tree: &Tree, layout: core::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: core::Layout<'b>, renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { self.content.as_widget_mut().overlay( &mut tree.children[0], layout, renderer, viewport, translation, ) } } impl<'a, Key, Message, Theme, Renderer> From<Sensor<'a, Key, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Key: self::Key + 'a, Renderer: core::Renderer + 'a, Theme: 'a, { fn from(pop: Sensor<'a, Key, Message, Theme, Renderer>) -> Self { Element::new(pop) } } /// The key of a widget. /// /// You should generally not need to care about this trait. pub trait Key { /// The owned version of the key. type Owned: 'static; /// Returns the owned version of the key. fn to_owned(&self) -> Self::Owned; /// Compares the key with the given owned version. fn eq(&self, other: &Self::Owned) -> bool; } impl<T> Key for &T where T: ToOwned + PartialEq<T::Owned> + ?Sized, T::Owned: 'static, { type Owned = T::Owned; fn to_owned(&self) -> <Self as Key>::Owned { ToOwned::to_owned(*self) } fn eq(&self, other: &Self::Owned) -> bool { *self == other } } struct OwnedKey<T>(T); impl<T> Key for OwnedKey<T> where T: PartialEq + Clone + 'static, { type Owned = T; fn to_owned(&self) -> Self::Owned { self.0.clone() } fn eq(&self, other: &Self::Owned) -> bool { &self.0 == other } } impl<T> PartialEq<T> for OwnedKey<T> where T: PartialEq, { fn eq(&self, other: &T) -> bool { &self.0 == other } } impl Key for () { type Owned = (); fn to_owned(&self) -> Self::Owned {} fn eq(&self, _other: &Self::Owned) -> bool { true } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/overlay/menu.rs
widget/src/overlay/menu.rs
//! Build and show dropdown menus. use crate::core::alignment; use crate::core::border::{self, Border}; use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::text::{self, Text}; use crate::core::touch; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ Background, Clipboard, Color, Event, Length, Padding, Pixels, Point, Rectangle, Shadow, Size, Theme, Vector, }; use crate::core::{Element, Shell, Widget}; use crate::scrollable::{self, Scrollable}; /// A list of selectable options. pub struct Menu<'a, 'b, T, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: Catalog, Renderer: text::Renderer, 'b: 'a, { state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option<usize>, on_selected: Box<dyn FnMut(T) -> Message + 'a>, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, width: f32, padding: Padding, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_shaping: text::Shaping, font: Option<Renderer::Font>, class: &'a <Theme as Catalog>::Class<'b>, } impl<'a, 'b, T, Message, Theme, Renderer> Menu<'a, 'b, T, Message, Theme, Renderer> where T: ToString + Clone, Message: 'a, Theme: Catalog + 'a, Renderer: text::Renderer + 'a, 'b: 'a, { /// Creates a new [`Menu`] with the given [`State`], a list of options, /// the message to produced when an option is selected, and its [`Style`]. pub fn new( state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option<usize>, on_selected: impl FnMut(T) -> Message + 'a, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, class: &'a <Theme as Catalog>::Class<'b>, ) -> Self { Menu { state, options, hovered_option, on_selected: Box::new(on_selected), on_option_hovered, width: 0.0, padding: Padding::ZERO, text_size: None, text_line_height: text::LineHeight::default(), text_shaping: text::Shaping::default(), font: None, class, } } /// Sets the width of the [`Menu`]. pub fn width(mut self, width: f32) -> Self { self.width = width; self } /// Sets the [`Padding`] of the [`Menu`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the text size of the [`Menu`]. pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self { self.text_size = Some(text_size.into()); self } /// Sets the text [`text::LineHeight`] of the [`Menu`]. pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self { self.text_line_height = line_height.into(); self } /// Sets the [`text::Shaping`] strategy of the [`Menu`]. pub fn text_shaping(mut self, shaping: text::Shaping) -> Self { self.text_shaping = shaping; self } /// Sets the font of the [`Menu`]. pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Turns the [`Menu`] into an overlay [`Element`] at the given target /// position. /// /// The `target_height` will be used to display the menu either on top /// of the target or under it, depending on the screen position and the /// dimensions of the [`Menu`]. pub fn overlay( self, position: Point, viewport: Rectangle, target_height: f32, menu_height: Length, ) -> overlay::Element<'a, Message, Theme, Renderer> { overlay::Element::new(Box::new(Overlay::new( position, viewport, self, target_height, menu_height, ))) } } /// The local state of a [`Menu`]. #[derive(Debug)] pub struct State { tree: Tree, } impl State { /// Creates a new [`State`] for a [`Menu`]. pub fn new() -> Self { Self { tree: Tree::empty(), } } } impl Default for State { fn default() -> Self { Self::new() } } struct Overlay<'a, 'b, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { position: Point, viewport: Rectangle, tree: &'a mut Tree, list: Scrollable<'a, Message, Theme, Renderer>, width: f32, target_height: f32, class: &'a <Theme as Catalog>::Class<'b>, } impl<'a, 'b, Message, Theme, Renderer> Overlay<'a, 'b, Message, Theme, Renderer> where Message: 'a, Theme: Catalog + scrollable::Catalog + 'a, Renderer: text::Renderer + 'a, 'b: 'a, { pub fn new<T>( position: Point, viewport: Rectangle, menu: Menu<'a, 'b, T, Message, Theme, Renderer>, target_height: f32, menu_height: Length, ) -> Self where T: Clone + ToString, { let Menu { state, options, hovered_option, on_selected, on_option_hovered, width, padding, font, text_size, text_line_height, text_shaping, class, } = menu; let list = Scrollable::new(List { options, hovered_option, on_selected, on_option_hovered, font, text_size, text_line_height, text_shaping, padding, class, }) .height(menu_height); state.tree.diff(&list as &dyn Widget<_, _, _>); Self { position, viewport, tree: &mut state.tree, list, width, target_height, class, } } } impl<Message, Theme, Renderer> crate::core::Overlay<Message, Theme, Renderer> for Overlay<'_, '_, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { let space_below = bounds.height - (self.position.y + self.target_height); let space_above = self.position.y; let limits = layout::Limits::new( Size::ZERO, Size::new( bounds.width - self.position.x, if space_below > space_above { space_below } else { space_above }, ), ) .width(self.width); let node = self.list.layout(self.tree, renderer, &limits); let size = node.size(); node.move_to(if space_below > space_above { self.position + Vector::new(0.0, self.target_height) } else { self.position - Vector::new(0.0, size.height) }) } fn update( &mut self, event: &Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { let bounds = layout.bounds(); self.list.update( self.tree, event, layout, cursor, renderer, clipboard, shell, &bounds, ); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.list .mouse_interaction(self.tree, layout, cursor, &self.viewport, renderer) } fn draw( &self, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { let bounds = layout.bounds(); let style = Catalog::style(theme, self.class); renderer.fill_quad( renderer::Quad { bounds, border: style.border, shadow: style.shadow, ..renderer::Quad::default() }, style.background, ); self.list.draw( self.tree, renderer, theme, defaults, layout, cursor, &bounds, ); } } struct List<'a, 'b, T, Message, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, { options: &'a [T], hovered_option: &'a mut Option<usize>, on_selected: Box<dyn FnMut(T) -> Message + 'a>, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, padding: Padding, text_size: Option<Pixels>, text_line_height: text::LineHeight, text_shaping: text::Shaping, font: Option<Renderer::Font>, class: &'a <Theme as Catalog>::Class<'b>, } struct ListState { is_hovered: Option<bool>, } impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for List<'_, '_, T, Message, Theme, Renderer> where T: Clone + ToString, Theme: Catalog, Renderer: text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<Option<bool>>() } fn state(&self) -> tree::State { tree::State::new(ListState { is_hovered: None }) } fn size(&self) -> Size<Length> { Size { width: Length::Fill, height: Length::Shrink, } } fn layout( &mut self, _tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { use std::f32; let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); let text_line_height = self.text_line_height.to_absolute(text_size); let size = { let intrinsic = Size::new( 0.0, (f32::from(text_line_height) + self.padding.y()) * self.options.len() as f32, ); limits.resolve(Length::Fill, Length::Shrink, intrinsic) }; layout::Node::new(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, ) { match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { if cursor.is_over(layout.bounds()) && let Some(index) = *self.hovered_option && let Some(option) = self.options.get(index) { shell.publish((self.on_selected)(option.clone())); shell.capture_event(); } } Event::Mouse(mouse::Event::CursorMoved { .. }) => { if let Some(cursor_position) = cursor.position_in(layout.bounds()) { let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); let option_height = f32::from(self.text_line_height.to_absolute(text_size)) + self.padding.y(); let new_hovered_option = (cursor_position.y / option_height) as usize; if *self.hovered_option != Some(new_hovered_option) && let Some(option) = self.options.get(new_hovered_option) { if let Some(on_option_hovered) = self.on_option_hovered { shell.publish(on_option_hovered(option.clone())); } shell.request_redraw(); } *self.hovered_option = Some(new_hovered_option); } } Event::Touch(touch::Event::FingerPressed { .. }) => { if let Some(cursor_position) = cursor.position_in(layout.bounds()) { let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); let option_height = f32::from(self.text_line_height.to_absolute(text_size)) + self.padding.y(); *self.hovered_option = Some((cursor_position.y / option_height) as usize); if let Some(index) = *self.hovered_option && let Some(option) = self.options.get(index) { shell.publish((self.on_selected)(option.clone())); shell.capture_event(); } } } _ => {} } let state = tree.state.downcast_mut::<ListState>(); if let Event::Window(window::Event::RedrawRequested(_now)) = event { state.is_hovered = Some(cursor.is_over(layout.bounds())); } else if state .is_hovered .is_some_and(|is_hovered| is_hovered != cursor.is_over(layout.bounds())) { shell.request_redraw(); } } fn mouse_interaction( &self, _tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let is_mouse_over = cursor.is_over(layout.bounds()); if is_mouse_over { mouse::Interaction::Pointer } else { mouse::Interaction::default() } } fn draw( &self, _tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let style = Catalog::style(theme, self.class); let bounds = layout.bounds(); let text_size = self.text_size.unwrap_or_else(|| renderer.default_size()); let option_height = f32::from(self.text_line_height.to_absolute(text_size)) + self.padding.y(); let offset = viewport.y - bounds.y; let start = (offset / option_height) as usize; let end = ((offset + viewport.height) / option_height).ceil() as usize; let visible_options = &self.options[start..end.min(self.options.len())]; for (i, option) in visible_options.iter().enumerate() { let i = start + i; let is_selected = *self.hovered_option == Some(i); let bounds = Rectangle { x: bounds.x, y: bounds.y + (option_height * i as f32), width: bounds.width, height: option_height, }; if is_selected { renderer.fill_quad( renderer::Quad { bounds: Rectangle { x: bounds.x + style.border.width, width: bounds.width - style.border.width * 2.0, ..bounds }, border: border::rounded(style.border.radius), ..renderer::Quad::default() }, style.selected_background, ); } renderer.fill_text( Text { content: option.to_string(), bounds: Size::new(f32::INFINITY, bounds.height), size: text_size, line_height: self.text_line_height, font: self.font.unwrap_or_else(|| renderer.default_font()), align_x: text::Alignment::Default, align_y: alignment::Vertical::Center, shaping: self.text_shaping, wrapping: text::Wrapping::default(), hint_factor: renderer.scale_factor(), }, Point::new(bounds.x + self.padding.left, bounds.center_y()), if is_selected { style.selected_text_color } else { style.text_color }, *viewport, ); } } } impl<'a, 'b, T, Message, Theme, Renderer> From<List<'a, 'b, T, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where T: ToString + Clone, Message: 'a, Theme: 'a + Catalog, Renderer: 'a + text::Renderer, 'b: 'a, { fn from(list: List<'a, 'b, T, Message, Theme, Renderer>) -> Self { Element::new(list) } } /// The appearance of a [`Menu`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Style { /// The [`Background`] of the menu. pub background: Background, /// The [`Border`] of the menu. pub border: Border, /// The text [`Color`] of the menu. pub text_color: Color, /// The text [`Color`] of a selected option in the menu. pub selected_text_color: Color, /// The background [`Color`] of a selected option in the menu. pub selected_background: Background, /// The [`Shadow`] of the menu. pub shadow: Shadow, } /// The theme catalog of a [`Menu`]. pub trait Catalog: scrollable::Catalog { /// The item class of the [`Catalog`]. type Class<'a>; /// The default class produced by the [`Catalog`]. fn default<'a>() -> <Self as Catalog>::Class<'a>; /// The default class for the scrollable of the [`Menu`]. fn default_scrollable<'a>() -> <Self as scrollable::Catalog>::Class<'a> { <Self as scrollable::Catalog>::default() } /// The [`Style`] of a class with the given status. fn style(&self, class: &<Self as Catalog>::Class<'_>) -> Style; } /// A styling function for a [`Menu`]. pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>; impl Catalog for Theme { type Class<'a> = StyleFn<'a, Self>; fn default<'a>() -> StyleFn<'a, Self> { Box::new(default) } fn style(&self, class: &StyleFn<'_, Self>) -> Style { class(self) } } /// The default style of the list of a [`Menu`]. pub fn default(theme: &Theme) -> Style { let palette = theme.extended_palette(); Style { background: palette.background.weak.color.into(), border: Border { width: 1.0, radius: 0.0.into(), color: palette.background.strong.color, }, text_color: palette.background.weak.text, selected_text_color: palette.primary.strong.text, selected_background: palette.primary.strong.color.into(), shadow: Shadow::default(), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/image/viewer.rs
widget/src/image/viewer.rs
//! Zoom and pan on an image. use crate::core::border; use crate::core::image::{self, FilterMethod}; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::{ Clipboard, ContentFit, Element, Event, Image, Layout, Length, Pixels, Point, Radians, Rectangle, Shell, Size, Vector, Widget, }; /// A frame that displays an image with the ability to zoom in/out and pan. pub struct Viewer<Handle> { padding: f32, width: Length, height: Length, min_scale: f32, max_scale: f32, scale_step: f32, handle: Handle, filter_method: FilterMethod, content_fit: ContentFit, } impl<Handle> Viewer<Handle> { /// Creates a new [`Viewer`] with the given [`State`]. pub fn new<T: Into<Handle>>(handle: T) -> Self { Viewer { handle: handle.into(), padding: 0.0, width: Length::Shrink, height: Length::Shrink, min_scale: 0.25, max_scale: 10.0, scale_step: 0.10, filter_method: FilterMethod::default(), content_fit: ContentFit::default(), } } /// Sets the [`FilterMethod`] of the [`Viewer`]. pub fn filter_method(mut self, filter_method: image::FilterMethod) -> Self { self.filter_method = filter_method; self } /// Sets the [`ContentFit`] of the [`Viewer`]. pub fn content_fit(mut self, content_fit: ContentFit) -> Self { self.content_fit = content_fit; self } /// Sets the padding of the [`Viewer`]. pub fn padding(mut self, padding: impl Into<Pixels>) -> Self { self.padding = padding.into().0; self } /// Sets the width of the [`Viewer`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Viewer`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the max scale applied to the image of the [`Viewer`]. /// /// Default is `10.0` pub fn max_scale(mut self, max_scale: f32) -> Self { self.max_scale = max_scale; self } /// Sets the min scale applied to the image of the [`Viewer`]. /// /// Default is `0.25` pub fn min_scale(mut self, min_scale: f32) -> Self { self.min_scale = min_scale; self } /// Sets the percentage the image of the [`Viewer`] will be scaled by /// when zoomed in / out. /// /// Default is `0.10` pub fn scale_step(mut self, scale_step: f32) -> Self { self.scale_step = scale_step; self } } impl<Message, Theme, Renderer, Handle> Widget<Message, Theme, Renderer> for Viewer<Handle> where Renderer: image::Renderer<Handle = Handle>, Handle: Clone, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State>() } fn state(&self) -> tree::State { tree::State::new(State::new()) } 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 { // The raw w/h of the underlying image let image_size = renderer.measure_image(&self.handle).unwrap_or_default(); let image_size = Size::new(image_size.width as f32, image_size.height as f32); // The size to be available to the widget prior to `Shrink`ing let raw_size = limits.resolve(self.width, self.height, image_size); // The uncropped size of the image when fit to the bounds above let full_size = self.content_fit.fit(image_size, raw_size); // Shrink the widget to fit the resized image, if requested let final_size = Size { width: match self.width { Length::Shrink => f32::min(raw_size.width, full_size.width), _ => raw_size.width, }, height: match self.height { Length::Shrink => f32::min(raw_size.height, full_size.height), _ => raw_size.height, }, }; layout::Node::new(final_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 bounds = layout.bounds(); match event { Event::Mouse(mouse::Event::WheelScrolled { delta }) => { let Some(cursor_position) = cursor.position_over(bounds) else { return; }; match *delta { mouse::ScrollDelta::Lines { y, .. } | mouse::ScrollDelta::Pixels { y, .. } => { let state = tree.state.downcast_mut::<State>(); let previous_scale = state.scale; if y < 0.0 && previous_scale > self.min_scale || y > 0.0 && previous_scale < self.max_scale { state.scale = (if y > 0.0 { state.scale * (1.0 + self.scale_step) } else { state.scale / (1.0 + self.scale_step) }) .clamp(self.min_scale, self.max_scale); let scaled_size = scaled_image_size( renderer, &self.handle, state, bounds.size(), self.content_fit, ); let factor = state.scale / previous_scale - 1.0; let cursor_to_center = cursor_position - bounds.center(); let adjustment = cursor_to_center * factor + state.current_offset * factor; state.current_offset = Vector::new( if scaled_size.width > bounds.width { state.current_offset.x + adjustment.x } else { 0.0 }, if scaled_size.height > bounds.height { state.current_offset.y + adjustment.y } else { 0.0 }, ); } } } shell.request_redraw(); shell.capture_event(); } Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { let Some(cursor_position) = cursor.position_over(bounds) else { return; }; let state = tree.state.downcast_mut::<State>(); state.cursor_grabbed_at = Some(cursor_position); state.starting_offset = state.current_offset; shell.capture_event(); } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => { let state = tree.state.downcast_mut::<State>(); state.cursor_grabbed_at = None; } Event::Mouse(mouse::Event::CursorMoved { position }) => { let state = tree.state.downcast_mut::<State>(); if let Some(origin) = state.cursor_grabbed_at { let scaled_size = scaled_image_size( renderer, &self.handle, state, bounds.size(), self.content_fit, ); let hidden_width = (scaled_size.width - bounds.width / 2.0).max(0.0).round(); let hidden_height = (scaled_size.height - bounds.height / 2.0).max(0.0).round(); let delta = *position - origin; let x = if bounds.width < scaled_size.width { (state.starting_offset.x - delta.x).clamp(-hidden_width, hidden_width) } else { 0.0 }; let y = if bounds.height < scaled_size.height { (state.starting_offset.y - delta.y).clamp(-hidden_height, hidden_height) } else { 0.0 }; state.current_offset = Vector::new(x, y); shell.request_redraw(); shell.capture_event(); } } _ => {} } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { let state = tree.state.downcast_ref::<State>(); let bounds = layout.bounds(); let is_mouse_over = cursor.is_over(bounds); if state.is_cursor_grabbed() { mouse::Interaction::Grabbing } else if is_mouse_over { mouse::Interaction::Grab } else { mouse::Interaction::None } } fn draw( &self, tree: &Tree, renderer: &mut Renderer, _theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { let state = tree.state.downcast_ref::<State>(); let bounds = layout.bounds(); let final_size = scaled_image_size( renderer, &self.handle, state, bounds.size(), self.content_fit, ); let translation = { let diff_w = bounds.width - final_size.width; let diff_h = bounds.height - final_size.height; let image_top_left = match self.content_fit { ContentFit::None => Vector::new(diff_w.max(0.0) / 2.0, diff_h.max(0.0) / 2.0), _ => Vector::new(diff_w / 2.0, diff_h / 2.0), }; image_top_left - state.offset(bounds, final_size) }; let drawing_bounds = Rectangle::new(bounds.position(), final_size); let render = |renderer: &mut Renderer| { renderer.with_translation(translation, |renderer| { renderer.draw_image( Image { handle: self.handle.clone(), border_radius: border::Radius::default(), filter_method: self.filter_method, rotation: Radians(0.0), opacity: 1.0, snap: true, }, drawing_bounds, *viewport - translation, ); }); }; renderer.with_layer(bounds, render); } } /// The local state of a [`Viewer`]. #[derive(Debug, Clone, Copy)] pub struct State { scale: f32, starting_offset: Vector, current_offset: Vector, cursor_grabbed_at: Option<Point>, } impl Default for State { fn default() -> Self { Self { scale: 1.0, starting_offset: Vector::default(), current_offset: Vector::default(), cursor_grabbed_at: None, } } } impl State { /// Creates a new [`State`]. pub fn new() -> Self { State::default() } /// Returns the current offset of the [`State`], given the bounds /// of the [`Viewer`] and its image. fn offset(&self, bounds: Rectangle, image_size: Size) -> Vector { let hidden_width = (image_size.width - bounds.width / 2.0).max(0.0).round(); let hidden_height = (image_size.height - bounds.height / 2.0).max(0.0).round(); Vector::new( self.current_offset.x.clamp(-hidden_width, hidden_width), self.current_offset.y.clamp(-hidden_height, hidden_height), ) } /// Returns if the cursor is currently grabbed by the [`Viewer`]. pub fn is_cursor_grabbed(&self) -> bool { self.cursor_grabbed_at.is_some() } } impl<'a, Message, Theme, Renderer, Handle> From<Viewer<Handle>> for Element<'a, Message, Theme, Renderer> where Renderer: 'a + image::Renderer<Handle = Handle>, Message: 'a, Handle: Clone + 'a, { fn from(viewer: Viewer<Handle>) -> Element<'a, Message, Theme, Renderer> { Element::new(viewer) } } /// Returns the bounds of the underlying image, given the bounds of /// the [`Viewer`]. Scaling will be applied and original aspect ratio /// will be respected. pub fn scaled_image_size<Renderer>( renderer: &Renderer, handle: &<Renderer as image::Renderer>::Handle, state: &State, bounds: Size, content_fit: ContentFit, ) -> Size where Renderer: image::Renderer, { let Size { width, height } = renderer.measure_image(handle).unwrap_or_default(); let image_size = Size::new(width as f32, height as f32); let adjusted_fit = content_fit.fit(image_size, bounds); Size::new( adjusted_fit.width * state.scale, adjusted_fit.height * state.scale, ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/node.rs
widget/src/pane_grid/node.rs
use crate::core::{Rectangle, Size}; use crate::pane_grid::{Axis, Pane, Split}; use std::collections::BTreeMap; /// A layout node of a [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone)] pub enum Node { /// The region of this [`Node`] is split into two. Split { /// The [`Split`] of this [`Node`]. id: Split, /// The direction of the split. axis: Axis, /// The ratio of the split in [0.0, 1.0]. ratio: f32, /// The left/top [`Node`] of the split. a: Box<Node>, /// The right/bottom [`Node`] of the split. b: Box<Node>, }, /// The region of this [`Node`] is taken by a [`Pane`]. Pane(Pane), } #[derive(Debug)] enum Count { Split { horizontal: usize, vertical: usize, a: Box<Count>, b: Box<Count>, }, Pane, } impl Count { fn horizontal(&self) -> usize { match self { Count::Split { horizontal, .. } => *horizontal, Count::Pane => 0, } } fn vertical(&self) -> usize { match self { Count::Split { vertical, .. } => *vertical, Count::Pane => 0, } } } impl Node { /// Returns an iterator over each [`Split`] in this [`Node`]. pub fn splits(&self) -> impl Iterator<Item = &Split> { let mut unvisited_nodes = vec![self]; std::iter::from_fn(move || { while let Some(node) = unvisited_nodes.pop() { if let Node::Split { id, a, b, .. } = node { unvisited_nodes.push(a); unvisited_nodes.push(b); return Some(id); } } None }) } fn count(&self) -> Count { match self { Node::Split { a, b, axis, .. } => { let a = a.count(); let b = b.count(); let (horizontal, vertical) = match axis { Axis::Horizontal => ( 1 + a.horizontal() + b.horizontal(), a.vertical().max(b.vertical()), ), Axis::Vertical => ( a.horizontal().max(b.horizontal()), 1 + a.vertical() + b.vertical(), ), }; Count::Split { horizontal, vertical, a: Box::new(a), b: Box::new(b), } } Node::Pane(_) => Count::Pane, } } /// Returns the rectangular region for each [`Pane`] in the [`Node`] given /// the spacing between panes and the total available space. pub fn pane_regions( &self, spacing: f32, min_size: f32, bounds: Size, ) -> BTreeMap<Pane, Rectangle> { let mut regions = BTreeMap::new(); let count = self.count(); self.compute_regions( spacing, min_size, &Rectangle { x: 0.0, y: 0.0, width: bounds.width, height: bounds.height, }, &count, &mut regions, ); regions } /// Returns the axis, rectangular region, and ratio for each [`Split`] in /// the [`Node`] given the spacing between panes and the total available /// space. pub fn split_regions( &self, spacing: f32, min_size: f32, bounds: Size, ) -> BTreeMap<Split, (Axis, Rectangle, f32)> { let mut splits = BTreeMap::new(); let count = self.count(); self.compute_splits( spacing, min_size, &Rectangle { x: 0.0, y: 0.0, width: bounds.width, height: bounds.height, }, &count, &mut splits, ); splits } pub(crate) fn find(&mut self, pane: Pane) -> Option<&mut Node> { match self { Node::Split { a, b, .. } => a.find(pane).or_else(move || b.find(pane)), Node::Pane(p) => { if *p == pane { Some(self) } else { None } } } } pub(crate) fn split(&mut self, id: Split, axis: Axis, new_pane: Pane) { *self = Node::Split { id, axis, ratio: 0.5, a: Box::new(self.clone()), b: Box::new(Node::Pane(new_pane)), }; } pub(crate) fn split_inverse(&mut self, id: Split, axis: Axis, pane: Pane) { *self = Node::Split { id, axis, ratio: 0.5, a: Box::new(Node::Pane(pane)), b: Box::new(self.clone()), }; } pub(crate) fn update(&mut self, f: &impl Fn(&mut Node)) { if let Node::Split { a, b, .. } = self { a.update(f); b.update(f); } f(self); } pub(crate) fn resize(&mut self, split: Split, percentage: f32) -> bool { match self { Node::Split { id, ratio, a, b, .. } => { if *id == split { *ratio = percentage; true } else if a.resize(split, percentage) { true } else { b.resize(split, percentage) } } Node::Pane(_) => false, } } pub(crate) fn remove(&mut self, pane: Pane) -> Option<Pane> { match self { Node::Split { a, b, .. } => { if a.pane() == Some(pane) { *self = *b.clone(); Some(self.first_pane()) } else if b.pane() == Some(pane) { *self = *a.clone(); Some(self.first_pane()) } else { a.remove(pane).or_else(|| b.remove(pane)) } } Node::Pane(_) => None, } } fn pane(&self) -> Option<Pane> { match self { Node::Split { .. } => None, Node::Pane(pane) => Some(*pane), } } fn first_pane(&self) -> Pane { match self { Node::Split { a, .. } => a.first_pane(), Node::Pane(pane) => *pane, } } fn compute_regions( &self, spacing: f32, min_size: f32, current: &Rectangle, count: &Count, regions: &mut BTreeMap<Pane, Rectangle>, ) { match (self, count) { ( Node::Split { axis, ratio, a, b, .. }, Count::Split { a: count_a, b: count_b, .. }, ) => { let (a_factor, b_factor) = match axis { Axis::Horizontal => (count_a.horizontal(), count_b.horizontal()), Axis::Vertical => (count_a.vertical(), count_b.vertical()), }; let (region_a, region_b, _ratio) = axis.split( current, *ratio, spacing, min_size * (a_factor + 1) as f32 + spacing * a_factor as f32, min_size * (b_factor + 1) as f32 + spacing * b_factor as f32, ); a.compute_regions(spacing, min_size, &region_a, count_a, regions); b.compute_regions(spacing, min_size, &region_b, count_b, regions); } (Node::Pane(pane), Count::Pane) => { let _ = regions.insert(*pane, *current); } _ => { unreachable!("Node configuration and count do not match") } } } fn compute_splits( &self, spacing: f32, min_size: f32, current: &Rectangle, count: &Count, splits: &mut BTreeMap<Split, (Axis, Rectangle, f32)>, ) { match (self, count) { ( Node::Split { axis, ratio, a, b, id, }, Count::Split { a: count_a, b: count_b, .. }, ) => { let (a_factor, b_factor) = match axis { Axis::Horizontal => (count_a.horizontal(), count_b.horizontal()), Axis::Vertical => (count_a.vertical(), count_b.vertical()), }; let (region_a, region_b, ratio) = axis.split( current, *ratio, spacing, min_size * (a_factor + 1) as f32 + spacing * a_factor as f32, min_size * (b_factor + 1) as f32 + spacing * b_factor as f32, ); let _ = splits.insert(*id, (*axis, *current, ratio)); a.compute_splits(spacing, min_size, &region_a, count_a, splits); b.compute_splits(spacing, min_size, &region_b, count_b, splits); } (Node::Pane(_), Count::Pane) => {} _ => { unreachable!("Node configuration and split count do not match") } } } } impl std::hash::Hash for Node { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { Node::Split { id, axis, ratio, a, b, } => { id.hash(state); axis.hash(state); ((ratio * 100_000.0) as u32).hash(state); a.hash(state); b.hash(state); } Node::Pane(pane) => { pane.hash(state); } } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/controls.rs
widget/src/pane_grid/controls.rs
use crate::container; use crate::core::{self, Element}; /// The controls of a [`Pane`]. /// /// [`Pane`]: super::Pane pub struct Controls<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { pub(super) full: Element<'a, Message, Theme, Renderer>, pub(super) compact: Option<Element<'a, Message, Theme, Renderer>>, } impl<'a, Message, Theme, Renderer> Controls<'a, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { /// Creates a new [`Controls`] with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { full: content.into(), compact: None, } } /// Creates a new [`Controls`] with a full and compact variant. /// If there is not enough room to show the full variant without overlap, /// then the compact variant will be shown instead. pub fn dynamic( full: impl Into<Element<'a, Message, Theme, Renderer>>, compact: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Self { Self { full: full.into(), compact: Some(compact.into()), } } } impl<'a, Message, Theme, Renderer> From<Element<'a, Message, Theme, Renderer>> for Controls<'a, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { fn from(value: Element<'a, Message, Theme, Renderer>) -> Self { Self::new(value) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/content.rs
widget/src/pane_grid/content.rs
use crate::container; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{self, Tree}; use crate::core::{self, Clipboard, Element, Event, Layout, Point, Rectangle, Shell, Size, Vector}; use crate::pane_grid::{Draggable, TitleBar}; /// The content of a [`Pane`]. /// /// [`Pane`]: super::Pane pub struct Content<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { title_bar: Option<TitleBar<'a, Message, Theme, Renderer>>, body: Element<'a, Message, Theme, Renderer>, class: Theme::Class<'a>, } impl<'a, Message, Theme, Renderer> Content<'a, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { /// Creates a new [`Content`] with the provided body. pub fn new(body: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { title_bar: None, body: body.into(), class: Theme::default(), } } /// Sets the [`TitleBar`] of the [`Content`]. pub fn title_bar(mut self, title_bar: TitleBar<'a, Message, Theme, Renderer>) -> Self { self.title_bar = Some(title_bar); self } /// Sets the style of the [`Content`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> container::Style + 'a) -> Self where Theme::Class<'a>: From<container::StyleFn<'a, Theme>>, { self.class = (Box::new(style) as container::StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`Content`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> Content<'_, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { pub(super) fn state(&self) -> Tree { let children = if let Some(title_bar) = self.title_bar.as_ref() { vec![Tree::new(&self.body), title_bar.state()] } else { vec![Tree::new(&self.body), Tree::empty()] }; Tree { children, ..Tree::empty() } } pub(super) fn diff(&self, tree: &mut Tree) { if tree.children.len() == 2 { if let Some(title_bar) = self.title_bar.as_ref() { title_bar.diff(&mut tree.children[1]); } tree.children[0].diff(&self.body); } else { *tree = self.state(); } } /// Draws the [`Content`] with the provided [`Renderer`] and [`Layout`]. /// /// [`Renderer`]: core::Renderer pub 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 style = theme.style(&self.class); container::draw_background(renderer, &style, bounds); } if let Some(title_bar) = &self.title_bar { let mut children = layout.children(); let title_bar_layout = children.next().unwrap(); let body_layout = children.next().unwrap(); let show_controls = cursor.is_over(bounds); self.body.as_widget().draw( &tree.children[0], renderer, theme, style, body_layout, cursor, viewport, ); title_bar.draw( &tree.children[1], renderer, theme, style, title_bar_layout, cursor, viewport, show_controls, ); } else { self.body.as_widget().draw( &tree.children[0], renderer, theme, style, layout, cursor, viewport, ); } } pub(crate) fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { if let Some(title_bar) = &mut self.title_bar { let max_size = limits.max(); let title_bar_layout = title_bar.layout( &mut tree.children[1], renderer, &layout::Limits::new(Size::ZERO, max_size), ); let title_bar_size = title_bar_layout.size(); let body_layout = self.body.as_widget_mut().layout( &mut tree.children[0], renderer, &layout::Limits::new( Size::ZERO, Size::new(max_size.width, max_size.height - title_bar_size.height), ), ); layout::Node::with_children( max_size, vec![ title_bar_layout, body_layout.move_to(Point::new(0.0, title_bar_size.height)), ], ) } else { self.body .as_widget_mut() .layout(&mut tree.children[0], renderer, limits) } } pub(crate) fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { let body_layout = if let Some(title_bar) = &mut self.title_bar { let mut children = layout.children(); title_bar.operate( &mut tree.children[1], children.next().unwrap(), renderer, operation, ); children.next().unwrap() } else { layout }; self.body .as_widget_mut() .operate(&mut tree.children[0], body_layout, renderer, operation); } pub(crate) 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, is_picked: bool, ) { let body_layout = if let Some(title_bar) = &mut self.title_bar { let mut children = layout.children(); title_bar.update( &mut tree.children[1], event, children.next().unwrap(), cursor, renderer, clipboard, shell, viewport, ); children.next().unwrap() } else { layout }; if !is_picked { self.body.as_widget_mut().update( &mut tree.children[0], event, body_layout, cursor, renderer, clipboard, shell, viewport, ); } } pub(crate) fn grid_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, drag_enabled: bool, ) -> Option<mouse::Interaction> { let title_bar = self.title_bar.as_ref()?; let mut children = layout.children(); let title_bar_layout = children.next().unwrap(); let is_over_pick_area = cursor .position() .map(|cursor_position| title_bar.is_over_pick_area(title_bar_layout, cursor_position)) .unwrap_or_default(); if is_over_pick_area && drag_enabled { return Some(mouse::Interaction::Grab); } None } pub(crate) fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, drag_enabled: bool, ) -> mouse::Interaction { let (body_layout, title_bar_interaction) = if let Some(title_bar) = &self.title_bar { let mut children = layout.children(); let title_bar_layout = children.next().unwrap(); let is_over_pick_area = cursor .position() .map(|cursor_position| { title_bar.is_over_pick_area(title_bar_layout, cursor_position) }) .unwrap_or_default(); if is_over_pick_area && drag_enabled { return mouse::Interaction::Grab; } let mouse_interaction = title_bar.mouse_interaction( &tree.children[1], title_bar_layout, cursor, viewport, renderer, ); (children.next().unwrap(), mouse_interaction) } else { (layout, mouse::Interaction::default()) }; self.body .as_widget() .mouse_interaction(&tree.children[0], body_layout, cursor, viewport, renderer) .max(title_bar_interaction) } pub(crate) 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>> { if let Some(title_bar) = self.title_bar.as_mut() { let mut children = layout.children(); let title_bar_layout = children.next()?; let mut states = tree.children.iter_mut(); let body_state = states.next().unwrap(); let title_bar_state = states.next().unwrap(); match title_bar.overlay( title_bar_state, title_bar_layout, renderer, viewport, translation, ) { Some(overlay) => Some(overlay), None => self.body.as_widget_mut().overlay( body_state, children.next()?, renderer, viewport, translation, ), } } else { self.body.as_widget_mut().overlay( &mut tree.children[0], layout, renderer, viewport, translation, ) } } } impl<Message, Theme, Renderer> Draggable for &Content<'_, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { fn can_be_dragged_at(&self, layout: Layout<'_>, cursor_position: Point) -> bool { if let Some(title_bar) = &self.title_bar { let mut children = layout.children(); let title_bar_layout = children.next().unwrap(); title_bar.is_over_pick_area(title_bar_layout, cursor_position) } else { false } } } impl<'a, T, Message, Theme, Renderer> From<T> for Content<'a, Message, Theme, Renderer> where T: Into<Element<'a, Message, Theme, Renderer>>, Theme: container::Catalog + 'a, Renderer: core::Renderer, { fn from(element: T) -> Self { Self::new(element) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/configuration.rs
widget/src/pane_grid/configuration.rs
use crate::pane_grid::Axis; /// The arrangement of a [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone)] pub enum Configuration<T> { /// A split of the available space. Split { /// The direction of the split. axis: Axis, /// The ratio of the split in [0.0, 1.0]. ratio: f32, /// The left/top [`Configuration`] of the split. a: Box<Configuration<T>>, /// The right/bottom [`Configuration`] of the split. b: Box<Configuration<T>>, }, /// A [`Pane`]. /// /// [`Pane`]: super::Pane Pane(T), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/state.rs
widget/src/pane_grid/state.rs
//! The state of a [`PaneGrid`]. //! //! [`PaneGrid`]: super::PaneGrid use crate::core::{Point, Size}; use crate::pane_grid::{Axis, Configuration, Direction, Edge, Node, Pane, Region, Split, Target}; use std::borrow::Cow; use std::collections::BTreeMap; /// The state of a [`PaneGrid`]. /// /// It keeps track of the state of each [`Pane`] and the position of each /// [`Split`]. /// /// The [`State`] needs to own any mutable contents a [`Pane`] may need. This is /// why this struct is generic over the type `T`. Values of this type are /// provided to the view function of [`PaneGrid::new`] for displaying each /// [`Pane`]. /// /// [`PaneGrid`]: super::PaneGrid /// [`PaneGrid::new`]: super::PaneGrid::new #[derive(Debug, Clone)] pub struct State<T> { /// The panes of the [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid pub panes: BTreeMap<Pane, T>, /// The internal state of the [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid pub internal: Internal, } impl<T> State<T> { /// Creates a new [`State`], initializing the first pane with the provided /// state. /// /// Alongside the [`State`], it returns the first [`Pane`] identifier. pub fn new(first_pane_state: T) -> (Self, Pane) { ( Self::with_configuration(Configuration::Pane(first_pane_state)), Pane(0), ) } /// Creates a new [`State`] with the given [`Configuration`]. pub fn with_configuration(config: impl Into<Configuration<T>>) -> Self { let mut panes = BTreeMap::default(); let internal = Internal::from_configuration(&mut panes, config.into(), 0); State { panes, internal } } /// Returns the total amount of panes in the [`State`]. pub fn len(&self) -> usize { self.panes.len() } /// Returns `true` if the amount of panes in the [`State`] is 0. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the internal state of the given [`Pane`], if it exists. pub fn get(&self, pane: Pane) -> Option<&T> { self.panes.get(&pane) } /// Returns the internal state of the given [`Pane`] with mutability, if it /// exists. pub fn get_mut(&mut self, pane: Pane) -> Option<&mut T> { self.panes.get_mut(&pane) } /// Returns an iterator over all the panes of the [`State`], alongside its /// internal state. pub fn iter(&self) -> impl Iterator<Item = (&Pane, &T)> { self.panes.iter() } /// Returns a mutable iterator over all the panes of the [`State`], /// alongside its internal state. pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Pane, &mut T)> { self.panes.iter_mut() } /// Returns the layout of the [`State`]. pub fn layout(&self) -> &Node { &self.internal.layout } /// Returns the adjacent [`Pane`] of another [`Pane`] in the given /// direction, if there is one. pub fn adjacent(&self, pane: Pane, direction: Direction) -> Option<Pane> { let regions = self .internal .layout .pane_regions(0.0, 0.0, Size::new(4096.0, 4096.0)); let current_region = regions.get(&pane)?; let target = match direction { Direction::Left => Point::new(current_region.x - 1.0, current_region.y + 1.0), Direction::Right => Point::new( current_region.x + current_region.width + 1.0, current_region.y + 1.0, ), Direction::Up => Point::new(current_region.x + 1.0, current_region.y - 1.0), Direction::Down => Point::new( current_region.x + 1.0, current_region.y + current_region.height + 1.0, ), }; let mut colliding_regions = regions.iter().filter(|(_, region)| region.contains(target)); let (pane, _) = colliding_regions.next()?; Some(*pane) } /// Splits the given [`Pane`] into two in the given [`Axis`] and /// initializing the new [`Pane`] with the provided internal state. pub fn split(&mut self, axis: Axis, pane: Pane, state: T) -> Option<(Pane, Split)> { self.split_node(axis, Some(pane), state, false) } /// Split a target [`Pane`] with a given [`Pane`] on a given [`Region`]. /// /// Panes will be swapped by default for [`Region::Center`]. pub fn split_with(&mut self, target: Pane, pane: Pane, region: Region) { match region { Region::Center => self.swap(pane, target), Region::Edge(edge) => match edge { Edge::Top => { self.split_and_swap(Axis::Horizontal, target, pane, true); } Edge::Bottom => { self.split_and_swap(Axis::Horizontal, target, pane, false); } Edge::Left => { self.split_and_swap(Axis::Vertical, target, pane, true); } Edge::Right => { self.split_and_swap(Axis::Vertical, target, pane, false); } }, } } /// Drops the given [`Pane`] into the provided [`Target`]. pub fn drop(&mut self, pane: Pane, target: Target) { match target { Target::Edge(edge) => self.move_to_edge(pane, edge), Target::Pane(target, region) => { self.split_with(target, pane, region); } } } fn split_node( &mut self, axis: Axis, pane: Option<Pane>, state: T, inverse: bool, ) -> Option<(Pane, Split)> { let node = if let Some(pane) = pane { self.internal.layout.find(pane)? } else { // Major node &mut self.internal.layout }; let new_pane = { self.internal.last_id = self.internal.last_id.checked_add(1)?; Pane(self.internal.last_id) }; let new_split = { self.internal.last_id = self.internal.last_id.checked_add(1)?; Split(self.internal.last_id) }; if inverse { node.split_inverse(new_split, axis, new_pane); } else { node.split(new_split, axis, new_pane); } let _ = self.panes.insert(new_pane, state); let _ = self.internal.maximized.take(); Some((new_pane, new_split)) } fn split_and_swap(&mut self, axis: Axis, target: Pane, pane: Pane, swap: bool) { if let Some((state, _)) = self.close(pane) && let Some((new_pane, _)) = self.split(axis, target, state) { // Ensure new node corresponds to original closed `Pane` for state continuity self.relabel(new_pane, pane); if swap { self.swap(target, pane); } } } /// Move [`Pane`] to an [`Edge`] of the [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid pub fn move_to_edge(&mut self, pane: Pane, edge: Edge) { match edge { Edge::Top => { self.split_major_node_and_swap(Axis::Horizontal, pane, true); } Edge::Bottom => { self.split_major_node_and_swap(Axis::Horizontal, pane, false); } Edge::Left => { self.split_major_node_and_swap(Axis::Vertical, pane, true); } Edge::Right => { self.split_major_node_and_swap(Axis::Vertical, pane, false); } } } fn split_major_node_and_swap(&mut self, axis: Axis, pane: Pane, inverse: bool) { if let Some((state, _)) = self.close(pane) && let Some((new_pane, _)) = self.split_node(axis, None, state, inverse) { // Ensure new node corresponds to original closed `Pane` for state continuity self.relabel(new_pane, pane); } } fn relabel(&mut self, target: Pane, label: Pane) { self.swap(target, label); let _ = self .panes .remove(&target) .and_then(|state| self.panes.insert(label, state)); } /// Swaps the position of the provided panes in the [`State`]. /// /// If you want to swap panes on drag and drop in your [`PaneGrid`], you /// will need to call this method when handling a [`DragEvent`]. /// /// [`PaneGrid`]: super::PaneGrid /// [`DragEvent`]: super::DragEvent pub fn swap(&mut self, a: Pane, b: Pane) { self.internal.layout.update(&|node| match node { Node::Split { .. } => {} Node::Pane(pane) => { if *pane == a { *node = Node::Pane(b); } else if *pane == b { *node = Node::Pane(a); } } }); } /// Resizes two panes by setting the position of the provided [`Split`]. /// /// The ratio is a value in [0, 1], representing the exact position of a /// [`Split`] between two panes. /// /// If you want to enable resize interactions in your [`PaneGrid`], you will /// need to call this method when handling a [`ResizeEvent`]. /// /// [`PaneGrid`]: super::PaneGrid /// [`ResizeEvent`]: super::ResizeEvent pub fn resize(&mut self, split: Split, ratio: f32) { let _ = self.internal.layout.resize(split, ratio); } /// Closes the given [`Pane`] and returns its internal state and its closest /// sibling, if it exists. pub fn close(&mut self, pane: Pane) -> Option<(T, Pane)> { if self.internal.maximized == Some(pane) { let _ = self.internal.maximized.take(); } if let Some(sibling) = self.internal.layout.remove(pane) { self.panes.remove(&pane).map(|state| (state, sibling)) } else { None } } /// Maximize the given [`Pane`]. Only this pane will be rendered by the /// [`PaneGrid`] until [`Self::restore()`] is called. /// /// [`PaneGrid`]: super::PaneGrid pub fn maximize(&mut self, pane: Pane) { self.internal.maximized = Some(pane); } /// Restore the currently maximized [`Pane`] to it's normal size. All panes /// will be rendered by the [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid pub fn restore(&mut self) { let _ = self.internal.maximized.take(); } /// Returns the maximized [`Pane`] of the [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid pub fn maximized(&self) -> Option<Pane> { self.internal.maximized } } /// The internal state of a [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone)] pub struct Internal { layout: Node, last_id: usize, maximized: Option<Pane>, } impl Internal { /// Initializes the [`Internal`] state of a [`PaneGrid`] from a /// [`Configuration`]. /// /// [`PaneGrid`]: super::PaneGrid pub fn from_configuration<T>( panes: &mut BTreeMap<Pane, T>, content: Configuration<T>, next_id: usize, ) -> Self { let (layout, last_id) = match content { Configuration::Split { axis, ratio, a, b } => { let Internal { layout: a, last_id: next_id, .. } = Self::from_configuration(panes, *a, next_id); let Internal { layout: b, last_id: next_id, .. } = Self::from_configuration(panes, *b, next_id); ( Node::Split { id: Split(next_id), axis, ratio, a: Box::new(a), b: Box::new(b), }, next_id + 1, ) } Configuration::Pane(state) => { let id = Pane(next_id); let _ = panes.insert(id, state); (Node::Pane(id), next_id + 1) } }; Self { layout, last_id, maximized: None, } } pub(super) fn layout(&self) -> Cow<'_, Node> { match self.maximized { Some(pane) => Cow::Owned(Node::Pane(pane)), None => Cow::Borrowed(&self.layout), } } pub(super) fn maximized(&self) -> Option<Pane> { self.maximized } } /// The current action of a [`PaneGrid`]. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone, Copy, PartialEq, Default)] pub enum Action { /// The [`PaneGrid`] is idle. /// /// [`PaneGrid`]: super::PaneGrid #[default] Idle, /// A [`Pane`] in the [`PaneGrid`] is being dragged. /// /// [`PaneGrid`]: super::PaneGrid Dragging { /// The [`Pane`] being dragged. pane: Pane, /// The starting [`Point`] of the drag interaction. origin: Point, }, /// A [`Split`] in the [`PaneGrid`] is being dragged. /// /// [`PaneGrid`]: super::PaneGrid Resizing { /// The [`Split`] being dragged. split: Split, /// The [`Axis`] of the [`Split`]. axis: Axis, }, } impl Action { /// Returns the current [`Pane`] that is being dragged, if any. pub fn picked_pane(&self) -> Option<(Pane, Point)> { match *self { Action::Dragging { pane, origin, .. } => Some((pane, origin)), _ => None, } } /// Returns the current [`Split`] that is being dragged, if any. pub fn picked_split(&self) -> Option<(Split, Axis)> { match *self { Action::Resizing { split, axis, .. } => Some((split, axis)), _ => None, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/draggable.rs
widget/src/pane_grid/draggable.rs
use crate::core::{Layout, Point}; /// A pane that can be dragged. pub trait Draggable { /// Returns whether the [`Draggable`] with the given [`Layout`] can be picked /// at the provided cursor position. fn can_be_dragged_at(&self, layout: Layout<'_>, cursor: Point) -> bool; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/title_bar.rs
widget/src/pane_grid/title_bar.rs
use crate::container; use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{self, Tree}; use crate::core::{ self, Clipboard, Element, Event, Layout, Padding, Point, Rectangle, Shell, Size, Vector, }; use crate::pane_grid::controls::Controls; /// The title bar of a [`Pane`]. /// /// [`Pane`]: super::Pane pub struct TitleBar<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { content: Element<'a, Message, Theme, Renderer>, controls: Option<Controls<'a, Message, Theme, Renderer>>, padding: Padding, always_show_controls: bool, class: Theme::Class<'a>, } impl<'a, Message, Theme, Renderer> TitleBar<'a, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { /// Creates a new [`TitleBar`] with the given content. pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self { Self { content: content.into(), controls: None, padding: Padding::ZERO, always_show_controls: false, class: Theme::default(), } } /// Sets the controls of the [`TitleBar`]. pub fn controls(mut self, controls: impl Into<Controls<'a, Message, Theme, Renderer>>) -> Self { self.controls = Some(controls.into()); self } /// Sets the [`Padding`] of the [`TitleBar`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets whether or not the [`controls`] attached to this [`TitleBar`] are /// always visible. /// /// By default, the controls are only visible when the [`Pane`] of this /// [`TitleBar`] is hovered. /// /// [`controls`]: Self::controls /// [`Pane`]: super::Pane pub fn always_show_controls(mut self) -> Self { self.always_show_controls = true; self } /// Sets the style of the [`TitleBar`]. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> container::Style + 'a) -> Self where Theme::Class<'a>: From<container::StyleFn<'a, Theme>>, { self.class = (Box::new(style) as container::StyleFn<'a, Theme>).into(); self } /// Sets the style class of the [`TitleBar`]. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<Message, Theme, Renderer> TitleBar<'_, Message, Theme, Renderer> where Theme: container::Catalog, Renderer: core::Renderer, { pub(super) fn state(&self) -> Tree { let children = match self.controls.as_ref() { Some(controls) => match controls.compact.as_ref() { Some(compact) => vec![ Tree::new(&self.content), Tree::new(&controls.full), Tree::new(compact), ], None => vec![ Tree::new(&self.content), Tree::new(&controls.full), Tree::empty(), ], }, None => { vec![Tree::new(&self.content), Tree::empty(), Tree::empty()] } }; Tree { children, ..Tree::empty() } } pub(super) fn diff(&self, tree: &mut Tree) { if tree.children.len() == 3 { if let Some(controls) = self.controls.as_ref() { if let Some(compact) = controls.compact.as_ref() { tree.children[2].diff(compact); } tree.children[1].diff(&controls.full); } tree.children[0].diff(&self.content); } else { *tree = self.state(); } } /// Draws the [`TitleBar`] with the provided [`Renderer`] and [`Layout`]. /// /// [`Renderer`]: core::Renderer pub fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, inherited_style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, show_controls: bool, ) { let bounds = layout.bounds(); let style = theme.style(&self.class); let inherited_style = renderer::Style { text_color: style.text_color.unwrap_or(inherited_style.text_color), }; container::draw_background(renderer, &style, bounds); let mut children = layout.children(); let padded = children.next().unwrap(); let mut children = padded.children(); let title_layout = children.next().unwrap(); let mut show_title = true; if let Some(controls) = &self.controls && (show_controls || self.always_show_controls) { let controls_layout = children.next().unwrap(); if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if let Some(compact) = controls.compact.as_ref() { let compact_layout = children.next().unwrap(); compact.as_widget().draw( &tree.children[2], renderer, theme, &inherited_style, compact_layout, cursor, viewport, ); } else { show_title = false; controls.full.as_widget().draw( &tree.children[1], renderer, theme, &inherited_style, controls_layout, cursor, viewport, ); } } else { controls.full.as_widget().draw( &tree.children[1], renderer, theme, &inherited_style, controls_layout, cursor, viewport, ); } } if show_title { self.content.as_widget().draw( &tree.children[0], renderer, theme, &inherited_style, title_layout, cursor, viewport, ); } } /// Returns whether the mouse cursor is over the pick area of the /// [`TitleBar`] or not. /// /// The whole [`TitleBar`] is a pick area, except its controls. pub fn is_over_pick_area(&self, layout: Layout<'_>, cursor_position: Point) -> bool { if layout.bounds().contains(cursor_position) { let mut children = layout.children(); let padded = children.next().unwrap(); let mut children = padded.children(); let title_layout = children.next().unwrap(); if let Some(controls) = self.controls.as_ref() { let controls_layout = children.next().unwrap(); if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if controls.compact.is_some() { let compact_layout = children.next().unwrap(); !compact_layout.bounds().contains(cursor_position) && !title_layout.bounds().contains(cursor_position) } else { !controls_layout.bounds().contains(cursor_position) } } else { !controls_layout.bounds().contains(cursor_position) && !title_layout.bounds().contains(cursor_position) } } else { !title_layout.bounds().contains(cursor_position) } } else { false } } pub(crate) fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let limits = limits.shrink(self.padding); let max_size = limits.max(); let title_layout = self.content.as_widget_mut().layout( &mut tree.children[0], renderer, &layout::Limits::new(Size::ZERO, max_size), ); let title_size = title_layout.size(); let node = if let Some(controls) = &mut self.controls { let controls_layout = controls.full.as_widget_mut().layout( &mut tree.children[1], renderer, &layout::Limits::new(Size::ZERO, max_size), ); if title_layout.bounds().width + controls_layout.bounds().width > max_size.width { if let Some(compact) = controls.compact.as_mut() { let compact_layout = compact.as_widget_mut().layout( &mut tree.children[2], renderer, &layout::Limits::new(Size::ZERO, max_size), ); let compact_size = compact_layout.size(); let space_before_controls = max_size.width - compact_size.width; let height = title_size.height.max(compact_size.height); layout::Node::with_children( Size::new(max_size.width, height), vec![ title_layout, controls_layout, compact_layout.move_to(Point::new(space_before_controls, 0.0)), ], ) } else { let controls_size = controls_layout.size(); let space_before_controls = max_size.width - controls_size.width; let height = title_size.height.max(controls_size.height); layout::Node::with_children( Size::new(max_size.width, height), vec![ title_layout, controls_layout.move_to(Point::new(space_before_controls, 0.0)), ], ) } } else { let controls_size = controls_layout.size(); let space_before_controls = max_size.width - controls_size.width; let height = title_size.height.max(controls_size.height); layout::Node::with_children( Size::new(max_size.width, height), vec![ title_layout, controls_layout.move_to(Point::new(space_before_controls, 0.0)), ], ) } } else { layout::Node::with_children( Size::new(max_size.width, title_size.height), vec![title_layout], ) }; layout::Node::container(node, self.padding) } pub(crate) fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { let mut children = layout.children(); let padded = children.next().unwrap(); let mut children = padded.children(); let title_layout = children.next().unwrap(); let mut show_title = true; if let Some(controls) = &mut self.controls { let controls_layout = children.next().unwrap(); if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if let Some(compact) = controls.compact.as_mut() { let compact_layout = children.next().unwrap(); compact.as_widget_mut().operate( &mut tree.children[2], compact_layout, renderer, operation, ); } else { show_title = false; controls.full.as_widget_mut().operate( &mut tree.children[1], controls_layout, renderer, operation, ); } } else { controls.full.as_widget_mut().operate( &mut tree.children[1], controls_layout, renderer, operation, ); } }; if show_title { self.content.as_widget_mut().operate( &mut tree.children[0], title_layout, renderer, operation, ); } } pub(crate) 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 mut children = layout.children(); let padded = children.next().unwrap(); let mut children = padded.children(); let title_layout = children.next().unwrap(); let mut show_title = true; if let Some(controls) = &mut self.controls { let controls_layout = children.next().unwrap(); if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if let Some(compact) = controls.compact.as_mut() { let compact_layout = children.next().unwrap(); compact.as_widget_mut().update( &mut tree.children[2], event, compact_layout, cursor, renderer, clipboard, shell, viewport, ); } else { show_title = false; controls.full.as_widget_mut().update( &mut tree.children[1], event, controls_layout, cursor, renderer, clipboard, shell, viewport, ); } } else { controls.full.as_widget_mut().update( &mut tree.children[1], event, controls_layout, cursor, renderer, clipboard, shell, viewport, ); } } if show_title { self.content.as_widget_mut().update( &mut tree.children[0], event, title_layout, cursor, renderer, clipboard, shell, viewport, ); } } pub(crate) fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { let mut children = layout.children(); let padded = children.next().unwrap(); let mut children = padded.children(); let title_layout = children.next().unwrap(); let title_interaction = self.content.as_widget().mouse_interaction( &tree.children[0], title_layout, cursor, viewport, renderer, ); if let Some(controls) = &self.controls { let controls_layout = children.next().unwrap(); let controls_interaction = controls.full.as_widget().mouse_interaction( &tree.children[1], controls_layout, cursor, viewport, renderer, ); if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if let Some(compact) = controls.compact.as_ref() { let compact_layout = children.next().unwrap(); let compact_interaction = compact.as_widget().mouse_interaction( &tree.children[2], compact_layout, cursor, viewport, renderer, ); compact_interaction.max(title_interaction) } else { controls_interaction } } else { controls_interaction.max(title_interaction) } } else { title_interaction } } pub(crate) 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 mut children = layout.children(); let padded = children.next()?; let mut children = padded.children(); let title_layout = children.next()?; let Self { content, controls, .. } = self; let mut states = tree.children.iter_mut(); let title_state = states.next().unwrap(); let controls_state = states.next().unwrap(); content .as_widget_mut() .overlay(title_state, title_layout, renderer, viewport, translation) .or_else(move || { controls.as_mut().and_then(|controls| { let controls_layout = children.next()?; if title_layout.bounds().width + controls_layout.bounds().width > padded.bounds().width { if let Some(compact) = controls.compact.as_mut() { let compact_state = states.next().unwrap(); let compact_layout = children.next()?; compact.as_widget_mut().overlay( compact_state, compact_layout, renderer, viewport, translation, ) } else { controls.full.as_widget_mut().overlay( controls_state, controls_layout, renderer, viewport, translation, ) } } else { controls.full.as_widget_mut().overlay( controls_state, controls_layout, renderer, viewport, translation, ) } }) }) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/pane.rs
widget/src/pane_grid/pane.rs
/// A rectangular region in a [`PaneGrid`] used to display widgets. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Pane(pub(super) usize);
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/axis.rs
widget/src/pane_grid/axis.rs
use crate::core::Rectangle; /// A fixed reference line for the measurement of coordinates. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Axis { /// The horizontal axis: — Horizontal, /// The vertical axis: | Vertical, } impl Axis { /// Splits the provided [`Rectangle`] on the current [`Axis`] with the /// given `ratio` and `spacing`. pub fn split( &self, rectangle: &Rectangle, ratio: f32, spacing: f32, min_size_a: f32, min_size_b: f32, ) -> (Rectangle, Rectangle, f32) { match self { Axis::Horizontal => { let height_top = (rectangle.height * ratio - spacing / 2.0) .round() .max(min_size_a) .min(rectangle.height - min_size_b - spacing); let height_bottom = (rectangle.height - height_top - spacing).max(min_size_b); let ratio = (height_top + spacing / 2.0) / rectangle.height; ( Rectangle { height: height_top, ..*rectangle }, Rectangle { y: rectangle.y + height_top + spacing, height: height_bottom, ..*rectangle }, ratio, ) } Axis::Vertical => { let width_left = (rectangle.width * ratio - spacing / 2.0) .round() .max(min_size_a) .min(rectangle.width - min_size_b - spacing); let width_right = (rectangle.width - width_left - spacing).max(min_size_b); let ratio = (width_left + spacing / 2.0) / rectangle.width; ( Rectangle { width: width_left, ..*rectangle }, Rectangle { x: rectangle.x + width_left + spacing, width: width_right, ..*rectangle }, ratio, ) } } } /// Calculates the bounds of the split line in a [`Rectangle`] region. pub fn split_line_bounds(&self, rectangle: Rectangle, ratio: f32, spacing: f32) -> Rectangle { match self { Axis::Horizontal => Rectangle { x: rectangle.x, y: (rectangle.y + rectangle.height * ratio - spacing / 2.0).round(), width: rectangle.width, height: spacing, }, Axis::Vertical => Rectangle { x: (rectangle.x + rectangle.width * ratio - spacing / 2.0).round(), y: rectangle.y, width: spacing, height: rectangle.height, }, } } } #[cfg(test)] mod tests { use super::*; enum Case { Horizontal { overall_height: f32, spacing: f32, top_height: f32, bottom_y: f32, bottom_height: f32, }, Vertical { overall_width: f32, spacing: f32, left_width: f32, right_x: f32, right_width: f32, }, } #[test] fn split() { let cases = vec![ // Even height, even spacing Case::Horizontal { overall_height: 10.0, spacing: 2.0, top_height: 4.0, bottom_y: 6.0, bottom_height: 4.0, }, // Odd height, even spacing Case::Horizontal { overall_height: 9.0, spacing: 2.0, top_height: 4.0, bottom_y: 6.0, bottom_height: 3.0, }, // Even height, odd spacing Case::Horizontal { overall_height: 10.0, spacing: 1.0, top_height: 5.0, bottom_y: 6.0, bottom_height: 4.0, }, // Odd height, odd spacing Case::Horizontal { overall_height: 9.0, spacing: 1.0, top_height: 4.0, bottom_y: 5.0, bottom_height: 4.0, }, // Even width, even spacing Case::Vertical { overall_width: 10.0, spacing: 2.0, left_width: 4.0, right_x: 6.0, right_width: 4.0, }, // Odd width, even spacing Case::Vertical { overall_width: 9.0, spacing: 2.0, left_width: 4.0, right_x: 6.0, right_width: 3.0, }, // Even width, odd spacing Case::Vertical { overall_width: 10.0, spacing: 1.0, left_width: 5.0, right_x: 6.0, right_width: 4.0, }, // Odd width, odd spacing Case::Vertical { overall_width: 9.0, spacing: 1.0, left_width: 4.0, right_x: 5.0, right_width: 4.0, }, ]; for case in cases { match case { Case::Horizontal { overall_height, spacing, top_height, bottom_y, bottom_height, } => { let a = Axis::Horizontal; let r = Rectangle { x: 0.0, y: 0.0, width: 10.0, height: overall_height, }; let (top, bottom, _ratio) = a.split(&r, 0.5, spacing, 0.0, 0.0); assert_eq!( top, Rectangle { height: top_height, ..r } ); assert_eq!( bottom, Rectangle { y: bottom_y, height: bottom_height, ..r } ); } Case::Vertical { overall_width, spacing, left_width, right_x, right_width, } => { let a = Axis::Vertical; let r = Rectangle { x: 0.0, y: 0.0, width: overall_width, height: 10.0, }; let (left, right, _ratio) = a.split(&r, 0.5, spacing, 0.0, 0.0); assert_eq!( left, Rectangle { width: left_width, ..r } ); assert_eq!( right, Rectangle { x: right_x, width: right_width, ..r } ); } } } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/direction.rs
widget/src/pane_grid/direction.rs
/// A four cardinal direction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Direction { /// ↑ Up, /// ↓ Down, /// ← Left, /// → Right, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/pane_grid/split.rs
widget/src/pane_grid/split.rs
/// A divider that splits a region in a [`PaneGrid`] into two different panes. /// /// [`PaneGrid`]: super::PaneGrid #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Split(pub(super) usize);
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/lazy/helpers.rs
widget/src/lazy/helpers.rs
use crate::core::{self, Element}; use crate::lazy::component; use std::hash::Hash; #[allow(deprecated)] pub use crate::lazy::{Component, Lazy}; /// Creates a new [`Lazy`] widget with the given data `Dependency` and a /// closure that can turn this data into a widget tree. #[cfg(feature = "lazy")] pub fn lazy<'a, Message, Theme, Renderer, Dependency, View>( dependency: Dependency, view: impl Fn(&Dependency) -> View + 'a, ) -> Lazy<'a, Message, Theme, Renderer, Dependency, View> where Dependency: Hash + 'a, View: Into<Element<'static, Message, Theme, Renderer>>, { Lazy::new(dependency, view) } /// Turns an implementor of [`Component`] into an [`Element`] that can be /// embedded in any application. #[cfg(feature = "lazy")] #[deprecated( since = "0.13.0", note = "components introduce encapsulated state and hamper the use of a single source of truth. \ Instead, leverage the Elm Architecture directly, or implement a custom widget" )] #[allow(deprecated)] pub fn component<'a, C, Message, Theme, Renderer>( component: C, ) -> Element<'a, Message, Theme, Renderer> where C: Component<Message, Theme, Renderer> + 'a, C::State: 'static, Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { component::view(component) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/lazy/cache.rs
widget/src/lazy/cache.rs
#![allow(dead_code)] use crate::core::Element; use crate::core::overlay; use ouroboros::self_referencing; #[self_referencing(pub_extras)] pub struct Cache<'a, Message: 'a, Theme: 'a, Renderer: 'a> { pub element: Element<'a, Message, Theme, Renderer>, #[borrows(mut element)] #[covariant] overlay: Option<overlay::Element<'this, Message, Theme, Renderer>>, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/lazy/component.rs
widget/src/lazy/component.rs
//! Build and reuse custom widgets using The Elm Architecture. #![allow(deprecated)] use crate::core::layout::{self, Layout}; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::{self, Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget}; use ouroboros::self_referencing; use std::cell::RefCell; use std::marker::PhantomData; use std::rc::Rc; /// A reusable, custom widget that uses The Elm Architecture. /// /// A [`Component`] allows you to implement custom widgets as if they were /// `iced` applications with encapsulated state. /// /// In other words, a [`Component`] allows you to turn `iced` applications into /// custom widgets and embed them without cumbersome wiring. /// /// A [`Component`] produces widgets that may fire an [`Event`](Component::Event) /// and update the internal state of the [`Component`]. /// /// Additionally, a [`Component`] is capable of producing a `Message` to notify /// the parent application of any relevant interactions. /// /// # State /// A component can store its state in one of two ways: either as data within the /// implementor of the trait, or in a type [`State`][Component::State] that is managed /// by the runtime and provided to the trait methods. These two approaches are not /// mutually exclusive and have opposite pros and cons. /// /// For instance, if a piece of state is needed by multiple components that reside /// in different branches of the tree, then it's more convenient to let a common /// ancestor store it and pass it down. /// /// On the other hand, if a piece of state is only needed by the component itself, /// you can store it as part of its internal [`State`][Component::State]. #[cfg(feature = "lazy")] #[deprecated( since = "0.13.0", note = "components introduce encapsulated state and hamper the use of a single source of truth. \ Instead, leverage the Elm Architecture directly, or implement a custom widget" )] pub trait Component<Message, Theme = crate::Theme, Renderer = crate::Renderer> { /// The internal state of this [`Component`]. type State: Default; /// The type of event this [`Component`] handles internally. type Event; /// Processes an [`Event`](Component::Event) and updates the [`Component`] state accordingly. /// /// It can produce a `Message` for the parent application. fn update(&mut self, state: &mut Self::State, event: Self::Event) -> Option<Message>; /// Produces the widgets of the [`Component`], which may trigger an [`Event`](Component::Event) /// on user interaction. fn view(&self, state: &Self::State) -> Element<'_, Self::Event, Theme, Renderer>; /// Update the [`Component`] state based on the provided [`Operation`](widget::Operation) /// /// By default, it does nothing. fn operate( &self, _bounds: Rectangle, _state: &mut Self::State, _operation: &mut dyn widget::Operation, ) { } /// Returns a [`Size`] hint for laying out the [`Component`]. /// /// This hint may be used by some widget containers to adjust their sizing strategy /// during construction. fn size_hint(&self) -> Size<Length> { Size { width: Length::Shrink, height: Length::Shrink, } } } struct Tag<T>(T); /// Turns an implementor of [`Component`] into an [`Element`] that can be /// embedded in any application. pub fn view<'a, C, Message, Theme, Renderer>(component: C) -> Element<'a, Message, Theme, Renderer> where C: Component<Message, Theme, Renderer> + 'a, C::State: 'static, Message: 'a, Theme: 'a, Renderer: core::Renderer + 'a, { Element::new(Instance { state: RefCell::new(Some( StateBuilder { component: Box::new(component), message: PhantomData, state: PhantomData, element_builder: |_| None, } .build(), )), tree: RefCell::new(Rc::new(RefCell::new(None))), }) } struct Instance<'a, Message, Theme, Renderer, Event, S> { state: RefCell<Option<State<'a, Message, Theme, Renderer, Event, S>>>, tree: RefCell<Rc<RefCell<Option<Tree>>>>, } #[self_referencing] struct State<'a, Message: 'a, Theme: 'a, Renderer: 'a, Event: 'a, S: 'a> { component: Box<dyn Component<Message, Theme, Renderer, Event = Event, State = S> + 'a>, message: PhantomData<Message>, state: PhantomData<S>, #[borrows(component)] #[covariant] element: Option<Element<'this, Event, Theme, Renderer>>, } impl<Message, Theme, Renderer, Event, S> Instance<'_, Message, Theme, Renderer, Event, S> where S: Default + 'static, Renderer: renderer::Renderer, { fn diff_self(&self) { self.with_element(|element| { self.tree .borrow_mut() .borrow_mut() .as_mut() .unwrap() .diff_children(std::slice::from_ref(&element)); }); } fn rebuild_element_if_necessary(&self) { let inner = self.state.borrow_mut().take().unwrap(); if inner.borrow_element().is_none() { let heads = inner.into_heads(); *self.state.borrow_mut() = Some( StateBuilder { component: heads.component, message: PhantomData, state: PhantomData, element_builder: |component| { Some( component.view( self.tree .borrow() .borrow() .as_ref() .unwrap() .state .downcast_ref::<S>(), ), ) }, } .build(), ); self.diff_self(); } else { *self.state.borrow_mut() = Some(inner); } } fn rebuild_element_with_operation( &self, layout: Layout<'_>, operation: &mut dyn widget::Operation, ) { let heads = self.state.borrow_mut().take().unwrap().into_heads(); heads.component.operate( layout.bounds(), self.tree .borrow_mut() .borrow_mut() .as_mut() .unwrap() .state .downcast_mut(), operation, ); *self.state.borrow_mut() = Some( StateBuilder { component: heads.component, message: PhantomData, state: PhantomData, element_builder: |component| { Some( component.view( self.tree .borrow() .borrow() .as_ref() .unwrap() .state .downcast_ref(), ), ) }, } .build(), ); self.diff_self(); } fn with_element<T>(&self, f: impl FnOnce(&Element<'_, Event, Theme, Renderer>) -> T) -> T { self.with_element_mut(|element| f(element)) } fn with_element_mut<T>( &self, f: impl FnOnce(&mut Element<'_, Event, Theme, Renderer>) -> T, ) -> T { self.rebuild_element_if_necessary(); self.state .borrow_mut() .as_mut() .unwrap() .with_element_mut(|element| f(element.as_mut().unwrap())) } } impl<Message, Theme, Renderer, Event, S> Widget<Message, Theme, Renderer> for Instance<'_, Message, Theme, Renderer, Event, S> where S: 'static + Default, Renderer: core::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<Tag<S>>() } fn state(&self) -> tree::State { let state = Rc::new(RefCell::new(Some(Tree { tag: tree::Tag::of::<Tag<S>>(), state: tree::State::new(S::default()), children: vec![Tree::empty()], }))); *self.tree.borrow_mut() = state.clone(); self.diff_self(); tree::State::new(state) } fn children(&self) -> Vec<Tree> { vec![] } fn diff(&self, tree: &mut Tree) { let tree = tree.state.downcast_ref::<Rc<RefCell<Option<Tree>>>>(); *self.tree.borrow_mut() = tree.clone(); self.rebuild_element_if_necessary(); } fn size(&self) -> Size<Length> { self.with_element(|element| element.as_widget().size()) } fn size_hint(&self) -> Size<Length> { self.state .borrow() .as_ref() .expect("Borrow instance state") .borrow_component() .size_hint() } fn layout( &mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { let t = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>(); self.with_element_mut(|element| { element.as_widget_mut().layout( &mut t.borrow_mut().as_mut().unwrap().children[0], renderer, limits, ) }) } fn update( &mut self, tree: &mut Tree, event: &core::Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); let t = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>(); self.with_element_mut(|element| { element.as_widget_mut().update( &mut t.borrow_mut().as_mut().unwrap().children[0], event, layout, cursor, renderer, clipboard, &mut local_shell, viewport, ); }); if local_shell.is_event_captured() { shell.capture_event(); } local_shell.revalidate_layout(|| shell.invalidate_layout()); shell.request_redraw_at(local_shell.redraw_request()); shell.request_input_method(local_shell.input_method()); if !local_messages.is_empty() { let mut heads = self.state.take().unwrap().into_heads(); for message in local_messages.into_iter().filter_map(|message| { heads.component.update( t.borrow_mut().as_mut().unwrap().state.downcast_mut(), message, ) }) { shell.publish(message); } self.state = RefCell::new(Some( StateBuilder { component: heads.component, message: PhantomData, state: PhantomData, element_builder: |_| None, } .build(), )); shell.invalidate_layout(); shell.request_redraw(); } } fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn widget::Operation, ) { self.rebuild_element_with_operation(layout, operation); let tree = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>(); self.with_element_mut(|element| { element.as_widget_mut().operate( &mut tree.borrow_mut().as_mut().unwrap().children[0], layout, renderer, operation, ); }); } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { let tree = tree.state.downcast_ref::<Rc<RefCell<Option<Tree>>>>(); self.with_element(|element| { element.as_widget().draw( &tree.borrow().as_ref().unwrap().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 { let tree = tree.state.downcast_ref::<Rc<RefCell<Option<Tree>>>>(); self.with_element(|element| { element.as_widget().mouse_interaction( &tree.borrow().as_ref().unwrap().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>> { self.rebuild_element_if_necessary(); let state = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>(); let tree = state.borrow_mut().take().unwrap(); let overlay = InnerBuilder { instance: self, tree, types: PhantomData, overlay_builder: |instance, tree| { instance .state .get_mut() .as_mut() .unwrap() .with_element_mut(move |element| { element .as_mut() .unwrap() .as_widget_mut() .overlay( &mut tree.children[0], layout, renderer, viewport, translation, ) .map(|overlay| RefCell::new(overlay::Nested::new(overlay))) }) }, } .build(); #[allow(clippy::redundant_closure_for_method_calls)] if overlay.with_overlay(|overlay| overlay.is_some()) { Some(overlay::Element::new(Box::new(OverlayInstance { overlay: Some(Overlay(Some(overlay))), // Beautiful, I know }))) } else { let heads = overlay.into_heads(); // - You may not like it, but this is what peak performance looks like // - TODO: Get rid of ouroboros, for good // - What?! *state.borrow_mut() = Some(heads.tree); None } } } struct Overlay<'a, 'b, Message, Theme, Renderer, Event, S>( Option<Inner<'a, 'b, Message, Theme, Renderer, Event, S>>, ); impl<Message, Theme, Renderer, Event, S> Drop for Overlay<'_, '_, Message, Theme, Renderer, Event, S> { fn drop(&mut self) { if let Some(heads) = self.0.take().map(Inner::into_heads) { *heads.instance.tree.borrow_mut().borrow_mut() = Some(heads.tree); } } } #[self_referencing] struct Inner<'a, 'b, Message, Theme, Renderer, Event, S> { instance: &'a mut Instance<'b, Message, Theme, Renderer, Event, S>, tree: Tree, types: PhantomData<(Message, Event, S)>, #[borrows(mut instance, mut tree)] #[not_covariant] overlay: Option<RefCell<overlay::Nested<'this, Event, Theme, Renderer>>>, } struct OverlayInstance<'a, 'b, Message, Theme, Renderer, Event, S> { overlay: Option<Overlay<'a, 'b, Message, Theme, Renderer, Event, S>>, } impl<Message, Theme, Renderer, Event, S> OverlayInstance<'_, '_, Message, Theme, Renderer, Event, S> { fn with_overlay_maybe<T>( &self, f: impl FnOnce(&mut overlay::Nested<'_, Event, Theme, Renderer>) -> T, ) -> Option<T> { self.overlay .as_ref() .unwrap() .0 .as_ref() .unwrap() .with_overlay(|overlay| overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut()))) } fn with_overlay_mut_maybe<T>( &mut self, f: impl FnOnce(&mut overlay::Nested<'_, Event, Theme, Renderer>) -> T, ) -> Option<T> { self.overlay .as_mut() .unwrap() .0 .as_mut() .unwrap() .with_overlay_mut(|overlay| overlay.as_mut().map(|nested| (f)(nested.get_mut()))) } } impl<Message, Theme, Renderer, Event, S> overlay::Overlay<Message, Theme, Renderer> for OverlayInstance<'_, '_, Message, Theme, Renderer, Event, S> where Renderer: core::Renderer, S: 'static + Default, { fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { self.with_overlay_maybe(|overlay| overlay.layout(renderer, bounds)) .unwrap_or_default() } fn draw( &self, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, ) { let _ = self.with_overlay_maybe(|overlay| { overlay.draw(renderer, theme, style, layout, cursor); }); } fn mouse_interaction( &self, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { self.with_overlay_maybe(|overlay| overlay.mouse_interaction(layout, cursor, renderer)) .unwrap_or_default() } fn update( &mut self, event: &core::Event, layout: Layout<'_>, cursor: mouse::Cursor, renderer: &Renderer, clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) { let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); let _ = self.with_overlay_mut_maybe(|overlay| { overlay.update(event, layout, cursor, renderer, clipboard, &mut local_shell); }); if local_shell.is_event_captured() { shell.capture_event(); } local_shell.revalidate_layout(|| shell.invalidate_layout()); shell.request_redraw_at(local_shell.redraw_request()); shell.request_input_method(local_shell.input_method()); if !local_messages.is_empty() { let mut inner = self.overlay.take().unwrap().0.take().unwrap().into_heads(); let mut heads = inner.instance.state.take().unwrap().into_heads(); for message in local_messages.into_iter().filter_map(|message| { heads .component .update(inner.tree.state.downcast_mut(), message) }) { shell.publish(message); } *inner.instance.state.borrow_mut() = Some( StateBuilder { component: heads.component, message: PhantomData, state: PhantomData, element_builder: |_| None, } .build(), ); self.overlay = Some(Overlay(Some( InnerBuilder { instance: inner.instance, tree: inner.tree, types: PhantomData, overlay_builder: |_, _| None, } .build(), ))); shell.invalidate_layout(); } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/shader/program.rs
widget/src/shader/program.rs
use crate::core::Rectangle; use crate::core::mouse; use crate::renderer::wgpu::Primitive; use crate::shader::{self, Action}; /// The state and logic of a [`Shader`] widget. /// /// A [`Program`] can mutate the internal state of a [`Shader`] widget /// and produce messages for an application. /// /// [`Shader`]: crate::Shader pub trait Program<Message> { /// The internal state of the [`Program`]. type State: Default + 'static; /// The type of primitive this [`Program`] can draw. type Primitive: Primitive + 'static; /// Update the internal [`State`] of the [`Program`]. This can be used to reflect state changes /// based on mouse & other events. You can return an [`Action`] to publish a message, request a /// redraw, or capture the event. /// /// By default, this method returns `None`. /// /// [`State`]: Self::State fn update( &self, _state: &mut Self::State, _event: &shader::Event, _bounds: Rectangle, _cursor: mouse::Cursor, ) -> Option<Action<Message>> { None } /// Draws the [`Primitive`]. /// /// [`Primitive`]: Self::Primitive fn draw( &self, state: &Self::State, cursor: mouse::Cursor, bounds: Rectangle, ) -> Self::Primitive; /// Returns the current mouse interaction of the [`Program`]. /// /// The interaction returned will be in effect even if the cursor position is out of /// bounds of the [`Shader`]'s program. /// /// [`Shader`]: crate::Shader fn mouse_interaction( &self, _state: &Self::State, _bounds: Rectangle, _cursor: mouse::Cursor, ) -> mouse::Interaction { mouse::Interaction::default() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text_input/cursor.rs
widget/src/text_input/cursor.rs
//! Track the cursor of a text input. use crate::text_input::Value; /// The cursor of a text input. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Cursor { state: State, } /// The state of a [`Cursor`]. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum State { /// Cursor without a selection Index(usize), /// Cursor selecting a range of text Selection { /// The start of the selection start: usize, /// The end of the selection end: usize, }, } impl Default for Cursor { fn default() -> Self { Cursor { state: State::Index(0), } } } impl Cursor { /// Returns the [`State`] of the [`Cursor`]. pub fn state(&self, value: &Value) -> State { match self.state { State::Index(index) => State::Index(index.min(value.len())), State::Selection { start, end } => { let start = start.min(value.len()); let end = end.min(value.len()); if start == end { State::Index(start) } else { State::Selection { start, end } } } } } /// Returns the current selection of the [`Cursor`] for the given [`Value`]. /// /// `start` is guaranteed to be <= than `end`. pub fn selection(&self, value: &Value) -> Option<(usize, usize)> { match self.state(value) { State::Selection { start, end } => Some((start.min(end), start.max(end))), State::Index(_) => None, } } pub(crate) fn move_to(&mut self, position: usize) { self.state = State::Index(position); } pub(crate) fn move_right(&mut self, value: &Value) { self.move_right_by_amount(value, 1); } pub(crate) fn move_right_by_words(&mut self, value: &Value) { self.move_to(value.next_end_of_word(self.right(value))); } pub(crate) fn move_right_by_amount(&mut self, value: &Value, amount: usize) { match self.state(value) { State::Index(index) => { self.move_to(index.saturating_add(amount).min(value.len())); } State::Selection { start, end } => self.move_to(end.max(start)), } } pub(crate) fn move_left(&mut self, value: &Value) { match self.state(value) { State::Index(index) if index > 0 => self.move_to(index - 1), State::Selection { start, end } => self.move_to(start.min(end)), State::Index(_) => self.move_to(0), } } pub(crate) fn move_left_by_words(&mut self, value: &Value) { self.move_to(value.previous_start_of_word(self.left(value))); } pub(crate) fn select_range(&mut self, start: usize, end: usize) { if start == end { self.state = State::Index(start); } else { self.state = State::Selection { start, end }; } } pub(crate) fn select_left(&mut self, value: &Value) { match self.state(value) { State::Index(index) if index > 0 => { self.select_range(index, index - 1); } State::Selection { start, end } if end > 0 => { self.select_range(start, end - 1); } _ => {} } } pub(crate) fn select_right(&mut self, value: &Value) { match self.state(value) { State::Index(index) if index < value.len() => { self.select_range(index, index + 1); } State::Selection { start, end } if end < value.len() => { self.select_range(start, end + 1); } _ => {} } } pub(crate) fn select_left_by_words(&mut self, value: &Value) { match self.state(value) { State::Index(index) => { self.select_range(index, value.previous_start_of_word(index)); } State::Selection { start, end } => { self.select_range(start, value.previous_start_of_word(end)); } } } pub(crate) fn select_right_by_words(&mut self, value: &Value) { match self.state(value) { State::Index(index) => { self.select_range(index, value.next_end_of_word(index)); } State::Selection { start, end } => { self.select_range(start, value.next_end_of_word(end)); } } } pub(crate) fn select_all(&mut self, value: &Value) { self.select_range(0, value.len()); } pub(crate) fn start(&self, value: &Value) -> usize { let start = match self.state { State::Index(index) => index, State::Selection { start, .. } => start, }; start.min(value.len()) } pub(crate) fn end(&self, value: &Value) -> usize { let end = match self.state { State::Index(index) => index, State::Selection { end, .. } => end, }; end.min(value.len()) } fn left(&self, value: &Value) -> usize { match self.state(value) { State::Index(index) => index, State::Selection { start, end } => start.min(end), } } fn right(&self, value: &Value) -> usize { match self.state(value) { State::Index(index) => index, State::Selection { start, end } => start.max(end), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text_input/editor.rs
widget/src/text_input/editor.rs
use crate::text_input::{Cursor, Value}; pub struct Editor<'a> { value: &'a mut Value, cursor: &'a mut Cursor, } impl<'a> Editor<'a> { pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> { Editor { value, cursor } } pub fn contents(&self) -> String { self.value.to_string() } pub fn insert(&mut self, character: char) { if let Some((left, right)) = self.cursor.selection(self.value) { self.cursor.move_left(self.value); self.value.remove_many(left, right); } self.value.insert(self.cursor.end(self.value), character); self.cursor.move_right(self.value); } pub fn paste(&mut self, content: Value) { let length = content.len(); if let Some((left, right)) = self.cursor.selection(self.value) { self.cursor.move_left(self.value); self.value.remove_many(left, right); } self.value.insert_many(self.cursor.end(self.value), content); self.cursor.move_right_by_amount(self.value, length); } pub fn backspace(&mut self) { match self.cursor.selection(self.value) { Some((start, end)) => { self.cursor.move_left(self.value); self.value.remove_many(start, end); } None => { let start = self.cursor.start(self.value); if start > 0 { self.cursor.move_left(self.value); self.value.remove(start - 1); } } } } pub fn delete(&mut self) { match self.cursor.selection(self.value) { Some(_) => { self.backspace(); } None => { let end = self.cursor.end(self.value); if end < self.value.len() { self.value.remove(end); } } } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text_input/value.rs
widget/src/text_input/value.rs
use unicode_segmentation::UnicodeSegmentation; /// The value of a [`TextInput`]. /// /// [`TextInput`]: super::TextInput // TODO: Reduce allocations, cache results (?) #[derive(Debug, Clone)] pub struct Value { graphemes: Vec<String>, } impl Value { /// Creates a new [`Value`] from a string slice. pub fn new(string: &str) -> Self { let graphemes = UnicodeSegmentation::graphemes(string, true) .map(String::from) .collect(); Self { graphemes } } /// Returns whether the [`Value`] is empty or not. /// /// A [`Value`] is empty when it contains no graphemes. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the total amount of graphemes in the [`Value`]. pub fn len(&self) -> usize { self.graphemes.len() } /// Returns the position of the previous start of a word from the given /// grapheme `index`. pub fn previous_start_of_word(&self, index: usize) -> usize { let previous_string = &self.graphemes[..index.min(self.graphemes.len())].concat(); UnicodeSegmentation::split_word_bound_indices(previous_string as &str) .rfind(|(_, word)| !word.trim_start().is_empty()) .map(|(i, previous_word)| { index - UnicodeSegmentation::graphemes(previous_word, true).count() - UnicodeSegmentation::graphemes( &previous_string[i + previous_word.len()..] as &str, true, ) .count() }) .unwrap_or(0) } /// Returns the position of the next end of a word from the given grapheme /// `index`. pub fn next_end_of_word(&self, index: usize) -> usize { let next_string = &self.graphemes[index..].concat(); UnicodeSegmentation::split_word_bound_indices(next_string as &str) .find(|(_, word)| !word.trim_start().is_empty()) .map(|(i, next_word)| { index + UnicodeSegmentation::graphemes(next_word, true).count() + UnicodeSegmentation::graphemes(&next_string[..i] as &str, true).count() }) .unwrap_or(self.len()) } /// Returns a new [`Value`] containing the graphemes from `start` until the /// given `end`. pub fn select(&self, start: usize, end: usize) -> Self { let graphemes = self.graphemes[start.min(self.len())..end.min(self.len())].to_vec(); Self { graphemes } } /// Returns a new [`Value`] containing the graphemes until the given /// `index`. pub fn until(&self, index: usize) -> Self { let graphemes = self.graphemes[..index.min(self.len())].to_vec(); Self { graphemes } } /// Inserts a new `char` at the given grapheme `index`. pub fn insert(&mut self, index: usize, c: char) { self.graphemes.insert(index, c.to_string()); self.graphemes = UnicodeSegmentation::graphemes(&self.to_string() as &str, true) .map(String::from) .collect(); } /// Inserts a bunch of graphemes at the given grapheme `index`. pub fn insert_many(&mut self, index: usize, mut value: Value) { let _ = self .graphemes .splice(index..index, value.graphemes.drain(..)); } /// Removes the grapheme at the given `index`. pub fn remove(&mut self, index: usize) { let _ = self.graphemes.remove(index); } /// Removes the graphemes from `start` to `end`. pub fn remove_many(&mut self, start: usize, end: usize) { let _ = self.graphemes.splice(start..end, std::iter::empty()); } /// Returns a new [`Value`] with all its graphemes replaced with the /// dot ('•') character. pub fn secure(&self) -> Self { Self { graphemes: std::iter::repeat_n(String::from("•"), self.graphemes.len()).collect(), } } } impl std::fmt::Display for Value { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.graphemes.concat()) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/canvas/program.rs
widget/src/canvas/program.rs
use crate::Action; use crate::canvas::mouse; use crate::canvas::{Event, Geometry}; use crate::core::Rectangle; use crate::graphics::geometry; /// The state and logic of a [`Canvas`]. /// /// A [`Program`] can mutate internal state and produce messages for an /// application. /// /// [`Canvas`]: crate::Canvas pub trait Program<Message, Theme = crate::Theme, Renderer = crate::Renderer> where Renderer: geometry::Renderer, { /// The internal state mutated by the [`Program`]. type State: Default + 'static; /// Updates the [`State`](Self::State) of the [`Program`]. /// /// When a [`Program`] is used in a [`Canvas`], the runtime will call this /// method for each [`Event`]. /// /// This method can optionally return an [`Action`] to either notify an /// application of any meaningful interactions, capture the event, or /// request a redraw. /// /// By default, this method does and returns nothing. /// /// [`Canvas`]: crate::Canvas fn update( &self, _state: &mut Self::State, _event: &Event, _bounds: Rectangle, _cursor: mouse::Cursor, ) -> Option<Action<Message>> { None } /// Draws the state of the [`Program`], producing a bunch of [`Geometry`]. /// /// [`Geometry`] can be easily generated with a [`Frame`] or stored in a /// [`Cache`]. /// /// [`Geometry`]: crate::canvas::Geometry /// [`Frame`]: crate::canvas::Frame /// [`Cache`]: crate::canvas::Cache fn draw( &self, state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec<Geometry<Renderer>>; /// Returns the current mouse interaction of the [`Program`]. /// /// The interaction returned will be in effect even if the cursor position /// is out of bounds of the program's [`Canvas`]. /// /// [`Canvas`]: crate::Canvas fn mouse_interaction( &self, _state: &Self::State, _bounds: Rectangle, _cursor: mouse::Cursor, ) -> mouse::Interaction { mouse::Interaction::default() } } impl<Message, Theme, Renderer, T> Program<Message, Theme, Renderer> for &T where Renderer: geometry::Renderer, T: Program<Message, Theme, Renderer>, { type State = T::State; fn update( &self, state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: mouse::Cursor, ) -> Option<Action<Message>> { T::update(self, state, event, bounds, cursor) } fn draw( &self, state: &Self::State, renderer: &Renderer, theme: &Theme, bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec<Geometry<Renderer>> { T::draw(self, state, renderer, theme, bounds, cursor) } fn mouse_interaction( &self, state: &Self::State, bounds: Rectangle, cursor: mouse::Cursor, ) -> mouse::Interaction { T::mouse_interaction(self, state, bounds, cursor) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/text/rich.rs
widget/src/text/rich.rs
use crate::core::alignment; use crate::core::layout; use crate::core::mouse; use crate::core::renderer; use crate::core::text::{Paragraph, Span}; use crate::core::widget::text::{ self, Alignment, Catalog, LineHeight, Shaping, Style, StyleFn, Wrapping, }; use crate::core::widget::tree::{self, Tree}; use crate::core::{ self, Clipboard, Color, Element, Event, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Vector, Widget, }; /// A bunch of [`Rich`] text. pub struct Rich<'a, Link, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Link: Clone + 'static, Theme: Catalog, Renderer: core::text::Renderer, { spans: Box<dyn AsRef<[Span<'a, Link, Renderer::Font>]> + 'a>, size: Option<Pixels>, line_height: LineHeight, width: Length, height: Length, font: Option<Renderer::Font>, align_x: Alignment, align_y: alignment::Vertical, wrapping: Wrapping, class: Theme::Class<'a>, hovered_link: Option<usize>, on_link_click: Option<Box<dyn Fn(Link) -> Message + 'a>>, } impl<'a, Link, Message, Theme, Renderer> Rich<'a, Link, Message, Theme, Renderer> where Link: Clone + 'static, Theme: Catalog, Renderer: core::text::Renderer, Renderer::Font: 'a, { /// Creates a new empty [`Rich`] text. pub fn new() -> Self { Self { spans: Box::new([]), size: None, line_height: LineHeight::default(), width: Length::Shrink, height: Length::Shrink, font: None, align_x: Alignment::Default, align_y: alignment::Vertical::Top, wrapping: Wrapping::default(), class: Theme::default(), hovered_link: None, on_link_click: None, } } /// Creates a new [`Rich`] text with the given text spans. pub fn with_spans(spans: impl AsRef<[Span<'a, Link, Renderer::Font>]> + 'a) -> Self { Self { spans: Box::new(spans), ..Self::new() } } /// Sets the default size of the [`Rich`] text. pub fn size(mut self, size: impl Into<Pixels>) -> Self { self.size = Some(size.into()); self } /// Sets the default [`LineHeight`] of the [`Rich`] text. pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self { self.line_height = line_height.into(); self } /// Sets the default font of the [`Rich`] text. pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self { self.font = Some(font.into()); self } /// Sets the width of the [`Rich`] text boundaries. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Rich`] text boundaries. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Centers the [`Rich`] text, both horizontally and vertically. pub fn center(self) -> Self { self.align_x(alignment::Horizontal::Center) .align_y(alignment::Vertical::Center) } /// Sets the [`alignment::Horizontal`] of the [`Rich`] text. pub fn align_x(mut self, alignment: impl Into<Alignment>) -> Self { self.align_x = alignment.into(); self } /// Sets the [`alignment::Vertical`] of the [`Rich`] text. pub fn align_y(mut self, alignment: impl Into<alignment::Vertical>) -> Self { self.align_y = alignment.into(); self } /// Sets the [`Wrapping`] strategy of the [`Rich`] text. pub fn wrapping(mut self, wrapping: Wrapping) -> Self { self.wrapping = wrapping; self } /// Sets the message that will be produced when a link of the [`Rich`] text /// is clicked. /// /// If the spans of the [`Rich`] text contain no links, you may need to call /// this method with `on_link_click(never)` in order for the compiler to infer /// the proper `Link` generic type. pub fn on_link_click(mut self, on_link_click: impl Fn(Link) -> Message + 'a) -> Self { self.on_link_click = Some(Box::new(on_link_click)); self } /// Sets the default style of the [`Rich`] text. #[must_use] pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); self } /// Sets the default [`Color`] of the [`Rich`] text. pub fn color(self, color: impl Into<Color>) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { self.color_maybe(Some(color)) } /// Sets the default [`Color`] of the [`Rich`] text, if `Some`. pub fn color_maybe(self, color: Option<impl Into<Color>>) -> Self where Theme::Class<'a>: From<StyleFn<'a, Theme>>, { let color = color.map(Into::into); self.style(move |_theme| Style { color }) } /// Sets the default style class of the [`Rich`] text. #[cfg(feature = "advanced")] #[must_use] pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self { self.class = class.into(); self } } impl<'a, Link, Message, Theme, Renderer> Default for Rich<'a, Link, Message, Theme, Renderer> where Link: Clone + 'a, Theme: Catalog, Renderer: core::text::Renderer, Renderer::Font: 'a, { fn default() -> Self { Self::new() } } struct State<Link, P: Paragraph> { spans: Vec<Span<'static, Link, P::Font>>, span_pressed: Option<usize>, paragraph: P, } impl<Link, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Rich<'_, Link, Message, Theme, Renderer> where Link: Clone + 'static, Theme: Catalog, Renderer: core::text::Renderer, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Link, Renderer::Paragraph>>() } fn state(&self) -> tree::State { tree::State::new(State::<Link, _> { spans: Vec::new(), span_pressed: None, paragraph: Renderer::Paragraph::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( tree.state .downcast_mut::<State<Link, Renderer::Paragraph>>(), renderer, limits, self.width, self.height, self.spans.as_ref().as_ref(), self.line_height, self.size, self.font, self.align_x, self.align_y, self.wrapping, ) } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, defaults: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, viewport: &Rectangle, ) { if !layout.bounds().intersects(viewport) { return; } let state = tree .state .downcast_ref::<State<Link, Renderer::Paragraph>>(); let style = theme.style(&self.class); for (index, span) in self.spans.as_ref().as_ref().iter().enumerate() { let is_hovered_link = self.on_link_click.is_some() && Some(index) == self.hovered_link; if span.highlight.is_some() || span.underline || span.strikethrough || is_hovered_link { let translation = layout.position() - Point::ORIGIN; let regions = state.paragraph.span_bounds(index); if let Some(highlight) = span.highlight { for bounds in &regions { let bounds = Rectangle::new( bounds.position() - Vector::new(span.padding.left, span.padding.top), bounds.size() + Size::new(span.padding.x(), span.padding.y()), ); renderer.fill_quad( renderer::Quad { bounds: bounds + translation, border: highlight.border, ..Default::default() }, highlight.background, ); } } if span.underline || span.strikethrough || is_hovered_link { let size = span.size.or(self.size).unwrap_or(renderer.default_size()); let line_height = span .line_height .unwrap_or(self.line_height) .to_absolute(size); let color = span.color.or(style.color).unwrap_or(defaults.text_color); let baseline = translation + Vector::new(0.0, size.0 + (line_height.0 - size.0) / 2.0); if span.underline || is_hovered_link { for bounds in &regions { renderer.fill_quad( renderer::Quad { bounds: Rectangle::new( bounds.position() + baseline - Vector::new(0.0, size.0 * 0.08), Size::new(bounds.width, 1.0), ), ..Default::default() }, color, ); } } if span.strikethrough { for bounds in &regions { renderer.fill_quad( renderer::Quad { bounds: Rectangle::new( bounds.position() + baseline - Vector::new(0.0, size.0 / 2.0), Size::new(bounds.width, 1.0), ), ..Default::default() }, color, ); } } } } } text::draw( renderer, defaults, layout.bounds(), &state.paragraph, style, viewport, ); } 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 Some(on_link_clicked) = &self.on_link_click else { return; }; let was_hovered = self.hovered_link.is_some(); if let Some(position) = cursor.position_in(layout.bounds()) { let state = tree .state .downcast_ref::<State<Link, Renderer::Paragraph>>(); self.hovered_link = state.paragraph.hit_span(position).and_then(|span| { if self.spans.as_ref().as_ref().get(span)?.link.is_some() { Some(span) } else { None } }); } else { self.hovered_link = None; } if was_hovered != self.hovered_link.is_some() { shell.request_redraw(); } match event { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { let state = tree .state .downcast_mut::<State<Link, Renderer::Paragraph>>(); if self.hovered_link.is_some() { state.span_pressed = self.hovered_link; shell.capture_event(); } } Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => { let state = tree .state .downcast_mut::<State<Link, Renderer::Paragraph>>(); match state.span_pressed { Some(span) if Some(span) == self.hovered_link => { if let Some(link) = self .spans .as_ref() .as_ref() .get(span) .and_then(|span| span.link.clone()) { shell.publish(on_link_clicked(link)); } } _ => {} } state.span_pressed = None; } _ => {} } } fn mouse_interaction( &self, _tree: &Tree, _layout: Layout<'_>, _cursor: mouse::Cursor, _viewport: &Rectangle, _renderer: &Renderer, ) -> mouse::Interaction { if self.hovered_link.is_some() { mouse::Interaction::Pointer } else { mouse::Interaction::None } } } fn layout<Link, Renderer>( state: &mut State<Link, Renderer::Paragraph>, renderer: &Renderer, limits: &layout::Limits, width: Length, height: Length, spans: &[Span<'_, Link, Renderer::Font>], line_height: LineHeight, size: Option<Pixels>, font: Option<Renderer::Font>, align_x: Alignment, align_y: alignment::Vertical, wrapping: Wrapping, ) -> layout::Node where Link: Clone, Renderer: core::text::Renderer, { layout::sized(limits, width, height, |limits| { let bounds = limits.max(); let size = size.unwrap_or_else(|| renderer.default_size()); let font = font.unwrap_or_else(|| renderer.default_font()); let text_with_spans = || core::Text { content: spans, bounds, size, line_height, font, align_x, align_y, shaping: Shaping::Advanced, wrapping, hint_factor: renderer.scale_factor(), }; if state.spans != spans { state.paragraph = Renderer::Paragraph::with_spans(text_with_spans()); state.spans = spans.iter().cloned().map(Span::to_static).collect(); } else { match state.paragraph.compare(core::Text { content: (), bounds, size, line_height, font, align_x, align_y, shaping: Shaping::Advanced, wrapping, hint_factor: renderer.scale_factor(), }) { core::text::Difference::None => {} core::text::Difference::Bounds => { state.paragraph.resize(bounds); } core::text::Difference::Shape => { state.paragraph = Renderer::Paragraph::with_spans(text_with_spans()); } } } state.paragraph.min_bounds() }) } impl<'a, Link, Message, Theme, Renderer> FromIterator<Span<'a, Link, Renderer::Font>> for Rich<'a, Link, Message, Theme, Renderer> where Link: Clone + 'a, Theme: Catalog, Renderer: core::text::Renderer, Renderer::Font: 'a, { fn from_iter<T: IntoIterator<Item = Span<'a, Link, Renderer::Font>>>(spans: T) -> Self { Self::with_spans(spans.into_iter().collect::<Vec<_>>()) } } impl<'a, Link, Message, Theme, Renderer> From<Rich<'a, Link, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Message: 'a, Link: Clone + 'a, Theme: Catalog + 'a, Renderer: core::text::Renderer + 'a, { fn from( text: Rich<'a, Link, Message, Theme, Renderer>, ) -> Element<'a, Message, Theme, Renderer> { Element::new(text) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/widget/src/keyed/column.rs
widget/src/keyed/column.rs
//! Keyed columns distribute content vertically while keeping continuity. use crate::core::layout; use crate::core::mouse; use crate::core::overlay; use crate::core::renderer; use crate::core::widget::Operation; use crate::core::widget::tree::{self, Tree}; use crate::core::{ Alignment, Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents vertically while keeping continuity. /// /// # Example /// ```no_run /// # mod iced { pub mod widget { pub use iced_widget::*; } } /// # pub type State = (); /// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; /// use iced::widget::{keyed_column, text}; /// /// enum Message { /// // ... /// } /// /// fn view(state: &State) -> Element<'_, Message> { /// keyed_column((0..=100).map(|i| { /// (i, text!("Item {i}").into()) /// })).into() /// } /// ``` pub struct Column<'a, Key, Message, Theme = crate::Theme, Renderer = crate::Renderer> where Key: Copy + PartialEq, { spacing: f32, padding: Padding, width: Length, height: Length, max_width: f32, align_items: Alignment, keys: Vec<Key>, children: Vec<Element<'a, Message, Theme, Renderer>>, } impl<'a, Key, Message, Theme, Renderer> Column<'a, Key, Message, Theme, Renderer> where Key: Copy + PartialEq, Renderer: crate::core::Renderer, { /// Creates an empty [`Column`]. pub fn new() -> Self { Self::from_vecs(Vec::new(), Vec::new()) } /// Creates a [`Column`] from already allocated [`Vec`]s. /// /// Keep in mind that the [`Column`] will not inspect the [`Vec`]s, which means /// it won't automatically adapt to the sizing strategy of its contents. /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Column::width`] or [`Column::height`] accordingly. pub fn from_vecs(keys: Vec<Key>, children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, width: Length::Shrink, height: Length::Shrink, max_width: f32::INFINITY, align_items: Alignment::Start, keys, children, } } /// Creates a [`Column`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { Self::from_vecs(Vec::with_capacity(capacity), Vec::with_capacity(capacity)) } /// Creates a [`Column`] with the given elements. pub fn with_children( children: impl IntoIterator<Item = (Key, Element<'a, Message, Theme, Renderer>)>, ) -> Self { let iterator = children.into_iter(); Self::with_capacity(iterator.size_hint().0).extend(iterator) } /// Sets the vertical spacing _between_ elements. /// /// Custom margins per element do not exist in iced. You should use this /// method instead! While less flexible, it helps you keep spacing between /// elements consistent. pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self { self.spacing = amount.into().0; self } /// Sets the [`Padding`] of the [`Column`]. pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self { self.padding = padding.into(); self } /// Sets the width of the [`Column`]. pub fn width(mut self, width: impl Into<Length>) -> Self { self.width = width.into(); self } /// Sets the height of the [`Column`]. pub fn height(mut self, height: impl Into<Length>) -> Self { self.height = height.into(); self } /// Sets the maximum width of the [`Column`]. pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self { self.max_width = max_width.into().0; self } /// Sets the horizontal alignment of the contents of the [`Column`] . pub fn align_items(mut self, align: Alignment) -> Self { self.align_items = align; self } /// Adds an element to the [`Column`]. pub fn push( mut self, key: Key, child: impl Into<Element<'a, Message, Theme, Renderer>>, ) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); self.width = self.width.enclose(child_size.width); self.height = self.height.enclose(child_size.height); self.keys.push(key); self.children.push(child); self } /// Adds an element to the [`Column`], if `Some`. pub fn push_maybe( self, key: Key, child: Option<impl Into<Element<'a, Message, Theme, Renderer>>>, ) -> Self { if let Some(child) = child { self.push(key, child) } else { self } } /// Extends the [`Column`] with the given children. pub fn extend( self, children: impl IntoIterator<Item = (Key, Element<'a, Message, Theme, Renderer>)>, ) -> Self { children .into_iter() .fold(self, |column, (key, child)| column.push(key, child)) } } impl<Key, Message, Renderer> Default for Column<'_, Key, Message, Renderer> where Key: Copy + PartialEq, Renderer: crate::core::Renderer, { fn default() -> Self { Self::new() } } struct State<Key> where Key: Copy + PartialEq, { keys: Vec<Key>, } impl<Key, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Column<'_, Key, Message, Theme, Renderer> where Renderer: crate::core::Renderer, Key: Copy + PartialEq + 'static, { fn tag(&self) -> tree::Tag { tree::Tag::of::<State<Key>>() } fn state(&self) -> tree::State { tree::State::new(State { keys: self.keys.clone(), }) } fn children(&self) -> Vec<Tree> { self.children.iter().map(Tree::new).collect() } fn diff(&self, tree: &mut Tree) { let Tree { state, children, .. } = tree; let state = state.downcast_mut::<State<Key>>(); tree::diff_children_custom_with_search( children, &self.children, |tree, child| child.as_widget().diff(tree), |index| { self.keys.get(index).or_else(|| self.keys.last()).copied() != Some(state.keys[index]) }, |child| Tree::new(child.as_widget()), ); if state.keys != self.keys { state.keys.clone_from(&self.keys); } } 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 { let limits = limits .max_width(self.max_width) .width(self.width) .height(self.height); layout::flex::resolve( layout::flex::Axis::Vertical, renderer, &limits, self.width, self.height, self.padding, self.spacing, self.align_items, &mut self.children, &mut tree.children, ) } 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.children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), layout)| { child .as_widget_mut() .operate(state, 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, ) { for ((child, tree), layout) in self .children .iter_mut() .zip(&mut tree.children) .zip(layout.children()) { child.as_widget_mut().update( tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { self.children .iter() .zip(&tree.children) .zip(layout.children()) .map(|((child, tree), layout)| { child .as_widget() .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() } fn draw( &self, tree: &Tree, renderer: &mut Renderer, theme: &Theme, style: &renderer::Style, layout: Layout<'_>, cursor: mouse::Cursor, viewport: &Rectangle, ) { for ((child, state), layout) in self .children .iter() .zip(&tree.children) .zip(layout.children()) { child .as_widget() .draw(state, renderer, theme, style, layout, cursor, viewport); } } 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>> { overlay::from_children( &mut self.children, tree, layout, renderer, viewport, translation, ) } } impl<'a, Key, Message, Theme, Renderer> From<Column<'a, Key, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer> where Key: Copy + PartialEq + 'static, Message: 'a, Theme: 'a, Renderer: crate::core::Renderer + 'a, { fn from(column: Column<'a, Key, Message, Theme, Renderer>) -> Self { Self::new(column) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/highlighter/src/lib.rs
highlighter/src/lib.rs
//! A syntax highlighter for iced. use iced_core as core; use crate::core::Color; use crate::core::font::{self, Font}; use crate::core::text::highlighter::{self, Format}; use std::ops::Range; use std::sync::LazyLock; use syntect::highlighting; use syntect::parsing; use two_face::re_exports::syntect; static SYNTAXES: LazyLock<parsing::SyntaxSet> = LazyLock::new(two_face::syntax::extra_no_newlines); static THEMES: LazyLock<highlighting::ThemeSet> = LazyLock::new(highlighting::ThemeSet::load_defaults); const LINES_PER_SNAPSHOT: usize = 50; /// A syntax highlighter. #[derive(Debug)] pub struct Highlighter { syntax: &'static parsing::SyntaxReference, highlighter: highlighting::Highlighter<'static>, caches: Vec<(parsing::ParseState, parsing::ScopeStack)>, current_line: usize, } impl highlighter::Highlighter for Highlighter { type Settings = Settings; type Highlight = Highlight; type Iterator<'a> = Box<dyn Iterator<Item = (Range<usize>, Self::Highlight)> + 'a>; fn new(settings: &Self::Settings) -> Self { let syntax = SYNTAXES .find_syntax_by_token(&settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); let highlighter = highlighting::Highlighter::new(&THEMES.themes[settings.theme.key()]); let parser = parsing::ParseState::new(syntax); let stack = parsing::ScopeStack::new(); Highlighter { syntax, highlighter, caches: vec![(parser, stack)], current_line: 0, } } fn update(&mut self, new_settings: &Self::Settings) { self.syntax = SYNTAXES .find_syntax_by_token(&new_settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); self.highlighter = highlighting::Highlighter::new(&THEMES.themes[new_settings.theme.key()]); // Restart the highlighter self.change_line(0); } fn change_line(&mut self, line: usize) { let snapshot = line / LINES_PER_SNAPSHOT; if snapshot <= self.caches.len() { self.caches.truncate(snapshot); self.current_line = snapshot * LINES_PER_SNAPSHOT; } else { self.caches.truncate(1); self.current_line = 0; } let (parser, stack) = self.caches.last().cloned().unwrap_or_else(|| { ( parsing::ParseState::new(self.syntax), parsing::ScopeStack::new(), ) }); self.caches.push((parser, stack)); } fn highlight_line(&mut self, line: &str) -> Self::Iterator<'_> { if self.current_line / LINES_PER_SNAPSHOT >= self.caches.len() { let (parser, stack) = self.caches.last().expect("Caches must not be empty"); self.caches.push((parser.clone(), stack.clone())); } self.current_line += 1; let (parser, stack) = self.caches.last_mut().expect("Caches must not be empty"); let ops = parser.parse_line(line, &SYNTAXES).unwrap_or_default(); Box::new(scope_iterator(ops, line, stack, &self.highlighter)) } fn current_line(&self) -> usize { self.current_line } } fn scope_iterator<'a>( ops: Vec<(usize, parsing::ScopeStackOp)>, line: &str, stack: &'a mut parsing::ScopeStack, highlighter: &'a highlighting::Highlighter<'static>, ) -> impl Iterator<Item = (Range<usize>, Highlight)> + 'a { ScopeRangeIterator { ops, line_length: line.len(), index: 0, last_str_index: 0, } .filter_map(move |(range, scope)| { let _ = stack.apply(&scope); if range.is_empty() { None } else { Some(( range, Highlight(highlighter.style_mod_for_stack(&stack.scopes)), )) } }) } /// A streaming syntax highlighter. /// /// It can efficiently highlight an immutable stream of tokens. #[derive(Debug)] pub struct Stream { syntax: &'static parsing::SyntaxReference, highlighter: highlighting::Highlighter<'static>, commit: (parsing::ParseState, parsing::ScopeStack), state: parsing::ParseState, stack: parsing::ScopeStack, } impl Stream { /// Creates a new [`Stream`] highlighter. pub fn new(settings: &Settings) -> Self { let syntax = SYNTAXES .find_syntax_by_token(&settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); let highlighter = highlighting::Highlighter::new(&THEMES.themes[settings.theme.key()]); let state = parsing::ParseState::new(syntax); let stack = parsing::ScopeStack::new(); Self { syntax, highlighter, commit: (state.clone(), stack.clone()), state, stack, } } /// Highlights the given line from the last commit. pub fn highlight_line( &mut self, line: &str, ) -> impl Iterator<Item = (Range<usize>, Highlight)> + '_ { self.state = self.commit.0.clone(); self.stack = self.commit.1.clone(); let ops = self.state.parse_line(line, &SYNTAXES).unwrap_or_default(); scope_iterator(ops, line, &mut self.stack, &self.highlighter) } /// Commits the last highlighted line. pub fn commit(&mut self) { self.commit = (self.state.clone(), self.stack.clone()); } /// Resets the [`Stream`] highlighter. pub fn reset(&mut self) { self.state = parsing::ParseState::new(self.syntax); self.stack = parsing::ScopeStack::new(); self.commit = (self.state.clone(), self.stack.clone()); } } /// The settings of a [`Highlighter`]. #[derive(Debug, Clone, PartialEq)] pub struct Settings { /// The [`Theme`] of the [`Highlighter`]. /// /// It dictates the color scheme that will be used for highlighting. pub theme: Theme, /// The extension of the file or the name of the language to highlight. /// /// The [`Highlighter`] will use the token to automatically determine /// the grammar to use for highlighting. pub token: String, } /// A highlight produced by a [`Highlighter`]. #[derive(Debug)] pub struct Highlight(highlighting::StyleModifier); impl Highlight { /// Returns the color of this [`Highlight`]. /// /// If `None`, the original text color should be unchanged. pub fn color(&self) -> Option<Color> { self.0 .foreground .map(|color| Color::from_rgba8(color.r, color.g, color.b, color.a as f32 / 255.0)) } /// Returns the font of this [`Highlight`]. /// /// If `None`, the original font should be unchanged. pub fn font(&self) -> Option<Font> { self.0.font_style.and_then(|style| { let bold = style.contains(highlighting::FontStyle::BOLD); let italic = style.contains(highlighting::FontStyle::ITALIC); if bold || italic { Some(Font { weight: if bold { font::Weight::Bold } else { font::Weight::Normal }, style: if italic { font::Style::Italic } else { font::Style::Normal }, ..Font::MONOSPACE }) } else { None } }) } /// Returns the [`Format`] of the [`Highlight`]. /// /// It contains both the [`color`] and the [`font`]. /// /// [`color`]: Self::color /// [`font`]: Self::font pub fn to_format(&self) -> Format<Font> { Format { color: self.color(), font: self.font(), } } } /// A highlighting theme. #[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Theme { SolarizedDark, Base16Mocha, Base16Ocean, Base16Eighties, InspiredGitHub, } impl Theme { /// A static slice containing all the available themes. pub const ALL: &'static [Self] = &[ Self::SolarizedDark, Self::Base16Mocha, Self::Base16Ocean, Self::Base16Eighties, Self::InspiredGitHub, ]; /// Returns `true` if the [`Theme`] is dark, and false otherwise. pub fn is_dark(self) -> bool { match self { Self::SolarizedDark | Self::Base16Mocha | Self::Base16Ocean | Self::Base16Eighties => { true } Self::InspiredGitHub => false, } } fn key(self) -> &'static str { match self { Theme::SolarizedDark => "Solarized (dark)", Theme::Base16Mocha => "base16-mocha.dark", Theme::Base16Ocean => "base16-ocean.dark", Theme::Base16Eighties => "base16-eighties.dark", Theme::InspiredGitHub => "InspiredGitHub", } } } impl std::fmt::Display for Theme { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Theme::SolarizedDark => write!(f, "Solarized Dark"), Theme::Base16Mocha => write!(f, "Mocha"), Theme::Base16Ocean => write!(f, "Ocean"), Theme::Base16Eighties => write!(f, "Eighties"), Theme::InspiredGitHub => write!(f, "Inspired GitHub"), } } } struct ScopeRangeIterator { ops: Vec<(usize, parsing::ScopeStackOp)>, line_length: usize, index: usize, last_str_index: usize, } impl Iterator for ScopeRangeIterator { type Item = (std::ops::Range<usize>, parsing::ScopeStackOp); fn next(&mut self) -> Option<Self::Item> { if self.index > self.ops.len() { return None; } let next_str_i = if self.index == self.ops.len() { self.line_length } else { self.ops[self.index].0 }; let range = self.last_str_index..next_str_i; self.last_str_index = next_str_i; let op = if self.index == 0 { parsing::ScopeStackOp::Noop } else { self.ops[self.index - 1].1.clone() }; self.index += 1; Some((range, op)) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/scripts/build.rs
scripts/build.rs
fn main() { println!("cargo:rerun-if-changed=scripts/build.rs"); println!( "cargo:rustc-env=NU_FEATURES={}", std::env::var("CARGO_CFG_FEATURE").expect("set by cargo") ); #[cfg(windows)] { println!("cargo:rerun-if-changed=assets/nu_logo.ico"); let mut res = winresource::WindowsResource::new(); res.set_icon("assets/nu_logo.ico"); res.compile() .expect("Failed to run the Windows resource compiler (rc.exe)"); } #[cfg(not(windows))] { // Tango uses dynamic linking, to allow us to dynamically change between two bench suit at runtime. // This is currently not supported on non nightly rust, on windows. println!("cargo:rustc-link-arg-benches=-rdynamic"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/config_files.rs
src/config_files.rs
use log::warn; #[cfg(feature = "plugin")] use nu_cli::read_plugin_file; use nu_cli::{eval_config_contents, eval_source}; use nu_path::canonicalize_with; use nu_protocol::{ Config, ParseError, PipelineData, Spanned, engine::{EngineState, Stack, StateWorkingSet}, eval_const::{get_user_autoload_dirs, get_vendor_autoload_dirs}, report_parse_error, report_shell_error, }; use nu_utils::ConfigFileKind; use std::{ fs, fs::File, io::{Result, Write}, panic::{AssertUnwindSafe, catch_unwind}, path::Path, sync::Arc, }; const LOGINSHELL_FILE: &str = "login.nu"; pub(crate) fn read_config_file( engine_state: &mut EngineState, stack: &mut Stack, config_file: Option<Spanned<String>>, config_kind: ConfigFileKind, create_scaffold: bool, strict_mode: bool, ) { warn!("read_config_file() {config_kind:?} at {config_file:?}",); eval_default_config(engine_state, stack, config_kind); warn!("read_config_file() loading default {config_kind:?}"); // Load config startup file if let Some(file) = config_file { match engine_state.cwd_as_string(Some(stack)) { Ok(cwd) => { if let Ok(path) = canonicalize_with(&file.item, cwd) { eval_config_contents(path, engine_state, stack, strict_mode); } else { let e = ParseError::FileNotFound(file.item, file.span); report_parse_error(None, &StateWorkingSet::new(engine_state), &e); if strict_mode { std::process::exit(1); } } } Err(e) => { report_shell_error(None, engine_state, &e); } } } else if let Some(mut config_path) = nu_path::nu_config_dir() { // Create config directory if it does not exist if !config_path.exists() && let Err(err) = std::fs::create_dir_all(&config_path) { eprintln!("Failed to create config directory: {err}"); return; } config_path.push(config_kind.path()); if !config_path.exists() { let scaffold_config_file = config_kind.scaffold(); match create_scaffold { true => { if let Ok(mut output) = File::create(&config_path) { if write!(output, "{scaffold_config_file}").is_ok() { let config_name = config_kind.name(); println!( "{} file created at: {}", config_name, config_path.to_string_lossy() ); } else { eprintln!( "Unable to write to {}, sourcing default file instead", config_path.to_string_lossy(), ); return; } } else { eprintln!("Unable to create {scaffold_config_file}"); return; } } _ => { return; } } } eval_config_contents(config_path.into(), engine_state, stack, strict_mode); } } pub(crate) fn read_loginshell_file( engine_state: &mut EngineState, stack: &mut Stack, strict_mode: bool, ) { warn!( "read_loginshell_file() {}:{}:{}", file!(), line!(), column!() ); // read and execute loginshell file if exists if let Some(mut config_path) = nu_path::nu_config_dir() { config_path.push(LOGINSHELL_FILE); warn!("loginshell_file: {}", config_path.display()); if config_path.exists() { eval_config_contents(config_path.into(), engine_state, stack, strict_mode); } } } pub(crate) fn read_default_env_file(engine_state: &mut EngineState, stack: &mut Stack) { let config_file = ConfigFileKind::Env.default(); eval_source( engine_state, stack, config_file.as_bytes(), "default_env.nu", PipelineData::empty(), false, ); warn!( "read_default_env_file() env_file_contents: {config_file} {}:{}:{}", file!(), line!(), column!() ); // Merge the environment in case env vars changed in the config if let Err(e) = engine_state.merge_env(stack) { report_shell_error(None, engine_state, &e); } } /// Get files sorted lexicographically /// /// uses `impl Ord for String` fn read_and_sort_directory(path: &Path) -> Result<Vec<String>> { let mut entries = Vec::new(); for entry in fs::read_dir(path)? { let entry = entry?; let file_name = entry.file_name(); let file_name_str = file_name.into_string().unwrap_or_default(); entries.push(file_name_str); } entries.sort(); Ok(entries) } pub(crate) fn read_vendor_autoload_files(engine_state: &mut EngineState, stack: &mut Stack) { warn!( "read_vendor_autoload_files() {}:{}:{}", file!(), line!(), column!() ); // The evaluation order is first determined by the semantics of `get_vendor_autoload_dirs` // to determine the order of directories to evaluate get_vendor_autoload_dirs(engine_state) .iter() // User autoload directories are evaluated after vendor, which means that // the user can override vendor autoload files .chain(get_user_autoload_dirs(engine_state).iter()) .for_each(|autoload_dir| { warn!("read_vendor_autoload_files: {}", autoload_dir.display()); if autoload_dir.exists() { // on a second levels files are lexicographically sorted by the string of the filename let entries = read_and_sort_directory(autoload_dir); if let Ok(entries) = entries { for entry in entries { if !entry.ends_with(".nu") { continue; } let path = autoload_dir.join(entry); warn!("AutoLoading: {path:?}"); eval_config_contents(path, engine_state, stack, false); } } } }); } fn eval_default_config( engine_state: &mut EngineState, stack: &mut Stack, config_kind: ConfigFileKind, ) { warn!("eval_default_config() {config_kind:?}"); eval_source( engine_state, stack, config_kind.default().as_bytes(), config_kind.default_path(), PipelineData::empty(), false, ); // Merge the environment in case env vars changed in the config if let Err(e) = engine_state.merge_env(stack) { report_shell_error(Some(stack), engine_state, &e); } } pub(crate) fn setup_config( engine_state: &mut EngineState, stack: &mut Stack, #[cfg(feature = "plugin")] plugin_file: Option<Spanned<String>>, config_file: Option<Spanned<String>>, env_file: Option<Spanned<String>>, is_login_shell: bool, ) { warn!( "setup_config() config_file_specified: {:?}, env_file_specified: {:?}, login: {}", &config_file, &env_file, is_login_shell ); let create_scaffold = nu_path::nu_config_dir().is_some_and(|p| !p.exists()); let result = catch_unwind(AssertUnwindSafe(|| { #[cfg(feature = "plugin")] read_plugin_file(engine_state, plugin_file); read_config_file( engine_state, stack, env_file, ConfigFileKind::Env, create_scaffold, false, ); read_config_file( engine_state, stack, config_file, ConfigFileKind::Config, create_scaffold, false, ); if is_login_shell { read_loginshell_file(engine_state, stack, false); } // read and auto load vendor autoload files read_vendor_autoload_files(engine_state, stack); })); if result.is_err() { eprintln!( "A panic occurred while reading configuration files, using default configuration." ); engine_state.config = Arc::new(Config::default()) } } pub(crate) fn set_config_path( engine_state: &mut EngineState, cwd: &Path, default_config_name: &str, key: &str, config_file: Option<&Spanned<String>>, ) { warn!( "set_config_path() cwd: {:?}, default_config: {}, key: {}, config_file_specified: {:?}", &cwd, &default_config_name, &key, &config_file ); let config_path = match config_file { Some(s) => canonicalize_with(&s.item, cwd).ok(), None => nu_path::nu_config_dir().map(|p| { let mut p = canonicalize_with(&p, cwd).unwrap_or(p.into()); p.push(default_config_name); canonicalize_with(&p, cwd).unwrap_or(p) }), }; if let Some(path) = config_path { engine_state.set_config_path(key, path); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/command.rs
src/command.rs
use nu_engine::{command_prelude::*, get_full_help}; use nu_parser::{escape_for_script_arg, parse}; use nu_protocol::{ ast::{Expr, Expression}, engine::StateWorkingSet, report_parse_error, }; use nu_utils::{escape_quote_string, stdout_write_all_and_flush}; pub(crate) fn gather_commandline_args() -> (Vec<String>, String, Vec<String>) { // Would be nice if we had a way to parse this. The first flags we see will be going to nushell // then it'll be the script name // then the args to the script let mut args_to_nushell = Vec::from(["nu".into()]); let mut script_name = String::new(); let mut args = std::env::args(); // Mimic the behaviour of bash/zsh if let Some(argv0) = args.next() && argv0.starts_with('-') { args_to_nushell.push("--login".into()); } while let Some(arg) = args.next() { if !arg.starts_with('-') { script_name = arg; break; } let flag_value = match arg.as_ref() { "--commands" | "-c" | "--table-mode" | "-m" | "--error-style" | "-e" | "--execute" | "--config" | "--env-config" | "-I" | "ide-ast" => { args.next().map(|a| escape_quote_string(&a)) } #[cfg(feature = "plugin")] "--plugin-config" => args.next().map(|a| escape_quote_string(&a)), "--log-level" | "--log-target" | "--log-include" | "--log-exclude" | "--testbin" | "--threads" | "-t" | "--include-path" | "--lsp" | "--ide-goto-def" | "--ide-hover" | "--ide-complete" | "--ide-check" | "--experimental-options" => args.next(), #[cfg(feature = "mcp")] "--mcp" => args.next(), #[cfg(feature = "plugin")] "--plugins" => args.next(), _ => None, }; args_to_nushell.push(arg); if let Some(flag_value) = flag_value { args_to_nushell.push(flag_value); } } let args_to_script = if !script_name.is_empty() { args.map(|arg| escape_for_script_arg(&arg)).collect() } else { Vec::default() }; (args_to_nushell, script_name, args_to_script) } pub(crate) fn parse_commandline_args( commandline_args: &str, engine_state: &mut EngineState, ) -> Result<NushellCliArgs, ShellError> { let (block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); working_set.add_decl(Box::new(Nu)); let output = parse(&mut working_set, None, commandline_args.as_bytes(), false); if let Some(err) = working_set.parse_errors.first() { report_parse_error(None, &working_set, err); std::process::exit(1); } working_set.hide_decl(b"nu"); (output, working_set.render()) }; engine_state.merge_delta(delta)?; let mut stack = Stack::new(); // We should have a successful parse now if let Some(pipeline) = block.pipelines.first() && let Some(Expr::Call(call)) = pipeline.elements.first().map(|e| &e.expr.expr) { let redirect_stdin = call.get_named_arg("stdin"); let login_shell = call.get_named_arg("login"); let interactive_shell = call.get_named_arg("interactive"); let commands = call.get_flag_expr("commands"); let testbin = call.get_flag_expr("testbin"); #[cfg(feature = "plugin")] let plugin_file = call.get_flag_expr("plugin-config"); #[cfg(feature = "plugin")] let plugins = call.get_flag_expr("plugins"); let no_config_file = call.get_named_arg("no-config-file"); let no_history = call.get_named_arg("no-history"); let no_std_lib = call.get_named_arg("no-std-lib"); let config_file = call.get_flag_expr("config"); let env_file = call.get_flag_expr("env-config"); let log_level = call.get_flag_expr("log-level"); let log_target = call.get_flag_expr("log-target"); let log_include = call.get_flag_expr("log-include"); let log_exclude = call.get_flag_expr("log-exclude"); let execute = call.get_flag_expr("execute"); let table_mode: Option<Value> = call.get_flag(engine_state, &mut stack, "table-mode")?; let error_style: Option<Value> = call.get_flag(engine_state, &mut stack, "error-style")?; let no_newline = call.get_named_arg("no-newline"); let experimental_options = call.get_flag_expr("experimental-options"); // ide flags let lsp = call.has_flag(engine_state, &mut stack, "lsp")?; let include_path = call.get_flag_expr("include-path"); let ide_goto_def: Option<Value> = call.get_flag(engine_state, &mut stack, "ide-goto-def")?; let ide_hover: Option<Value> = call.get_flag(engine_state, &mut stack, "ide-hover")?; let ide_complete: Option<Value> = call.get_flag(engine_state, &mut stack, "ide-complete")?; let ide_check: Option<Value> = call.get_flag(engine_state, &mut stack, "ide-check")?; let ide_ast: Option<Spanned<String>> = call.get_named_arg("ide-ast"); #[cfg(feature = "mcp")] let mcp = call.has_flag(engine_state, &mut stack, "mcp")?; fn extract_contents( expression: Option<&Expression>, ) -> Result<Option<Spanned<String>>, ShellError> { if let Some(expr) = expression { let str = expr.as_string(); if let Some(str) = str { Ok(Some(Spanned { item: str, span: expr.span, })) } else { Err(ShellError::TypeMismatch { err_message: "string".into(), span: expr.span, }) } } else { Ok(None) } } fn extract_path( expression: Option<&Expression>, ) -> Result<Option<Spanned<String>>, ShellError> { if let Some(expr) = expression { let tuple = expr.as_filepath(); if let Some((str, _)) = tuple { Ok(Some(Spanned { item: str, span: expr.span, })) } else { Err(ShellError::TypeMismatch { err_message: "path".into(), span: expr.span, }) } } else { Ok(None) } } fn extract_list( expression: Option<&Expression>, type_name: &str, mut extract_item: impl FnMut(&Expression) -> Option<String>, ) -> Result<Option<Vec<Spanned<String>>>, ShellError> { expression .map(|expr| match &expr.expr { Expr::List(list) => list .iter() .map(|item| { extract_item(item.expr()) .map(|s| s.into_spanned(item.expr().span)) .ok_or_else(|| ShellError::TypeMismatch { err_message: type_name.into(), span: item.expr().span, }) }) .collect::<Result<Vec<Spanned<String>>, _>>(), _ => Err(ShellError::TypeMismatch { err_message: format!("list<{type_name}>"), span: expr.span, }), }) .transpose() } let commands = extract_contents(commands)?; let testbin = extract_contents(testbin)?; #[cfg(feature = "plugin")] let plugin_file = extract_path(plugin_file)?; #[cfg(feature = "plugin")] let plugins = extract_list(plugins, "path", |expr| expr.as_filepath().map(|t| t.0))?; let config_file = extract_path(config_file)?; let env_file = extract_path(env_file)?; let log_level = extract_contents(log_level)?; let log_target = extract_contents(log_target)?; let log_include = extract_list(log_include, "string", |expr| expr.as_string())?; let log_exclude = extract_list(log_exclude, "string", |expr| expr.as_string())?; let execute = extract_contents(execute)?; let include_path = extract_contents(include_path)?; let experimental_options = extract_list(experimental_options, "string", |expr| expr.as_string())?; let help = call.has_flag(engine_state, &mut stack, "help")?; if help { let full_help = get_full_help(&Nu, engine_state, &mut stack); let _ = std::panic::catch_unwind(move || stdout_write_all_and_flush(full_help)); std::process::exit(0); } if call.has_flag(engine_state, &mut stack, "version")? { let version = env!("CARGO_PKG_VERSION").to_string(); let _ = std::panic::catch_unwind(move || { stdout_write_all_and_flush(format!("{version}\n")) }); std::process::exit(0); } return Ok(NushellCliArgs { redirect_stdin, login_shell, interactive_shell, commands, testbin, #[cfg(feature = "plugin")] plugin_file, #[cfg(feature = "plugin")] plugins, no_config_file, no_history, no_std_lib, config_file, env_file, log_level, log_target, log_include, log_exclude, execute, include_path, ide_goto_def, ide_hover, ide_complete, lsp, ide_check, ide_ast, table_mode, error_style, no_newline, experimental_options, #[cfg(feature = "mcp")] mcp, }); } // Just give the help and exit if the above fails let full_help = get_full_help(&Nu, engine_state, &mut stack); print!("{full_help}"); std::process::exit(1); } #[derive(Clone)] pub(crate) struct NushellCliArgs { pub(crate) redirect_stdin: Option<Spanned<String>>, pub(crate) login_shell: Option<Spanned<String>>, pub(crate) interactive_shell: Option<Spanned<String>>, pub(crate) commands: Option<Spanned<String>>, pub(crate) testbin: Option<Spanned<String>>, #[cfg(feature = "plugin")] pub(crate) plugin_file: Option<Spanned<String>>, #[cfg(feature = "plugin")] pub(crate) plugins: Option<Vec<Spanned<String>>>, pub(crate) no_config_file: Option<Spanned<String>>, pub(crate) no_history: Option<Spanned<String>>, pub(crate) no_std_lib: Option<Spanned<String>>, pub(crate) config_file: Option<Spanned<String>>, pub(crate) env_file: Option<Spanned<String>>, pub(crate) log_level: Option<Spanned<String>>, pub(crate) log_target: Option<Spanned<String>>, pub(crate) log_include: Option<Vec<Spanned<String>>>, pub(crate) log_exclude: Option<Vec<Spanned<String>>>, pub(crate) execute: Option<Spanned<String>>, pub(crate) table_mode: Option<Value>, pub(crate) error_style: Option<Value>, pub(crate) no_newline: Option<Spanned<String>>, pub(crate) include_path: Option<Spanned<String>>, pub(crate) lsp: bool, pub(crate) ide_goto_def: Option<Value>, pub(crate) ide_hover: Option<Value>, pub(crate) ide_complete: Option<Value>, pub(crate) ide_check: Option<Value>, pub(crate) ide_ast: Option<Spanned<String>>, pub(crate) experimental_options: Option<Vec<Spanned<String>>>, #[cfg(feature = "mcp")] pub(crate) mcp: bool, } #[derive(Clone)] struct Nu; impl Command for Nu { fn name(&self) -> &str { "nu" } fn signature(&self) -> Signature { let mut signature = Signature::build("nu") .description("The nushell language and shell.") .named( "commands", SyntaxShape::String, "run the given commands and then exit", Some('c'), ) .named( "execute", SyntaxShape::String, "run the given commands and then enter an interactive shell", Some('e'), ) .named( "include-path", SyntaxShape::String, "set the NU_LIB_DIRS for the given script (delimited by char record_sep ('\x1e'))", Some('I'), ) .switch("interactive", "start as an interactive shell", Some('i')) .switch("login", "start as a login shell", Some('l')) .named( "table-mode", SyntaxShape::String, "the table mode to use. rounded is default.", Some('m'), ) .named( "error-style", SyntaxShape::String, "the error style to use (fancy or plain). default: fancy", None, ) .switch("no-newline", "print the result for --commands(-c) without a newline", None) .switch( "no-config-file", "start with no config file and no env file", Some('n'), ) .switch( "no-history", "disable reading and writing to command history", None, ) .switch("no-std-lib", "start with no standard library", None) .named( "threads", SyntaxShape::Int, "threads to use for parallel commands", Some('t'), ) .switch("version", "print the version", Some('v')) .named( "config", SyntaxShape::Filepath, "start with an alternate config file", None, ) .named( "env-config", SyntaxShape::Filepath, "start with an alternate environment config file", None, ) .switch( "lsp", "start nu's language server protocol", None, ) .named( "ide-goto-def", SyntaxShape::Int, "go to the definition of the item at the given position", None, ) .named( "ide-hover", SyntaxShape::Int, "give information about the item at the given position", None, ) .named( "ide-complete", SyntaxShape::Int, "list completions for the item at the given position", None, ) .named( "ide-check", SyntaxShape::Int, "run a diagnostic check on the given source and limit number of errors returned to provided number", None, ) .switch("ide-ast", "generate the ast on the given source", None); #[cfg(feature = "mcp")] { signature = signature.switch("mcp", "start nu's model context protocol server", None); } #[cfg(feature = "plugin")] { signature = signature .named( "plugin-config", SyntaxShape::Filepath, "start with an alternate plugin registry file", None, ) .named( "plugins", SyntaxShape::List(Box::new(SyntaxShape::Filepath)), "list of plugin executable files to load, separately from the registry file", None, ) } signature = signature .named( "log-level", SyntaxShape::String, "log level for diagnostic logs (error, warn, info, debug, trace). Off by default", None, ) .named( "log-target", SyntaxShape::String, "set the target for the log to output. stdout, stderr(default), mixed or file", None, ) .named( "log-include", SyntaxShape::List(Box::new(SyntaxShape::String)), "set the Rust module prefixes to include in the log output. default: [nu]", None, ) .named( "log-exclude", SyntaxShape::List(Box::new(SyntaxShape::String)), "set the Rust module prefixes to exclude from the log output", None, ) .switch( "stdin", "redirect standard input to a command (with `-c`) or a script file", None, ) .named( "testbin", SyntaxShape::String, "run internal test binary", None, ) .named( "experimental-options", SyntaxShape::List(Box::new(SyntaxShape::String)), r#"enable or disable experimental options, use `"all"` to set all active options"#, None, ) .optional( "script file", SyntaxShape::Filepath, "name of the optional script file to run", ) .rest( "script args", SyntaxShape::String, "parameters to the script file", ) .category(Category::System); signature } fn description(&self) -> &str { "The nushell language and shell." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { description: "Run a script", example: "nu myfile.nu", result: None, }, Example { description: "Run nushell interactively (as a shell or REPL)", example: "nu", result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/command_context.rs
src/command_context.rs
use nu_protocol::engine::EngineState; pub(crate) fn add_command_context(engine_state: EngineState) -> EngineState { let engine_state = nu_cmd_lang::add_default_context(engine_state); #[cfg(feature = "plugin")] let engine_state = nu_cmd_plugin::add_plugin_command_context(engine_state); let engine_state = nu_command::add_shell_command_context(engine_state); let engine_state = nu_cmd_extra::add_extra_command_context(engine_state); let engine_state = nu_cli::add_cli_context(engine_state); let mut engine_state = nu_explore::add_explore_context(engine_state); nu_command::IntoValue::add_deprecated_call(&mut engine_state); engine_state } #[cfg(test)] mod tests { use super::*; use nu_protocol::{Category, PositionalArg}; #[test] fn arguments_end_period() { fn ends_period(cmd_name: &str, ty: &str, arg: PositionalArg, failures: &mut Vec<String>) { let arg_name = arg.name; let desc = arg.desc; if !desc.ends_with('.') { failures.push(format!( "{cmd_name} {ty} argument \"{arg_name}\": \"{desc}\"" )); } } let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let signature = cmd.signature(); for arg in signature.required_positional { ends_period(&cmd_name, "required", arg, &mut failures); } for arg in signature.optional_positional { ends_period(&cmd_name, "optional", arg, &mut failures); } if let Some(arg) = signature.rest_positional { ends_period(&cmd_name, "rest", arg, &mut failures); } } assert!( failures.is_empty(), "Command argument description does not end with a period:\n{}", failures.join("\n") ); } #[test] fn arguments_start_uppercase() { fn starts_uppercase( cmd_name: &str, ty: &str, arg: PositionalArg, failures: &mut Vec<String>, ) { let arg_name = arg.name; let desc = arg.desc; // Check lowercase to allow usage to contain syntax like: // // "`as` keyword …" if desc.starts_with(|u: char| u.is_lowercase()) { failures.push(format!( "{cmd_name} {ty} argument \"{arg_name}\": \"{desc}\"" )); } } let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let signature = cmd.signature(); for arg in signature.required_positional { starts_uppercase(&cmd_name, "required", arg, &mut failures); } for arg in signature.optional_positional { starts_uppercase(&cmd_name, "optional", arg, &mut failures); } if let Some(arg) = signature.rest_positional { starts_uppercase(&cmd_name, "rest", arg, &mut failures); } } assert!( failures.is_empty(), "Command argument description does not end with a period:\n{}", failures.join("\n") ); } #[test] fn signature_name_matches_command_name() { let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let sig_name = cmd.signature().name; let category = cmd.signature().category; if cmd_name != sig_name { failures.push(format!( "{cmd_name} ({category:?}): Signature name \"{sig_name}\" is not equal to the command name \"{cmd_name}\"" )); } } assert!( failures.is_empty(), "Name mismatch:\n{}", failures.join("\n") ); } #[test] fn commands_declare_input_output_types() { let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (_, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let sig_name = cmd.signature().name; let category = cmd.signature().category; if let Category::Removed = category { // Deprecated/Removed commands don't have to conform continue; } if cmd.signature().input_output_types.is_empty() { failures.push(format!( "{sig_name} ({category:?}): No pipeline input/output type signatures found" )); } } assert!( failures.is_empty(), "Command missing type annotations:\n{}", failures.join("\n") ); } #[test] fn no_search_term_duplicates() { let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let search_terms = cmd.search_terms(); let category = cmd.signature().category; for search_term in search_terms { if cmd_name.contains(search_term) { failures.push(format!("{cmd_name} ({category:?}): Search term \"{search_term}\" is substring of command name \"{cmd_name}\"")); } } } assert!( failures.is_empty(), "Duplication in search terms:\n{}", failures.join("\n") ); } #[test] fn description_end_period() { let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let description = cmd.description(); if !description.ends_with('.') { failures.push(format!("{cmd_name}: \"{description}\"")); } } assert!( failures.is_empty(), "Command description does not end with a period:\n{}", failures.join("\n") ); } #[test] fn description_start_uppercase() { let ctx = add_command_context(EngineState::new()); let decls = ctx.get_decls_sorted(true); let mut failures = Vec::new(); for (name_bytes, decl_id) in decls { let cmd = ctx.get_decl(decl_id); let cmd_name = String::from_utf8_lossy(&name_bytes); let description = cmd.description(); // Check lowercase to allow description to contain syntax like: // // "`$env.FOO = ...`" if description.starts_with(|u: char| u.is_lowercase()) { failures.push(format!("{cmd_name}: \"{description}\"")); } } assert!( failures.is_empty(), "Command description does not start with an uppercase letter:\n{}", failures.join("\n") ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/logger.rs
src/logger.rs
use log::{Level, LevelFilter, SetLoggerError}; use nu_protocol::ShellError; use simplelog::{ Color, ColorChoice, Config, ConfigBuilder, LevelPadding, TermLogger, TerminalMode, WriteLogger, format_description, }; use std::{fs::File, path::Path, str::FromStr}; pub enum LogTarget { Stdout, Stderr, Mixed, File, } impl From<&str> for LogTarget { fn from(s: &str) -> Self { match s { "stdout" => Self::Stdout, "mixed" => Self::Mixed, "file" => Self::File, _ => Self::Stderr, } } } pub fn logger( f: impl FnOnce(&mut ConfigBuilder) -> (LevelFilter, LogTarget), ) -> Result<(), ShellError> { let mut builder = ConfigBuilder::new(); let (level, target) = f(&mut builder); let config = builder.build(); let _ = match target { LogTarget::Stdout => { TermLogger::init(level, config, TerminalMode::Stdout, ColorChoice::Auto) } LogTarget::Mixed => TermLogger::init(level, config, TerminalMode::Mixed, ColorChoice::Auto), LogTarget::File => { let pid = std::process::id(); let mut path = std::env::temp_dir(); path.push(format!("nu-{pid}.log")); set_write_logger(level, config, &path) } _ => TermLogger::init(level, config, TerminalMode::Stderr, ColorChoice::Auto), }; Ok(()) } fn set_write_logger(level: LevelFilter, config: Config, path: &Path) -> Result<(), SetLoggerError> { // Use TermLogger instead if WriteLogger is not available if let Ok(file) = File::create(path) { WriteLogger::init(level, config, file) } else { let default_logger = TermLogger::init(level, config, TerminalMode::Stderr, ColorChoice::Auto); if default_logger.is_ok() { log::warn!("failed to init WriteLogger, use TermLogger instead"); } default_logger } } pub struct Filters { pub include: Option<Vec<String>>, pub exclude: Option<Vec<String>>, } pub fn configure( level: &str, target: &str, filters: Filters, builder: &mut ConfigBuilder, ) -> (LevelFilter, LogTarget) { let level = match Level::from_str(level) { Ok(level) => level, Err(_) => Level::Warn, }; // Add allowed module filter if let Some(include) = filters.include { for filter in include { builder.add_filter_allow(filter); } } else { builder.add_filter_allow_str("nu"); } // Add ignored module filter if let Some(exclude) = filters.exclude { for filter in exclude { builder.add_filter_ignore(filter); } } // Set level padding builder.set_level_padding(LevelPadding::Right); // Custom time format builder.set_time_format_custom(format_description!( "[year]-[month]-[day] [hour repr:12]:[minute]:[second].[subsecond digits:3] [period]" )); // Show module path builder.set_target_level(LevelFilter::Error); // Don't show thread id builder.set_thread_level(LevelFilter::Off); let log_target = LogTarget::from(target); // Only TermLogger supports color output if let LogTarget::Stdout | LogTarget::Stderr | LogTarget::Mixed = log_target { Level::iter().for_each(|level| set_colored_level(builder, level)); } (level.to_level_filter(), log_target) } fn set_colored_level(builder: &mut ConfigBuilder, level: Level) { let color = match level { Level::Trace => Color::Magenta, Level::Debug => Color::Blue, Level::Info => Color::Green, Level::Warn => Color::Yellow, Level::Error => Color::Red, }; builder.set_level_color(level, Some(color)); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/ide.rs
src/ide.rs
use miette::IntoDiagnostic; use nu_cli::NuCompleter; use nu_parser::{FlatShape, flatten_block, parse}; use nu_protocol::{ DeclId, ShellError, Span, Value, VarId, engine::{EngineState, Stack, StateWorkingSet}, report_shell_error, shell_error::io::{IoError, IoErrorExt, NotFound}, }; use reedline::Completer; use serde_json::{Value as JsonValue, json}; use std::{path::PathBuf, sync::Arc}; #[derive(Debug)] enum Id { Variable(VarId), Declaration(DeclId), Value(FlatShape), } fn find_id( working_set: &mut StateWorkingSet, file_path: &str, file: &[u8], location: &Value, ) -> Option<(Id, usize, Span)> { let file_id = working_set.add_file(file_path.to_string(), file); let offset = working_set.get_span_for_file(file_id).start; let _ = working_set.files.push(file_path.into(), Span::unknown()); let block = parse(working_set, Some(file_path), file, false); let flattened = flatten_block(working_set, &block); if let Ok(location) = location.as_int() { let location = location as usize + offset; for item in flattened { if location >= item.0.start && location < item.0.end { match &item.1 { FlatShape::Variable(var_id) | FlatShape::VarDecl(var_id) => { return Some((Id::Variable(*var_id), offset, item.0)); } FlatShape::InternalCall(decl_id) => { return Some((Id::Declaration(*decl_id), offset, item.0)); } _ => return Some((Id::Value(item.1), offset, item.0)), } } } None } else { None } } fn read_in_file<'a>( engine_state: &'a mut EngineState, file_path: &str, ) -> (Vec<u8>, StateWorkingSet<'a>) { let file = std::fs::read(file_path) .map_err(|err| { ShellError::Io(IoError::new_with_additional_context( err.not_found_as(NotFound::File), Span::unknown(), PathBuf::from(file_path), "Could not read file", )) }) .unwrap_or_else(|err| { report_shell_error(None, engine_state, &err); std::process::exit(1); }); engine_state.file = Some(PathBuf::from(file_path)); let working_set = StateWorkingSet::new(engine_state); (file, working_set) } pub fn check(engine_state: &mut EngineState, file_path: &str, max_errors: &Value) { let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); engine_state.generate_nu_constant(); let mut working_set = StateWorkingSet::new(engine_state); let file = std::fs::read(file_path); let max_errors = if let Ok(max_errors) = max_errors.as_int() { max_errors as usize } else { 100 }; if let Ok(contents) = file { let offset = working_set.next_span_start(); let _ = working_set.files.push(file_path.into(), Span::unknown()); let block = parse(&mut working_set, Some(file_path), &contents, false); for (idx, err) in working_set.parse_errors.iter().enumerate() { if idx >= max_errors { // eprintln!("Too many errors, stopping here. idx: {idx} max_errors: {max_errors}"); break; } let mut span = err.span(); span.start -= offset; span.end -= offset; let msg = err.to_string(); println!( "{}", json!({ "type": "diagnostic", "severity": "Error", "message": msg, "span": { "start": span.start, "end": span.end } }) ); } let flattened = flatten_block(&working_set, &block); for flat in flattened { if let FlatShape::VarDecl(var_id) = flat.1 { let var = working_set.get_variable(var_id); println!( "{}", json!({ "type": "hint", "typename": var.ty.to_string(), "position": { "start": flat.0.start - offset, "end": flat.0.end - offset } }) ); } } } } pub fn goto_def(engine_state: &mut EngineState, file_path: &str, location: &Value) { let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); let (file, mut working_set) = read_in_file(engine_state, file_path); match find_id(&mut working_set, file_path, &file, location) { Some((Id::Declaration(decl_id), ..)) => { let result = working_set.get_decl(decl_id); if let Some(block_id) = result.block_id() { let block = working_set.get_block(block_id); if let Some(span) = &block.span { for file in working_set.files() { if file.covered_span.contains(span.start) { println!( "{}", json!( { "file": &*file.name, "start": span.start - file.covered_span.start, "end": span.end - file.covered_span.start, } ) ); return; } } } } } Some((Id::Variable(var_id), ..)) => { let var = working_set.get_variable(var_id); for file in working_set.files() { if file.covered_span.contains(var.declaration_span.start) { println!( "{}", json!( { "file": &*file.name, "start": var.declaration_span.start - file.covered_span.start, "end": var.declaration_span.end - file.covered_span.start, } ) ); return; } } } _ => {} } println!("{{}}"); } pub fn hover(engine_state: &mut EngineState, file_path: &str, location: &Value) { let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); let (file, mut working_set) = read_in_file(engine_state, file_path); match find_id(&mut working_set, file_path, &file, location) { Some((Id::Declaration(decl_id), offset, span)) => { let decl = working_set.get_decl(decl_id); let mut description = String::new(); // first description description.push_str(&format!("{}\n", decl.description())); // additional description if !decl.extra_description().is_empty() { description.push_str(&format!("\n{}\n", decl.extra_description())); } // Usage description.push_str("### Usage\n```\n"); let signature = decl.signature(); description.push_str(&format!(" {}", signature.name)); if !signature.named.is_empty() { description.push_str(" {flags}") } for required_arg in &signature.required_positional { description.push_str(&format!(" <{}>", required_arg.name)); } for optional_arg in &signature.optional_positional { description.push_str(&format!(" <{}?>", optional_arg.name)); } if let Some(arg) = &signature.rest_positional { description.push_str(&format!(" <...{}>", arg.name)); } description.push_str("\n```\n"); // Flags if !signature.named.is_empty() { description.push_str("\n### Flags\n\n"); let mut first = true; for named in &signature.named { if !first { description.push_str("\\\n"); } else { first = false; } description.push_str(" "); if let Some(short_flag) = &named.short { description.push_str(&format!("`-{short_flag}`")); } if !named.long.is_empty() { if named.short.is_some() { description.push_str(", ") } description.push_str(&format!("`--{}`", named.long)); } if let Some(arg) = &named.arg { description.push_str(&format!(" `<{}>`", arg.to_type())) } if !named.desc.is_empty() { description.push_str(&format!(" - {}", named.desc)); } } description.push('\n'); } // Parameters if !signature.required_positional.is_empty() || !signature.optional_positional.is_empty() || signature.rest_positional.is_some() { description.push_str("\n### Parameters\n\n"); let mut first = true; for required_arg in &signature.required_positional { if !first { description.push_str("\\\n"); } else { first = false; } description.push_str(&format!( " `{}: {}`", required_arg.name, required_arg.shape.to_type() )); if !required_arg.desc.is_empty() { description.push_str(&format!(" - {}", required_arg.desc)); } description.push('\n'); } for optional_arg in &signature.optional_positional { if !first { description.push_str("\\\n"); } else { first = false; } description.push_str(&format!( " `{}: {}`", optional_arg.name, optional_arg.shape.to_type() )); if !optional_arg.desc.is_empty() { description.push_str(&format!(" - {}", optional_arg.desc)); } description.push('\n'); } if let Some(arg) = &signature.rest_positional { if !first { description.push_str("\\\n"); } description.push_str(&format!(" `...{}: {}`", arg.name, arg.shape.to_type())); if !arg.desc.is_empty() { description.push_str(&format!(" - {}", arg.desc)); } description.push('\n'); } description.push('\n'); } // Input/output types if !signature.input_output_types.is_empty() { description.push_str("\n### Input/output types\n"); description.push_str("\n```\n"); for input_output in &signature.input_output_types { description.push_str(&format!(" {} | {}\n", input_output.0, input_output.1)); } description.push_str("\n```\n"); } // Examples if !decl.examples().is_empty() { description.push_str("### Example(s)\n```\n"); for example in decl.examples() { description.push_str(&format!( "```\n {}\n```\n {}\n\n", example.description, example.example )); } } println!( "{}", json!({ "hover": description, "span": { "start": span.start - offset, "end": span.end - offset } }) ); } Some((Id::Variable(var_id), offset, span)) => { let var = working_set.get_variable(var_id); println!( "{}", json!({ "hover": format!("{}{}", if var.mutable { "mutable " } else { "" }, var.ty), "span": { "start": span.start - offset, "end": span.end - offset } }) ); } Some((Id::Value(shape), offset, span)) => match shape { FlatShape::Binary => println!( "{}", json!({ "hover": "binary", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Bool => println!( "{}", json!({ "hover": "bool", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::DateTime => println!( "{}", json!({ "hover": "datetime", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::External(alias_span) => println!( "{}", json!({ "hover": "external", "span": { "start": alias_span.start - offset, "end": alias_span.end - offset } }) ), FlatShape::ExternalArg => println!( "{}", json!({ "hover": "external arg", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Flag => println!( "{}", json!({ "hover": "flag", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Block => println!( "{}", json!({ "hover": "block", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Directory => println!( "{}", json!({ "hover": "directory", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Filepath => println!( "{}", json!({ "hover": "file path", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Float => println!( "{}", json!({ "hover": "float", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::GlobPattern => println!( "{}", json!({ "hover": "glob pattern", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Int => println!( "{}", json!({ "hover": "int", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Keyword => println!( "{}", json!({ "hover": "keyword", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::List => println!( "{}", json!({ "hover": "list", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::MatchPattern => println!( "{}", json!({ "hover": "match-pattern", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Nothing => println!( "{}", json!({ "hover": "nothing", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Range => println!( "{}", json!({ "hover": "range", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Record => println!( "{}", json!({ "hover": "record", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::String => println!( "{}", json!({ "hover": "string", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::RawString => println!( "{}", json!({ "hover": "raw-string", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::StringInterpolation => println!( "{}", json!({ "hover": "string interpolation", "span": { "start": span.start - offset, "end": span.end - offset } }) ), FlatShape::Table => println!( "{}", json!({ "hover": "table", "span": { "start": span.start - offset, "end": span.end - offset } }) ), _ => {} }, _ => {} } } pub fn complete(engine_reference: Arc<EngineState>, file_path: &str, location: &Value) { let mut completer = NuCompleter::new(engine_reference, Arc::new(Stack::new())); let file = std::fs::read(file_path) .into_diagnostic() .unwrap_or_else(|_| { std::process::exit(1); }); if let Ok(location) = location.as_int() { let results = completer.complete( &String::from_utf8_lossy(&file)[..location as usize], location as usize, ); print!("{{\"completions\": ["); let mut first = true; for result in results { if !first { print!(", ") } else { first = false; } print!("\"{}\"", result.value,) } println!("]}}"); } } pub fn ast(engine_state: &mut EngineState, file_path: &str) { let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); let mut working_set = StateWorkingSet::new(engine_state); let file = std::fs::read(file_path); if let Ok(contents) = file { let offset = working_set.next_span_start(); let _ = working_set.files.push(file_path.into(), Span::unknown()); let parsed_block = parse(&mut working_set, Some(file_path), &contents, false); let flat = flatten_block(&working_set, &parsed_block); let mut json_val: JsonValue = json!([]); for (span, shape) in flat { let content = String::from_utf8_lossy(working_set.get_span_contents(span)).to_string(); let json = json!( { "type": "ast", "span": { "start": span.start.checked_sub(offset), "end": span.end.checked_sub(offset), }, "shape": shape.to_string(), "content": content // may not be necessary, but helpful for debugging } ); json_merge(&mut json_val, &json); } if let Ok(json_str) = serde_json::to_string(&json_val) { println!("{json_str}"); } else { println!("{{}}"); }; } } fn json_merge(a: &mut JsonValue, b: &JsonValue) { match (a, b) { (JsonValue::Object(a), JsonValue::Object(b)) => { for (k, v) in b { json_merge(a.entry(k).or_insert(JsonValue::Null), v); } } (JsonValue::Array(a), JsonValue::Array(b)) => { a.extend(b.clone()); } (JsonValue::Array(a), JsonValue::Object(b)) => { a.extend([JsonValue::Object(b.clone())]); } (a, b) => { *a = b.clone(); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false