Merge branch 'master' into beacon

This commit is contained in:
Héctor Ramón Jiménez 2024-05-09 12:32:25 +02:00
commit aaf396256e
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
284 changed files with 18747 additions and 15450 deletions

View file

@ -1,20 +1,17 @@
use std::{f32::consts::PI, time::Instant};
use iced::executor;
use iced::mouse;
use iced::widget::canvas::{
self, stroke, Cache, Canvas, Geometry, Path, Stroke,
};
use iced::{
Application, Command, Element, Length, Point, Rectangle, Renderer,
Settings, Subscription, Theme,
};
use iced::{Element, Length, Point, Rectangle, Renderer, Subscription, Theme};
pub fn main() -> iced::Result {
Arc::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program("Arc - Iced", Arc::update, Arc::view)
.subscription(Arc::subscription)
.theme(|_| Theme::Dark)
.antialiasing(true)
.run()
}
struct Arc {
@ -27,30 +24,9 @@ enum Message {
Tick,
}
impl Application for Arc {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Arc {
start: Instant::now(),
cache: Cache::default(),
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Arc - Iced")
}
fn update(&mut self, _: Message) -> Command<Message> {
impl Arc {
fn update(&mut self, _: Message) {
self.cache.clear();
Command::none()
}
fn view(&self) -> Element<Message> {
@ -60,16 +36,21 @@ impl Application for Arc {
.into()
}
fn theme(&self) -> Theme {
Theme::Dark
}
fn subscription(&self) -> Subscription<Message> {
iced::time::every(std::time::Duration::from_millis(10))
.map(|_| Message::Tick)
}
}
impl Default for Arc {
fn default() -> Self {
Arc {
start: Instant::now(),
cache: Cache::default(),
}
}
}
impl<Message> canvas::Program<Message> for Arc {
type State = ();

View file

@ -1,12 +1,13 @@
//! This example showcases an interactive `Canvas` for drawing Bézier curves.
use iced::widget::{button, column, text};
use iced::{Alignment, Element, Length, Sandbox, Settings};
use iced::alignment;
use iced::widget::{button, container, horizontal_space, hover};
use iced::{Element, Length, Theme};
pub fn main() -> iced::Result {
Example::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program("Bezier Tool - Iced", Example::update, Example::view)
.theme(|_| Theme::CatppuccinMocha)
.antialiasing(true)
.run()
}
#[derive(Default)]
@ -21,17 +22,7 @@ enum Message {
Clear,
}
impl Sandbox for Example {
type Message = Message;
fn new() -> Self {
Example::default()
}
fn title(&self) -> String {
String::from("Bezier tool - Iced")
}
impl Example {
fn update(&mut self, message: Message) {
match message {
Message::AddCurve(curve) => {
@ -46,14 +37,22 @@ impl Sandbox for Example {
}
fn view(&self) -> Element<Message> {
column![
text("Bezier tool example").width(Length::Shrink).size(50),
container(hover(
self.bezier.view(&self.curves).map(Message::AddCurve),
button("Clear").padding(8).on_press(Message::Clear),
]
if self.curves.is_empty() {
container(horizontal_space())
} else {
container(
button("Clear")
.style(button::danger)
.on_press(Message::Clear),
)
.padding(10)
.width(Length::Fill)
.align_x(alignment::Horizontal::Right)
},
))
.padding(20)
.spacing(20)
.align_items(Alignment::Center)
.into()
}
}
@ -148,27 +147,24 @@ mod bezier {
&self,
state: &Self::State,
renderer: &Renderer,
_theme: &Theme,
theme: &Theme,
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Vec<Geometry> {
let content = self.state.cache.draw(
renderer,
bounds.size(),
|frame: &mut Frame| {
Curve::draw_all(self.curves, frame);
let content =
self.state.cache.draw(renderer, bounds.size(), |frame| {
Curve::draw_all(self.curves, frame, theme);
frame.stroke(
&Path::rectangle(Point::ORIGIN, frame.size()),
Stroke::default().with_width(2.0),
Stroke::default()
.with_width(2.0)
.with_color(theme.palette().text),
);
},
);
});
if let Some(pending) = state {
let pending_curve = pending.draw(renderer, bounds, cursor);
vec![content, pending_curve]
vec![content, pending.draw(renderer, theme, bounds, cursor)]
} else {
vec![content]
}
@ -196,7 +192,7 @@ mod bezier {
}
impl Curve {
fn draw_all(curves: &[Curve], frame: &mut Frame) {
fn draw_all(curves: &[Curve], frame: &mut Frame, theme: &Theme) {
let curves = Path::new(|p| {
for curve in curves {
p.move_to(curve.from);
@ -204,7 +200,12 @@ mod bezier {
}
});
frame.stroke(&curves, Stroke::default().with_width(2.0));
frame.stroke(
&curves,
Stroke::default()
.with_width(2.0)
.with_color(theme.palette().text),
);
}
}
@ -218,6 +219,7 @@ mod bezier {
fn draw(
&self,
renderer: &Renderer,
theme: &Theme,
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Geometry {
@ -227,7 +229,12 @@ mod bezier {
match *self {
Pending::One { from } => {
let line = Path::line(from, cursor_position);
frame.stroke(&line, Stroke::default().with_width(2.0));
frame.stroke(
&line,
Stroke::default()
.with_width(2.0)
.with_color(theme.palette().text),
);
}
Pending::Two { from, to } => {
let curve = Curve {
@ -236,7 +243,7 @@ mod bezier {
control: cursor_position,
};
Curve::draw_all(&[curve], &mut frame);
Curve::draw_all(&[curve], &mut frame, theme);
}
};
}

View file

@ -1,13 +1,12 @@
use iced::executor;
use iced::font::{self, Font};
use iced::theme;
use iced::widget::{checkbox, column, container, row, text};
use iced::{Application, Command, Element, Length, Settings, Theme};
use iced::widget::{center, checkbox, column, row, text};
use iced::{Element, Font};
const ICON_FONT: Font = Font::with_name("icons");
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::program("Checkbox - Iced", Example::update, Example::view)
.font(include_bytes!("../fonts/icons.ttf").as_slice())
.run()
}
#[derive(Default)]
@ -22,28 +21,10 @@ enum Message {
DefaultToggled(bool),
CustomToggled(bool),
StyledToggled(bool),
FontLoaded(Result<(), font::Error>),
}
impl Application for Example {
type Message = Message;
type Flags = ();
type Executor = executor::Default;
type Theme = Theme;
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
Self::default(),
font::load(include_bytes!("../fonts/icons.ttf").as_slice())
.map(Message::FontLoaded),
)
}
fn title(&self) -> String {
String::from("Checkbox - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl Example {
fn update(&mut self, message: Message) {
match message {
Message::DefaultToggled(default) => {
self.default = default;
@ -54,27 +35,23 @@ impl Application for Example {
Message::CustomToggled(custom) => {
self.custom = custom;
}
Message::FontLoaded(_) => (),
}
Command::none()
}
fn view(&self) -> Element<Message> {
let default_checkbox = checkbox("Default", self.default)
.on_toggle(Message::DefaultToggled);
let styled_checkbox = |label, style| {
let styled_checkbox = |label| {
checkbox(label, self.styled)
.on_toggle_maybe(self.default.then_some(Message::StyledToggled))
.style(style)
};
let checkboxes = row![
styled_checkbox("Primary", theme::Checkbox::Primary),
styled_checkbox("Secondary", theme::Checkbox::Secondary),
styled_checkbox("Success", theme::Checkbox::Success),
styled_checkbox("Danger", theme::Checkbox::Danger),
styled_checkbox("Primary").style(checkbox::primary),
styled_checkbox("Secondary").style(checkbox::secondary),
styled_checkbox("Success").style(checkbox::success),
styled_checkbox("Danger").style(checkbox::danger),
]
.spacing(20);
@ -91,11 +68,6 @@ impl Application for Example {
let content =
column![default_checkbox, checkboxes, custom_checkbox].spacing(20);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
}

View file

@ -10,3 +10,4 @@ iced.workspace = true
iced.features = ["canvas", "tokio", "debug"]
time = { version = "0.3", features = ["local-offset"] }
tracing-subscriber = "0.3"

View file

@ -1,17 +1,20 @@
use iced::executor;
use iced::alignment;
use iced::mouse;
use iced::widget::canvas::{stroke, Cache, Geometry, LineCap, Path, Stroke};
use iced::widget::{canvas, container};
use iced::{
Application, Color, Command, Element, Length, Point, Rectangle, Renderer,
Settings, Subscription, Theme, Vector,
Degrees, Element, Font, Length, Point, Rectangle, Renderer, Subscription,
Theme, Vector,
};
pub fn main() -> iced::Result {
Clock::run(Settings {
antialiasing: true,
..Settings::default()
})
tracing_subscriber::fmt::init();
iced::program("Clock - Iced", Clock::update, Clock::view)
.subscription(Clock::subscription)
.theme(Clock::theme)
.antialiasing(true)
.run()
}
struct Clock {
@ -24,28 +27,8 @@ enum Message {
Tick(time::OffsetDateTime),
}
impl Application for Clock {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Clock {
now: time::OffsetDateTime::now_local()
.unwrap_or_else(|_| time::OffsetDateTime::now_utc()),
clock: Cache::default(),
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Clock - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl Clock {
fn update(&mut self, message: Message) {
match message {
Message::Tick(local_time) => {
let now = local_time;
@ -56,8 +39,6 @@ impl Application for Clock {
}
}
}
Command::none()
}
fn view(&self) -> Element<Message> {
@ -80,6 +61,21 @@ impl Application for Clock {
)
})
}
fn theme(&self) -> Theme {
Theme::ALL[(self.now.unix_timestamp() as usize / 10) % Theme::ALL.len()]
.clone()
}
}
impl Default for Clock {
fn default() -> Self {
Self {
now: time::OffsetDateTime::now_local()
.unwrap_or_else(|_| time::OffsetDateTime::now_utc()),
clock: Cache::default(),
}
}
}
impl<Message> canvas::Program<Message> for Clock {
@ -89,16 +85,18 @@ impl<Message> canvas::Program<Message> for Clock {
&self,
_state: &Self::State,
renderer: &Renderer,
_theme: &Theme,
theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<Geometry> {
let clock = self.clock.draw(renderer, bounds.size(), |frame| {
let palette = theme.extended_palette();
let center = frame.center();
let radius = frame.width().min(frame.height()) / 2.0;
let background = Path::circle(center, radius);
frame.fill(&background, Color::from_rgb8(0x12, 0x93, 0xD8));
frame.fill(&background, palette.secondary.strong.color);
let short_hand =
Path::line(Point::ORIGIN, Point::new(0.0, -0.5 * radius));
@ -111,7 +109,7 @@ impl<Message> canvas::Program<Message> for Clock {
let thin_stroke = || -> Stroke {
Stroke {
width,
style: stroke::Style::Solid(Color::WHITE),
style: stroke::Style::Solid(palette.secondary.strong.text),
line_cap: LineCap::Round,
..Stroke::default()
}
@ -120,7 +118,7 @@ impl<Message> canvas::Program<Message> for Clock {
let wide_stroke = || -> Stroke {
Stroke {
width: width * 3.0,
style: stroke::Style::Solid(Color::WHITE),
style: stroke::Style::Solid(palette.secondary.strong.text),
line_cap: LineCap::Round,
..Stroke::default()
}
@ -139,8 +137,31 @@ impl<Message> canvas::Program<Message> for Clock {
});
frame.with_save(|frame| {
frame.rotate(hand_rotation(self.now.second(), 60));
let rotation = hand_rotation(self.now.second(), 60);
frame.rotate(rotation);
frame.stroke(&long_hand, thin_stroke());
let rotate_factor = if rotation < 180.0 { 1.0 } else { -1.0 };
frame.rotate(Degrees(-90.0 * rotate_factor));
frame.fill_text(canvas::Text {
content: theme.to_string(),
size: (radius / 15.0).into(),
position: Point::new(
(0.78 * radius) * rotate_factor,
-width * 2.0,
),
color: palette.secondary.strong.text,
horizontal_alignment: if rotate_factor > 0.0 {
alignment::Horizontal::Right
} else {
alignment::Horizontal::Left
},
vertical_alignment: alignment::Vertical::Bottom,
font: Font::MONOSPACE,
..canvas::Text::default()
});
});
});
@ -148,8 +169,8 @@ impl<Message> canvas::Program<Message> for Clock {
}
}
fn hand_rotation(n: u8, total: u8) -> f32 {
fn hand_rotation(n: u8, total: u8) -> Degrees {
let turns = n as f32 / total as f32;
2.0 * std::f32::consts::PI * turns
Degrees(360.0 * turns)
}

View file

@ -7,6 +7,6 @@ publish = false
[dependencies]
iced.workspace = true
iced.features = ["canvas", "palette"]
iced.features = ["canvas"]
palette.workspace = true

View file

@ -3,20 +3,23 @@ use iced::mouse;
use iced::widget::canvas::{self, Canvas, Frame, Geometry, Path};
use iced::widget::{column, row, text, Slider};
use iced::{
Color, Element, Length, Pixels, Point, Rectangle, Renderer, Sandbox,
Settings, Size, Vector,
};
use palette::{
self, convert::FromColor, rgb::Rgb, Darken, Hsl, Lighten, ShiftHue,
Color, Element, Font, Length, Pixels, Point, Rectangle, Renderer, Size,
Vector,
};
use palette::{convert::FromColor, rgb::Rgb, Darken, Hsl, Lighten, ShiftHue};
use std::marker::PhantomData;
use std::ops::RangeInclusive;
pub fn main() -> iced::Result {
ColorPalette::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program(
"Color Palette - Iced",
ColorPalette::update,
ColorPalette::view,
)
.theme(ColorPalette::theme)
.default_font(Font::MONOSPACE)
.antialiasing(true)
.run()
}
#[derive(Default)]
@ -40,17 +43,7 @@ pub enum Message {
LchColorChanged(palette::Lch),
}
impl Sandbox for ColorPalette {
type Message = Message;
fn new() -> Self {
Self::default()
}
fn title(&self) -> String {
String::from("Color palette - Iced")
}
impl ColorPalette {
fn update(&mut self, message: Message) {
let srgb = match message {
Message::RgbColorChanged(rgb) => Rgb::from(rgb),
@ -87,6 +80,19 @@ impl Sandbox for ColorPalette {
.spacing(10)
.into()
}
fn theme(&self) -> iced::Theme {
iced::Theme::custom(
String::from("Custom"),
iced::theme::Palette {
background: self.theme.base,
primary: *self.theme.lower.first().unwrap(),
text: *self.theme.higher.last().unwrap(),
success: *self.theme.lower.last().unwrap(),
danger: *self.theme.higher.last().unwrap(),
},
)
}
}
#[derive(Debug)]
@ -150,7 +156,7 @@ impl Theme {
.into()
}
fn draw(&self, frame: &mut Frame) {
fn draw(&self, frame: &mut Frame, text_color: Color) {
let pad = 20.0;
let box_size = Size {
@ -169,6 +175,7 @@ impl Theme {
horizontal_alignment: alignment::Horizontal::Center,
vertical_alignment: alignment::Vertical::Top,
size: Pixels(15.0),
color: text_color,
..canvas::Text::default()
};
@ -246,12 +253,14 @@ impl<Message> canvas::Program<Message> for Theme {
&self,
_state: &Self::State,
renderer: &Renderer,
_theme: &iced::Theme,
theme: &iced::Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<Geometry> {
let theme = self.canvas_cache.draw(renderer, bounds.size(), |frame| {
self.draw(frame);
let palette = theme.extended_palette();
self.draw(frame, palette.background.base.text);
});
vec![theme]
@ -308,7 +317,7 @@ impl<C: ColorSpace + Copy> ColorPicker<C> {
slider(cr1, c1, move |v| C::new(v, c2, c3)),
slider(cr2, c2, move |v| C::new(c1, v, c3)),
slider(cr3, c3, move |v| C::new(c1, c2, v)),
text(color.to_string()).width(185).size(14),
text(color.to_string()).width(185).size(12),
]
.spacing(10)
.align_items(Alignment::Center)

View file

@ -1,10 +1,10 @@
use iced::widget::{
column, combo_box, container, scrollable, text, vertical_space,
center, column, combo_box, scrollable, text, vertical_space,
};
use iced::{Alignment, Element, Length, Sandbox, Settings};
use iced::{Alignment, Element, Length};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Combo Box - Iced", Example::update, Example::view)
}
struct Example {
@ -20,9 +20,7 @@ enum Message {
Closed,
}
impl Sandbox for Example {
type Message = Message;
impl Example {
fn new() -> Self {
Self {
languages: combo_box::State::new(Language::ALL.to_vec()),
@ -31,10 +29,6 @@ impl Sandbox for Example {
}
}
fn title(&self) -> String {
String::from("Combo box - Iced")
}
fn update(&mut self, message: Message) {
match message {
Message::Selected(language) => {
@ -74,12 +68,13 @@ impl Sandbox for Example {
.align_items(Alignment::Center)
.spacing(10);
container(scrollable(content))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(scrollable(content)).into()
}
}
impl Default for Example {
fn default() -> Self {
Example::new()
}
}

View file

@ -1,10 +1,10 @@
use iced::widget::container;
use iced::{Element, Length, Sandbox, Settings};
use iced::widget::center;
use iced::Element;
use numeric_input::numeric_input;
pub fn main() -> iced::Result {
Component::run(Settings::default())
iced::run("Component - Iced", Component::update, Component::view)
}
#[derive(Default)]
@ -17,17 +17,7 @@ enum Message {
NumericInputChanged(Option<u32>),
}
impl Sandbox for Component {
type Message = Message;
fn new() -> Self {
Self::default()
}
fn title(&self) -> String {
String::from("Component - Iced")
}
impl Component {
fn update(&mut self, message: Message) {
match message {
Message::NumericInputChanged(value) => {
@ -37,10 +27,8 @@ impl Sandbox for Component {
}
fn view(&self) -> Element<Message> {
container(numeric_input(self.value, Message::NumericInputChanged))
center(numeric_input(self.value, Message::NumericInputChanged))
.padding(20)
.height(Length::Fill)
.center_y()
.into()
}
}
@ -81,7 +69,10 @@ mod numeric_input {
}
}
impl<Message> Component<Message> for NumericInput<Message> {
impl<Message, Theme> Component<Message, Theme> for NumericInput<Message>
where
Theme: text::Catalog + button::Catalog + text_input::Catalog + 'static,
{
type State = ();
type Event = Event;
@ -111,7 +102,7 @@ mod numeric_input {
}
}
fn view(&self, _state: &Self::State) -> Element<Event> {
fn view(&self, _state: &Self::State) -> Element<'_, Event, Theme> {
let button = |label, on_press| {
button(
text(label)
@ -152,8 +143,10 @@ mod numeric_input {
}
}
impl<'a, Message> From<NumericInput<Message>> for Element<'a, Message>
impl<'a, Message, Theme> From<NumericInput<Message>>
for Element<'a, Message, Theme>
where
Theme: text::Catalog + button::Catalog + text_input::Catalog + 'static,
Message: 'a,
{
fn from(numeric_input: NumericInput<Message>) -> Self {

View file

@ -1,50 +1,40 @@
use iced::widget::{button, column, text};
use iced::{Alignment, Element, Sandbox, Settings};
use iced::widget::{button, column, text, Column};
use iced::Alignment;
pub fn main() -> iced::Result {
Counter::run(Settings::default())
iced::run("A cool counter", Counter::update, Counter::view)
}
#[derive(Default)]
struct Counter {
value: i32,
value: i64,
}
#[derive(Debug, Clone, Copy)]
enum Message {
IncrementPressed,
DecrementPressed,
Increment,
Decrement,
}
impl Sandbox for Counter {
type Message = Message;
fn new() -> Self {
Self { value: 0 }
}
fn title(&self) -> String {
String::from("Counter - Iced")
}
impl Counter {
fn update(&mut self, message: Message) {
match message {
Message::IncrementPressed => {
Message::Increment => {
self.value += 1;
}
Message::DecrementPressed => {
Message::Decrement => {
self.value -= 1;
}
}
}
fn view(&self) -> Element<Message> {
fn view(&self) -> Column<Message> {
column![
button("Increment").on_press(Message::IncrementPressed),
button("Increment").on_press(Message::Increment),
text(self.value).size(50),
button("Decrement").on_press(Message::DecrementPressed)
button("Decrement").on_press(Message::Decrement)
]
.padding(20)
.align_items(Alignment::Center)
.into()
}
}

View file

@ -81,13 +81,11 @@ mod quad {
}
}
use iced::widget::{column, container, slider, text};
use iced::{
Alignment, Color, Element, Length, Sandbox, Settings, Shadow, Vector,
};
use iced::widget::{center, column, slider, text};
use iced::{Alignment, Color, Element, Shadow, Vector};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Custom Quad - Iced", Example::update, Example::view)
}
struct Example {
@ -109,9 +107,7 @@ enum Message {
ShadowBlurRadiusChanged(f32),
}
impl Sandbox for Example {
type Message = Message;
impl Example {
fn new() -> Self {
Self {
radius: [50.0; 4],
@ -124,10 +120,6 @@ impl Sandbox for Example {
}
}
fn title(&self) -> String {
String::from("Custom widget - Iced")
}
fn update(&mut self, message: Message) {
let [tl, tr, br, bl] = self.radius;
match message {
@ -195,11 +187,12 @@ impl Sandbox for Example {
.max_width(500)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
}
impl Default for Example {
fn default() -> Self {
Self::new()
}
}

View file

@ -2,18 +2,16 @@ mod scene;
use scene::Scene;
use iced::executor;
use iced::time::Instant;
use iced::widget::shader::wgpu;
use iced::widget::{checkbox, column, container, row, shader, slider, text};
use iced::widget::{center, checkbox, column, row, shader, slider, text};
use iced::window;
use iced::{
Alignment, Application, Color, Command, Element, Length, Subscription,
Theme,
};
use iced::{Alignment, Color, Element, Length, Subscription};
fn main() -> iced::Result {
IcedCubes::run(iced::Settings::default())
iced::program("Custom Shader - Iced", IcedCubes::update, IcedCubes::view)
.subscription(IcedCubes::subscription)
.run()
}
struct IcedCubes {
@ -30,27 +28,15 @@ enum Message {
LightColorChanged(Color),
}
impl Application for IcedCubes {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, Command<Self::Message>) {
(
Self {
start: Instant::now(),
scene: Scene::new(),
},
Command::none(),
)
impl IcedCubes {
fn new() -> Self {
Self {
start: Instant::now(),
scene: Scene::new(),
}
}
fn title(&self) -> String {
"Iced Cubes".to_string()
}
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
fn update(&mut self, message: Message) {
match message {
Message::CubeAmountChanged(amount) => {
self.scene.change_amount(amount);
@ -68,11 +54,9 @@ impl Application for IcedCubes {
self.scene.light_color = color;
}
}
Command::none()
}
fn view(&self) -> Element<'_, Self::Message> {
fn view(&self) -> Element<'_, Message> {
let top_controls = row![
control(
"Amount",
@ -139,19 +123,20 @@ impl Application for IcedCubes {
let shader =
shader(&self.scene).width(Length::Fill).height(Length::Fill);
container(column![shader, controls].align_items(Alignment::Center))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(column![shader, controls].align_items(Alignment::Center)).into()
}
fn subscription(&self) -> Subscription<Self::Message> {
fn subscription(&self) -> Subscription<Message> {
window::frames().map(Message::Tick)
}
}
impl Default for IcedCubes {
fn default() -> Self {
Self::new()
}
}
fn control<'a>(
label: &'static str,
control: impl Into<Element<'a, Message>>,

View file

@ -9,8 +9,8 @@ use pipeline::cube::{self, Cube};
use iced::mouse;
use iced::time::Duration;
use iced::widget::shader;
use iced::{Color, Rectangle, Size};
use iced::widget::shader::{self, Viewport};
use iced::{Color, Rectangle};
use glam::Vec3;
use rand::Rng;
@ -130,25 +130,29 @@ impl Primitive {
impl shader::Primitive for Primitive {
fn prepare(
&self,
format: wgpu::TextureFormat,
device: &wgpu::Device,
queue: &wgpu::Queue,
_bounds: Rectangle,
target_size: Size<u32>,
_scale_factor: f32,
format: wgpu::TextureFormat,
storage: &mut shader::Storage,
_bounds: &Rectangle,
viewport: &Viewport,
) {
if !storage.has::<Pipeline>() {
storage.store(Pipeline::new(device, queue, format, target_size));
storage.store(Pipeline::new(
device,
queue,
format,
viewport.physical_size(),
));
}
let pipeline = storage.get_mut::<Pipeline>().unwrap();
//upload data to GPU
// Upload data to GPU
pipeline.update(
device,
queue,
target_size,
viewport.physical_size(),
&self.uniforms,
self.cubes.len(),
&self.cubes,
@ -157,20 +161,19 @@ impl shader::Primitive for Primitive {
fn render(
&self,
encoder: &mut wgpu::CommandEncoder,
storage: &shader::Storage,
target: &wgpu::TextureView,
_target_size: Size<u32>,
viewport: Rectangle<u32>,
encoder: &mut wgpu::CommandEncoder,
clip_bounds: &Rectangle<u32>,
) {
//at this point our pipeline should always be initialized
// At this point our pipeline should always be initialized
let pipeline = storage.get::<Pipeline>().unwrap();
//render primitive
// Render primitive
pipeline.render(
target,
encoder,
viewport,
*clip_bounds,
self.cubes.len() as u32,
self.show_depth_buffer,
);

View file

@ -62,7 +62,7 @@ mod circle {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border: Border::with_radius(self.radius),
border: Border::rounded(self.radius),
..renderer::Quad::default()
},
Color::BLACK,
@ -82,11 +82,11 @@ mod circle {
}
use circle::circle;
use iced::widget::{column, container, slider, text};
use iced::{Alignment, Element, Length, Sandbox, Settings};
use iced::widget::{center, column, slider, text};
use iced::{Alignment, Element};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Custom Widget - Iced", Example::update, Example::view)
}
struct Example {
@ -98,17 +98,11 @@ enum Message {
RadiusChanged(f32),
}
impl Sandbox for Example {
type Message = Message;
impl Example {
fn new() -> Self {
Example { radius: 50.0 }
}
fn title(&self) -> String {
String::from("Custom widget - Iced")
}
fn update(&mut self, message: Message) {
match message {
Message::RadiusChanged(radius) => {
@ -128,11 +122,12 @@ impl Sandbox for Example {
.max_width(500)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
}
impl Default for Example {
fn default() -> Self {
Self::new()
}
}

View file

@ -12,12 +12,6 @@ pub fn file<I: 'static + Hash + Copy + Send + Sync, T: ToString>(
})
}
#[derive(Debug, Hash, Clone)]
pub struct Download<I> {
id: I,
url: String,
}
async fn download<I: Copy>(id: I, state: State) -> ((I, Progress), State) {
match state {
State::Ready(url) => {

View file

@ -1,14 +1,12 @@
use iced::executor;
use iced::widget::{button, column, container, progress_bar, text, Column};
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
Theme,
};
mod download;
use iced::widget::{button, center, column, progress_bar, text, Column};
use iced::{Alignment, Element, Subscription};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::program("Download Progress - Iced", Example::update, Example::view)
.subscription(Example::subscription)
.run()
}
#[derive(Debug)]
@ -24,27 +22,15 @@ pub enum Message {
DownloadProgressed((usize, download::Progress)),
}
impl Application for Example {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Example, Command<Message>) {
(
Example {
downloads: vec![Download::new(0)],
last_id: 0,
},
Command::none(),
)
impl Example {
fn new() -> Self {
Self {
downloads: vec![Download::new(0)],
last_id: 0,
}
}
fn title(&self) -> String {
String::from("Download progress - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
fn update(&mut self, message: Message) {
match message {
Message::Add => {
self.last_id += 1;
@ -63,9 +49,7 @@ impl Application for Example {
download.progress(progress);
}
}
};
Command::none()
}
}
fn subscription(&self) -> Subscription<Message> {
@ -83,13 +67,13 @@ impl Application for Example {
.spacing(20)
.align_items(Alignment::End);
container(downloads)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.padding(20)
.into()
center(downloads).padding(20).into()
}
}
impl Default for Example {
fn default() -> Self {
Self::new()
}
}

View file

@ -1,15 +1,10 @@
use iced::executor;
use iced::highlighter::{self, Highlighter};
use iced::keyboard;
use iced::theme::{self, Theme};
use iced::widget::{
button, column, container, horizontal_space, pick_list, row, text,
text_editor, tooltip,
};
use iced::{
Alignment, Application, Command, Element, Font, Length, Settings,
Subscription,
};
use iced::{Alignment, Command, Element, Font, Length, Subscription, Theme};
use std::ffi;
use std::io;
@ -17,11 +12,13 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
pub fn main() -> iced::Result {
Editor::run(Settings {
fonts: vec![include_bytes!("../fonts/icons.ttf").as_slice().into()],
default_font: Font::MONOSPACE,
..Settings::default()
})
iced::program("Editor - Iced", Editor::update, Editor::view)
.load(Editor::load)
.subscription(Editor::subscription)
.theme(Editor::theme)
.font(include_bytes!("../fonts/icons.ttf").as_slice())
.default_font(Font::MONOSPACE)
.run()
}
struct Editor {
@ -43,27 +40,22 @@ enum Message {
FileSaved(Result<PathBuf, Error>),
}
impl Application for Editor {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
Self {
file: None,
content: text_editor::Content::new(),
theme: highlighter::Theme::SolarizedDark,
is_loading: true,
is_dirty: false,
},
Command::perform(load_file(default_file()), Message::FileOpened),
)
impl Editor {
fn new() -> Self {
Self {
file: None,
content: text_editor::Content::new(),
theme: highlighter::Theme::SolarizedDark,
is_loading: true,
is_dirty: false,
}
}
fn title(&self) -> String {
String::from("Editor - Iced")
fn load() -> Command<Message> {
Command::perform(
load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))),
Message::FileOpened,
)
}
fn update(&mut self, message: Message) -> Command<Message> {
@ -222,16 +214,18 @@ impl Application for Editor {
}
}
impl Default for Editor {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub enum Error {
DialogClosed,
IoError(io::ErrorKind),
}
fn default_file() -> PathBuf {
PathBuf::from(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR")))
}
async fn open_file() -> Result<(PathBuf, Arc<String>), Error> {
let picked_file = rfd::AsyncFileDialog::new()
.set_title("Open a text file...")
@ -239,10 +233,14 @@ async fn open_file() -> Result<(PathBuf, Arc<String>), Error> {
.await
.ok_or(Error::DialogClosed)?;
load_file(picked_file.path().to_owned()).await
load_file(picked_file).await
}
async fn load_file(path: PathBuf) -> Result<(PathBuf, Arc<String>), Error> {
async fn load_file(
path: impl Into<PathBuf>,
) -> Result<(PathBuf, Arc<String>), Error> {
let path = path.into();
let contents = tokio::fs::read_to_string(&path)
.await
.map(Arc::new)
@ -279,7 +277,7 @@ fn action<'a, Message: Clone + 'a>(
label: &'a str,
on_press: Option<Message>,
) -> Element<'a, Message> {
let action = button(container(content).width(30).center_x());
let action = button(container(content).center_x().width(30));
if let Some(on_press) = on_press {
tooltip(
@ -287,10 +285,10 @@ fn action<'a, Message: Clone + 'a>(
label,
tooltip::Position::FollowCursor,
)
.style(theme::Container::Box)
.style(container::rounded_box)
.into()
} else {
action.style(theme::Button::Secondary).into()
action.style(button::secondary).into()
}
}

View file

@ -1,21 +1,14 @@
use iced::alignment;
use iced::event::{self, Event};
use iced::executor;
use iced::widget::{button, checkbox, container, text, Column};
use iced::widget::{button, center, checkbox, text, Column};
use iced::window;
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
Theme,
};
use iced::{Alignment, Command, Element, Length, Subscription};
pub fn main() -> iced::Result {
Events::run(Settings {
window: window::Settings {
exit_on_close_request: false,
..window::Settings::default()
},
..Settings::default()
})
iced::program("Events - Iced", Events::update, Events::view)
.subscription(Events::subscription)
.exit_on_close_request(false)
.run()
}
#[derive(Debug, Default)]
@ -31,20 +24,7 @@ enum Message {
Exit,
}
impl Application for Events {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Events, Command<Message>) {
(Events::default(), Command::none())
}
fn title(&self) -> String {
String::from("Events - Iced")
}
impl Events {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::EventOccurred(event) if self.enabled => {
@ -104,11 +84,6 @@ impl Application for Events {
.push(toggle)
.push(exit);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
}

View file

@ -1,10 +1,9 @@
use iced::executor;
use iced::widget::{button, column, container};
use iced::widget::{button, center, column};
use iced::window;
use iced::{Alignment, Application, Command, Element, Length, Settings, Theme};
use iced::{Alignment, Command, Element};
pub fn main() -> iced::Result {
Exit::run(Settings::default())
iced::program("Exit - Iced", Exit::update, Exit::view).run()
}
#[derive(Default)]
@ -18,20 +17,7 @@ enum Message {
Exit,
}
impl Application for Exit {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(Self::default(), Command::none())
}
fn title(&self) -> String {
String::from("Exit - Iced")
}
impl Exit {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Confirm => window::close(window::Id::MAIN),
@ -60,12 +46,6 @@ impl Application for Exit {
.spacing(10)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
center(content).padding(20).into()
}
}

View file

@ -0,0 +1,10 @@
[package]
name = "ferris"
version = "0.1.0"
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
edition = "2021"
publish = false
[dependencies]
iced.workspace = true
iced.features = ["image", "tokio", "debug"]

211
examples/ferris/src/main.rs Normal file
View file

@ -0,0 +1,211 @@
use iced::time::Instant;
use iced::widget::{
center, checkbox, column, container, image, pick_list, row, slider, text,
};
use iced::window;
use iced::{
Alignment, Color, ContentFit, Degrees, Element, Length, Radians, Rotation,
Subscription, Theme,
};
pub fn main() -> iced::Result {
iced::program("Ferris - Iced", Image::update, Image::view)
.subscription(Image::subscription)
.theme(|_| Theme::TokyoNight)
.run()
}
struct Image {
width: f32,
opacity: f32,
rotation: Rotation,
content_fit: ContentFit,
spin: bool,
last_tick: Instant,
}
#[derive(Debug, Clone, Copy)]
enum Message {
WidthChanged(f32),
OpacityChanged(f32),
RotationStrategyChanged(RotationStrategy),
RotationChanged(Degrees),
ContentFitChanged(ContentFit),
SpinToggled(bool),
RedrawRequested(Instant),
}
impl Image {
fn update(&mut self, message: Message) {
match message {
Message::WidthChanged(width) => {
self.width = width;
}
Message::OpacityChanged(opacity) => {
self.opacity = opacity;
}
Message::RotationStrategyChanged(strategy) => {
self.rotation = match strategy {
RotationStrategy::Floating => {
Rotation::Floating(self.rotation.radians())
}
RotationStrategy::Solid => {
Rotation::Solid(self.rotation.radians())
}
};
}
Message::RotationChanged(rotation) => {
self.rotation = match self.rotation {
Rotation::Floating(_) => {
Rotation::Floating(rotation.into())
}
Rotation::Solid(_) => Rotation::Solid(rotation.into()),
};
}
Message::ContentFitChanged(content_fit) => {
self.content_fit = content_fit;
}
Message::SpinToggled(spin) => {
self.spin = spin;
self.last_tick = Instant::now();
}
Message::RedrawRequested(now) => {
const ROTATION_SPEED: Degrees = Degrees(360.0);
let delta = (now - self.last_tick).as_millis() as f32 / 1_000.0;
*self.rotation.radians_mut() = (self.rotation.radians()
+ ROTATION_SPEED * delta)
% (2.0 * Radians::PI);
self.last_tick = now;
}
}
}
fn subscription(&self) -> Subscription<Message> {
if self.spin {
window::frames().map(Message::RedrawRequested)
} else {
Subscription::none()
}
}
fn view(&self) -> Element<Message> {
let i_am_ferris = column![
"Hello!",
Element::from(
image(format!(
"{}/../tour/images/ferris.png",
env!("CARGO_MANIFEST_DIR")
))
.width(self.width)
.content_fit(self.content_fit)
.rotation(self.rotation)
.opacity(self.opacity)
)
.explain(Color::WHITE),
"I am Ferris!"
]
.spacing(20)
.align_items(Alignment::Center);
let fit = row![
pick_list(
[
ContentFit::Contain,
ContentFit::Cover,
ContentFit::Fill,
ContentFit::None,
ContentFit::ScaleDown
],
Some(self.content_fit),
Message::ContentFitChanged
)
.width(Length::Fill),
pick_list(
[RotationStrategy::Floating, RotationStrategy::Solid],
Some(match self.rotation {
Rotation::Floating(_) => RotationStrategy::Floating,
Rotation::Solid(_) => RotationStrategy::Solid,
}),
Message::RotationStrategyChanged,
)
.width(Length::Fill),
]
.spacing(10)
.align_items(Alignment::End);
let properties = row![
with_value(
slider(100.0..=500.0, self.width, Message::WidthChanged),
format!("Width: {}px", self.width)
),
with_value(
slider(0.0..=1.0, self.opacity, Message::OpacityChanged)
.step(0.01),
format!("Opacity: {:.2}", self.opacity)
),
with_value(
row![
slider(
Degrees::RANGE,
self.rotation.degrees(),
Message::RotationChanged
),
checkbox("Spin!", self.spin)
.text_size(12)
.on_toggle(Message::SpinToggled)
.size(12)
]
.spacing(10)
.align_items(Alignment::Center),
format!("Rotation: {:.0}°", f32::from(self.rotation.degrees()))
)
]
.spacing(10)
.align_items(Alignment::End);
container(column![fit, center(i_am_ferris), properties].spacing(10))
.padding(10)
.into()
}
}
impl Default for Image {
fn default() -> Self {
Self {
width: 300.0,
opacity: 1.0,
rotation: Rotation::default(),
content_fit: ContentFit::default(),
spin: false,
last_tick: Instant::now(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RotationStrategy {
Floating,
Solid,
}
impl std::fmt::Display for RotationStrategy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Floating => "Floating",
Self::Solid => "Solid",
})
}
}
fn with_value<'a>(
control: impl Into<Element<'a, Message>>,
value: String,
) -> Element<'a, Message> {
column![control.into(), text(value).size(12).line_height(1.0)]
.spacing(2)
.align_items(Alignment::Center)
.into()
}

View file

@ -5,32 +5,24 @@ mod preset;
use grid::Grid;
use preset::Preset;
use iced::executor;
use iced::theme::{self, Theme};
use iced::time;
use iced::widget::{
button, checkbox, column, container, pick_list, row, slider, text,
};
use iced::window;
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
};
use iced::{Alignment, Command, Element, Length, Subscription, Theme};
use std::time::Duration;
pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
GameOfLife::run(Settings {
antialiasing: true,
window: window::Settings {
position: window::Position::Centered,
..window::Settings::default()
},
..Settings::default()
})
iced::program("Game of Life - Iced", GameOfLife::update, GameOfLife::view)
.subscription(GameOfLife::subscription)
.theme(|_| Theme::Dark)
.antialiasing(true)
.centered()
.run()
}
#[derive(Default)]
struct GameOfLife {
grid: Grid,
is_playing: bool,
@ -52,24 +44,16 @@ enum Message {
PresetPicked(Preset),
}
impl Application for GameOfLife {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Self {
speed: 5,
..Self::default()
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Game of Life - Iced")
impl GameOfLife {
fn new() -> Self {
Self {
grid: Grid::default(),
is_playing: false,
queued_ticks: 0,
speed: 5,
next_speed: None,
version: 0,
}
}
fn update(&mut self, message: Message) -> Command<Message> {
@ -154,9 +138,11 @@ impl Application for GameOfLife {
.height(Length::Fill)
.into()
}
}
fn theme(&self) -> Theme {
Theme::Dark
impl Default for GameOfLife {
fn default() -> Self {
Self::new()
}
}
@ -171,7 +157,7 @@ fn view_controls<'a>(
.on_press(Message::TogglePlayback),
button("Next")
.on_press(Message::Next)
.style(theme::Button::Secondary),
.style(button::secondary),
]
.spacing(10);
@ -185,17 +171,14 @@ fn view_controls<'a>(
row![
playback_controls,
speed_controls,
checkbox("Grid", is_grid_enabled)
.on_toggle(Message::ToggleGrid)
.size(16)
.spacing(5)
.text_size(16),
pick_list(preset::ALL, Some(preset), Message::PresetPicked)
.padding(8)
.text_size(16),
button("Clear")
.on_press(Message::Clear)
.style(theme::Button::Destructive),
checkbox("Grid", is_grid_enabled).on_toggle(Message::ToggleGrid),
row![
pick_list(preset::ALL, Some(preset), Message::PresetPicked),
button("Clear")
.on_press(Message::Clear)
.style(button::danger)
]
.spacing(10)
]
.padding(10)
.spacing(20)
@ -619,9 +602,7 @@ mod grid {
frame.into_geometry()
};
if self.scaling < 0.2 || !self.show_lines {
vec![life, overlay]
} else {
if self.scaling >= 0.2 && self.show_lines {
let grid =
self.grid_cache.draw(renderer, bounds.size(), |frame| {
frame.translate(center);
@ -658,6 +639,8 @@ mod grid {
});
vec![life, grid, overlay]
} else {
vec![life, overlay]
}
}

View file

@ -6,7 +6,10 @@ mod rainbow {
use iced::advanced::renderer;
use iced::advanced::widget::{self, Widget};
use iced::mouse;
use iced::{Element, Length, Rectangle, Renderer, Size, Theme, Vector};
use iced::{
Element, Length, Rectangle, Renderer, Size, Theme, Transformation,
Vector,
};
#[derive(Debug, Clone, Copy, Default)]
pub struct Rainbow;
@ -44,7 +47,9 @@ mod rainbow {
cursor: mouse::Cursor,
_viewport: &Rectangle,
) {
use iced::advanced::graphics::mesh::{self, Mesh, SolidVertex2D};
use iced::advanced::graphics::mesh::{
self, Mesh, Renderer as _, SolidVertex2D,
};
use iced::advanced::Renderer as _;
let bounds = layout.bounds();
@ -77,7 +82,6 @@ mod rainbow {
let posn_l = [0.0, bounds.height / 2.0];
let mesh = Mesh::Solid {
size: bounds.size(),
buffers: mesh::Indexed {
vertices: vec![
SolidVertex2D {
@ -128,6 +132,8 @@ mod rainbow {
0, 8, 1, // L
],
},
transformation: Transformation::IDENTITY,
clip_bounds: Rectangle::INFINITE,
};
renderer.with_translation(
@ -147,51 +153,30 @@ mod rainbow {
}
use iced::widget::{column, container, scrollable};
use iced::{Element, Length, Sandbox, Settings};
use iced::Element;
use rainbow::rainbow;
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Custom 2D Geometry - Iced", |_: &mut _, _| {}, view)
}
struct Example;
impl Sandbox for Example {
type Message = ();
fn new() -> Self {
Self
}
fn title(&self) -> String {
String::from("Custom 2D geometry - Iced")
}
fn update(&mut self, _: ()) {}
fn view(&self) -> Element<()> {
let content = column![
rainbow(),
"In this example we draw a custom widget Rainbow, using \
fn view(_state: &()) -> Element<'_, ()> {
let content = column![
rainbow(),
"In this example we draw a custom widget Rainbow, using \
the Mesh2D primitive. This primitive supplies a list of \
triangles, expressed as vertices and indices.",
"Move your cursor over it, and see the center vertex \
"Move your cursor over it, and see the center vertex \
follow you!",
"Every Vertex2D defines its own color. You could use the \
"Every Vertex2D defines its own color. You could use the \
Mesh2D primitive to render virtually any two-dimensional \
geometry for your widget.",
]
.padding(20)
.spacing(20)
.max_width(500);
]
.padding(20)
.spacing(20)
.max_width(500);
let scrollable =
scrollable(container(content).width(Length::Fill).center_x());
let scrollable = scrollable(container(content).center_x());
container(scrollable)
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.into()
}
container(scrollable).center_y().into()
}

View file

@ -1,23 +1,17 @@
use iced::application;
use iced::theme::{self, Theme};
use iced::gradient;
use iced::program;
use iced::widget::{
checkbox, column, container, horizontal_space, row, slider, text,
};
use iced::{gradient, window};
use iced::{
Alignment, Background, Color, Element, Length, Radians, Sandbox, Settings,
};
use iced::{Alignment, Color, Element, Length, Radians, Theme};
pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
Gradient::run(Settings {
window: window::Settings {
transparent: true,
..Default::default()
},
..Default::default()
})
iced::program("Gradient - Iced", Gradient::update, Gradient::view)
.style(Gradient::style)
.transparent(true)
.run()
}
#[derive(Debug, Clone, Copy)]
@ -36,9 +30,7 @@ enum Message {
TransparentToggled(bool),
}
impl Sandbox for Gradient {
type Message = Message;
impl Gradient {
fn new() -> Self {
Self {
start: Color::WHITE,
@ -48,10 +40,6 @@ impl Sandbox for Gradient {
}
}
fn title(&self) -> String {
String::from("Gradient")
}
fn update(&mut self, message: Message) {
match message {
Message::StartChanged(color) => self.start = color,
@ -72,19 +60,15 @@ impl Sandbox for Gradient {
} = *self;
let gradient_box = container(horizontal_space())
.width(Length::Fill)
.height(Length::Fill)
.style(move |_: &_| {
.style(move |_theme| {
let gradient = gradient::Linear::new(angle)
.add_stop(0.0, start)
.add_stop(1.0, end)
.into();
.add_stop(1.0, end);
container::Appearance {
background: Some(Background::Gradient(gradient)),
..Default::default()
}
});
gradient.into()
})
.width(Length::Fill)
.height(Length::Fill);
let angle_picker = row![
text("Angle").width(64),
@ -111,20 +95,26 @@ impl Sandbox for Gradient {
.into()
}
fn style(&self) -> theme::Application {
fn style(&self, theme: &Theme) -> program::Appearance {
use program::DefaultStyle;
if self.transparent {
theme::Application::custom(|theme: &Theme| {
application::Appearance {
background_color: Color::TRANSPARENT,
text_color: theme.palette().text,
}
})
program::Appearance {
background_color: Color::TRANSPARENT,
text_color: theme.palette().text,
}
} else {
theme::Application::Default
Theme::default_style(theme)
}
}
}
impl Default for Gradient {
fn default() -> Self {
Self::new()
}
}
fn color_picker(label: &str, color: Color) -> Element<'_, Color> {
row![
text(label).width(64),

View file

@ -10,25 +10,8 @@ The __[`main`]__ file contains all the code of the example.
You can run it with `cargo run`:
```
cargo run --package integration_wgpu
cargo run --package integration
```
### How to run this example with WebGL backend
NOTE: Currently, WebGL backend is is still experimental, so expect bugs.
```sh
# 0. Install prerequisites
cargo install wasm-bindgen-cli https
# 1. cd to the current folder
# 2. Compile wasm module
cargo build -p integration_wgpu --target wasm32-unknown-unknown
# 3. Invoke wasm-bindgen
wasm-bindgen ../../target/wasm32-unknown-unknown/debug/integration_wgpu.wasm --out-dir . --target web --no-typescript
# 4. run http server
http
# 5. Open 127.0.0.1:8000 in browser
```
[`main`]: src/main.rs
[`wgpu`]: https://github.com/gfx-rs/wgpu

View file

@ -1,21 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>Iced - wgpu + WebGL integration</title>
</head>
<body>
<h1>integration_wgpu</h1>
<canvas id="iced_canvas"></canvas>
<script type="module">
import init from "./integration.js";
init('./integration_bg.wasm');
</script>
<style>
body {
width: 100%;
text-align: center;
}
</style>
</body>
</html>

View file

@ -1,25 +1,25 @@
use iced_wgpu::Renderer;
use iced_widget::{slider, text_input, Column, Row, Text};
use iced_winit::core::{Alignment, Color, Element, Length};
use iced_widget::{column, container, row, slider, text, text_input};
use iced_winit::core::alignment;
use iced_winit::core::{Color, Element, Length, Theme};
use iced_winit::runtime::{Command, Program};
use iced_winit::style::Theme;
pub struct Controls {
background_color: Color,
text: String,
input: String,
}
#[derive(Debug, Clone)]
pub enum Message {
BackgroundColorChanged(Color),
TextChanged(String),
InputChanged(String),
}
impl Controls {
pub fn new() -> Controls {
Controls {
background_color: Color::BLACK,
text: String::default(),
input: String::default(),
}
}
@ -38,8 +38,8 @@ impl Program for Controls {
Message::BackgroundColorChanged(color) => {
self.background_color = color;
}
Message::TextChanged(text) => {
self.text = text;
Message::InputChanged(input) => {
self.input = input;
}
}
@ -48,60 +48,48 @@ impl Program for Controls {
fn view(&self) -> Element<Message, Theme, Renderer> {
let background_color = self.background_color;
let text = &self.text;
let sliders = Row::new()
.width(500)
.spacing(20)
.push(
slider(0.0..=1.0, background_color.r, move |r| {
Message::BackgroundColorChanged(Color {
r,
..background_color
})
let sliders = row![
slider(0.0..=1.0, background_color.r, move |r| {
Message::BackgroundColorChanged(Color {
r,
..background_color
})
.step(0.01),
)
.push(
slider(0.0..=1.0, background_color.g, move |g| {
Message::BackgroundColorChanged(Color {
g,
..background_color
})
})
.step(0.01),
slider(0.0..=1.0, background_color.g, move |g| {
Message::BackgroundColorChanged(Color {
g,
..background_color
})
.step(0.01),
)
.push(
slider(0.0..=1.0, background_color.b, move |b| {
Message::BackgroundColorChanged(Color {
b,
..background_color
})
})
.step(0.01),
slider(0.0..=1.0, background_color.b, move |b| {
Message::BackgroundColorChanged(Color {
b,
..background_color
})
.step(0.01),
);
})
.step(0.01),
]
.width(500)
.spacing(20);
Row::new()
.height(Length::Fill)
.align_items(Alignment::End)
.push(
Column::new().align_items(Alignment::End).push(
Column::new()
.padding(10)
.spacing(10)
.push(Text::new("Background color").style(Color::WHITE))
.push(sliders)
.push(
Text::new(format!("{background_color:?}"))
.size(14)
.style(Color::WHITE),
)
.push(
text_input("Placeholder", text)
.on_input(Message::TextChanged),
),
),
)
.into()
container(
column![
text("Background color").color(Color::WHITE),
text(format!("{background_color:?}"))
.size(14)
.color(Color::WHITE),
text_input("Placeholder", &self.input)
.on_input(Message::InputChanged),
sliders,
]
.spacing(10),
)
.padding(10)
.height(Length::Fill)
.align_y(alignment::Vertical::Bottom)
.into()
}
}

View file

@ -5,315 +5,347 @@ use controls::Controls;
use scene::Scene;
use iced_wgpu::graphics::Viewport;
use iced_wgpu::{wgpu, Backend, Renderer, Settings};
use iced_wgpu::{wgpu, Engine, Renderer};
use iced_winit::conversion;
use iced_winit::core::mouse;
use iced_winit::core::renderer;
use iced_winit::core::window;
use iced_winit::core::{Color, Font, Pixels, Size};
use iced_winit::core::{Color, Font, Pixels, Size, Theme};
use iced_winit::futures;
use iced_winit::runtime::program;
use iced_winit::style::Theme;
use iced_winit::winit;
use iced_winit::Clipboard;
use winit::{
event::{Event, WindowEvent},
event::WindowEvent,
event_loop::{ControlFlow, EventLoop},
keyboard::ModifiersState,
};
use std::sync::Arc;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;
#[cfg(target_arch = "wasm32")]
use web_sys::HtmlCanvasElement;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::WindowBuilderExtWebSys;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(target_arch = "wasm32")]
let canvas_element = {
console_log::init().expect("Initialize logger");
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
web_sys::window()
.and_then(|win| win.document())
.and_then(|doc| doc.get_element_by_id("iced_canvas"))
.and_then(|element| element.dyn_into::<HtmlCanvasElement>().ok())
.expect("Get canvas element")
};
#[cfg(not(target_arch = "wasm32"))]
pub fn main() -> Result<(), winit::error::EventLoopError> {
tracing_subscriber::fmt::init();
// Initialize winit
let event_loop = EventLoop::new()?;
#[cfg(target_arch = "wasm32")]
let window = winit::window::WindowBuilder::new()
.with_canvas(Some(canvas_element))
.build(&event_loop)?;
#[allow(clippy::large_enum_variant)]
enum Runner {
Loading,
Ready {
window: Arc<winit::window::Window>,
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
format: wgpu::TextureFormat,
engine: Engine,
renderer: Renderer,
scene: Scene,
state: program::State<Controls>,
cursor_position: Option<winit::dpi::PhysicalPosition<f64>>,
clipboard: Clipboard,
viewport: Viewport,
modifiers: ModifiersState,
resized: bool,
},
}
#[cfg(not(target_arch = "wasm32"))]
let window = winit::window::Window::new(&event_loop)?;
impl winit::application::ApplicationHandler for Runner {
fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if let Self::Loading = self {
let window = Arc::new(
event_loop
.create_window(
winit::window::WindowAttributes::default(),
)
.expect("Create window"),
);
let window = Arc::new(window);
let physical_size = window.inner_size();
let viewport = Viewport::with_physical_size(
Size::new(physical_size.width, physical_size.height),
window.scale_factor(),
);
let clipboard = Clipboard::connect(&window);
let physical_size = window.inner_size();
let mut viewport = Viewport::with_physical_size(
Size::new(physical_size.width, physical_size.height),
window.scale_factor(),
);
let mut cursor_position = None;
let mut modifiers = ModifiersState::default();
let mut clipboard = Clipboard::connect(&window);
let backend =
wgpu::util::backend_bits_from_env().unwrap_or_default();
// Initialize wgpu
#[cfg(target_arch = "wasm32")]
let default_backend = wgpu::Backends::GL;
#[cfg(not(target_arch = "wasm32"))]
let default_backend = wgpu::Backends::PRIMARY;
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: backend,
..Default::default()
});
let surface = instance
.create_surface(window.clone())
.expect("Create window surface");
let backend =
wgpu::util::backend_bits_from_env().unwrap_or(default_backend);
let (format, adapter, device, queue) =
futures::futures::executor::block_on(async {
let adapter =
wgpu::util::initialize_adapter_from_env_or_default(
&instance,
Some(&surface),
)
.await
.expect("Create adapter");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: backend,
..Default::default()
});
let surface = instance.create_surface(window.clone())?;
let adapter_features = adapter.features();
let (format, adapter, device, queue) =
futures::futures::executor::block_on(async {
let adapter = wgpu::util::initialize_adapter_from_env_or_default(
&instance,
Some(&surface),
)
.await
.expect("Create adapter");
let capabilities = surface.get_capabilities(&adapter);
let adapter_features = adapter.features();
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
required_features: adapter_features
& wgpu::Features::default(),
required_limits: wgpu::Limits::default(),
},
None,
)
.await
.expect("Request device");
#[cfg(target_arch = "wasm32")]
let needed_limits = wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits());
(
capabilities
.formats
.iter()
.copied()
.find(wgpu::TextureFormat::is_srgb)
.or_else(|| {
capabilities.formats.first().copied()
})
.expect("Get preferred format"),
adapter,
device,
queue,
)
});
#[cfg(not(target_arch = "wasm32"))]
let needed_limits = wgpu::Limits::default();
let capabilities = surface.get_capabilities(&adapter);
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
required_features: adapter_features
& wgpu::Features::default(),
required_limits: needed_limits,
surface.configure(
&device,
&wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width: physical_size.width,
height: physical_size.height,
present_mode: wgpu::PresentMode::AutoVsync,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
None,
)
.await
.expect("Request device");
);
(
capabilities
.formats
.iter()
.copied()
.find(wgpu::TextureFormat::is_srgb)
.or_else(|| capabilities.formats.first().copied())
.expect("Get preferred format"),
adapter,
// Initialize scene and GUI controls
let scene = Scene::new(&device, format);
let controls = Controls::new();
// Initialize iced
let engine =
Engine::new(&adapter, &device, &queue, format, None);
let mut renderer = Renderer::new(
&device,
&engine,
Font::default(),
Pixels::from(16),
);
let state = program::State::new(
controls,
viewport.logical_size(),
&mut renderer,
);
// You should change this if you want to render continuously
event_loop.set_control_flow(ControlFlow::Wait);
*self = Self::Ready {
window,
device,
queue,
surface,
format,
engine,
renderer,
scene,
state,
cursor_position: None,
modifiers: ModifiersState::default(),
clipboard,
viewport,
resized: false,
};
}
}
fn window_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let Self::Ready {
window,
device,
queue,
)
});
surface,
format,
engine,
renderer,
scene,
state,
viewport,
cursor_position,
modifiers,
clipboard,
resized,
} = self
else {
return;
};
surface.configure(
&device,
&wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width: physical_size.width,
height: physical_size.height,
present_mode: wgpu::PresentMode::AutoVsync,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
match event {
WindowEvent::RedrawRequested => {
if *resized {
let size = window.inner_size();
let mut resized = false;
// Initialize scene and GUI controls
let scene = Scene::new(&device, format);
let controls = Controls::new();
// Initialize iced
let mut renderer = Renderer::new(
Backend::new(&adapter, &device, &queue, Settings::default(), format),
Font::default(),
Pixels(16.0),
);
let mut state =
program::State::new(controls, viewport.logical_size(), &mut renderer);
// Run event loop
event_loop.run(move |event, window_target| {
// You should change this if you want to render continuosly
window_target.set_control_flow(ControlFlow::Wait);
match event {
Event::WindowEvent {
event: WindowEvent::RedrawRequested,
..
} => {
if resized {
let size = window.inner_size();
viewport = Viewport::with_physical_size(
Size::new(size.width, size.height),
window.scale_factor(),
);
surface.configure(
&device,
&wgpu::SurfaceConfiguration {
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::AutoVsync,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
resized = false;
}
match surface.get_current_texture() {
Ok(frame) => {
let mut encoder = device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
*viewport = Viewport::with_physical_size(
Size::new(size.width, size.height),
window.scale_factor(),
);
let program = state.program();
let view = frame.texture.create_view(
&wgpu::TextureViewDescriptor::default(),
surface.configure(
device,
&wgpu::SurfaceConfiguration {
format: *format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::AutoVsync,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
{
// We clear the frame
let mut render_pass = Scene::clear(
&view,
&mut encoder,
program.background_color(),
*resized = false;
}
match surface.get_current_texture() {
Ok(frame) => {
let mut encoder = device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
// Draw the scene
scene.draw(&mut render_pass);
}
let program = state.program();
// And then iced on top
renderer.with_primitives(|backend, primitive| {
backend.present(
&device,
&queue,
let view = frame.texture.create_view(
&wgpu::TextureViewDescriptor::default(),
);
{
// We clear the frame
let mut render_pass = Scene::clear(
&view,
&mut encoder,
program.background_color(),
);
// Draw the scene
scene.draw(&mut render_pass);
}
// And then iced on top
renderer.present(
engine,
device,
queue,
&mut encoder,
None,
frame.texture.format(),
&view,
primitive,
&viewport,
viewport,
);
});
// Then we submit the work
queue.submit(Some(encoder.finish()));
frame.present();
// Then we submit the work
engine.submit(queue, encoder);
frame.present();
// Update the mouse cursor
window.set_cursor_icon(
iced_winit::conversion::mouse_interaction(
state.mouse_interaction(),
),
);
}
Err(error) => match error {
wgpu::SurfaceError::OutOfMemory => {
panic!(
"Swapchain error: {error}. \
// Update the mouse cursor
window.set_cursor(
iced_winit::conversion::mouse_interaction(
state.mouse_interaction(),
),
);
}
Err(error) => match error {
wgpu::SurfaceError::OutOfMemory => {
panic!(
"Swapchain error: {error}. \
Rendering cannot continue."
)
}
_ => {
// Try rendering again next frame.
window.request_redraw();
}
},
}
}
WindowEvent::CursorMoved { position, .. } => {
*cursor_position = Some(position);
}
WindowEvent::ModifiersChanged(new_modifiers) => {
*modifiers = new_modifiers.state();
}
WindowEvent::Resized(_) => {
*resized = true;
}
WindowEvent::CloseRequested => {
event_loop.exit();
}
_ => {}
}
// Map window event to iced event
if let Some(event) = iced_winit::conversion::window_event(
window::Id::MAIN,
event,
window.scale_factor(),
*modifiers,
) {
state.queue_event(event);
}
// If there are events pending
if !state.is_queue_empty() {
// We update iced
let _ = state.update(
viewport.logical_size(),
cursor_position
.map(|p| {
conversion::cursor_position(
p,
viewport.scale_factor(),
)
}
_ => {
// Try rendering again next frame.
window.request_redraw();
}
})
.map(mouse::Cursor::Available)
.unwrap_or(mouse::Cursor::Unavailable),
renderer,
&Theme::Dark,
&renderer::Style {
text_color: Color::WHITE,
},
}
clipboard,
);
// and request a redraw
window.request_redraw();
}
Event::WindowEvent { event, .. } => {
match event {
WindowEvent::CursorMoved { position, .. } => {
cursor_position = Some(position);
}
WindowEvent::ModifiersChanged(new_modifiers) => {
modifiers = new_modifiers.state();
}
WindowEvent::Resized(_) => {
resized = true;
}
WindowEvent::CloseRequested => {
window_target.exit();
}
_ => {}
}
// Map window event to iced event
if let Some(event) = iced_winit::conversion::window_event(
window::Id::MAIN,
event,
window.scale_factor(),
modifiers,
) {
state.queue_event(event);
}
}
_ => {}
}
}
// If there are events pending
if !state.is_queue_empty() {
// We update iced
let _ = state.update(
viewport.logical_size(),
cursor_position
.map(|p| {
conversion::cursor_position(p, viewport.scale_factor())
})
.map(mouse::Cursor::Available)
.unwrap_or(mouse::Cursor::Unavailable),
&mut renderer,
&Theme::Dark,
&renderer::Style {
text_color: Color::WHITE,
},
&mut clipboard,
);
// and request a redraw
window.request_redraw();
}
})?;
Ok(())
let mut runner = Runner::Loading;
event_loop.run_app(&mut runner)
}

View file

@ -1,21 +1,22 @@
use iced::executor;
use iced::keyboard;
use iced::mouse;
use iced::theme;
use iced::widget::{
button, canvas, checkbox, column, container, horizontal_space, pick_list,
row, scrollable, text, vertical_rule,
button, canvas, center, checkbox, column, container, horizontal_space,
pick_list, row, scrollable, text,
};
use iced::{
color, Alignment, Application, Color, Command, Element, Font, Length,
Point, Rectangle, Renderer, Settings, Subscription, Theme,
color, Alignment, Element, Font, Length, Point, Rectangle, Renderer,
Subscription, Theme,
};
pub fn main() -> iced::Result {
Layout::run(Settings::default())
iced::program(Layout::title, Layout::update, Layout::view)
.subscription(Layout::subscription)
.theme(Layout::theme)
.run()
}
#[derive(Debug)]
#[derive(Default, Debug)]
struct Layout {
example: Example,
explain: bool,
@ -30,28 +31,12 @@ enum Message {
ThemeSelected(Theme),
}
impl Application for Layout {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
Self {
example: Example::default(),
explain: false,
theme: Theme::Light,
},
Command::none(),
)
}
impl Layout {
fn title(&self) -> String {
format!("{} - Layout - Iced", self.example.title)
}
fn update(&mut self, message: Self::Message) -> Command<Message> {
fn update(&mut self, message: Message) {
match message {
Message::Next => {
self.example = self.example.next();
@ -66,8 +51,6 @@ impl Application for Layout {
self.theme = theme;
}
}
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
@ -93,22 +76,18 @@ impl Application for Layout {
.spacing(20)
.align_items(Alignment::Center);
let example = container(if self.explain {
let example = center(if self.explain {
self.example.view().explain(color!(0x0000ff))
} else {
self.example.view()
})
.style(|theme: &Theme| {
.style(|theme| {
let palette = theme.extended_palette();
container::Appearance::default()
container::Style::default()
.with_border(palette.background.strong.color, 4.0)
})
.padding(4)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y();
.padding(4);
let controls = row([
(!self.example.is_first()).then_some(
@ -167,10 +146,6 @@ impl Example {
title: "Application",
view: application,
},
Self {
title: "Nested Quotes",
view: nested_quotes,
},
];
fn is_first(self) -> bool {
@ -216,12 +191,7 @@ impl Default for Example {
}
fn centered<'a>() -> Element<'a, Message> {
container(text("I am centered!").size(50))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(text("I am centered!").size(50)).into()
}
fn column_<'a>() -> Element<'a, Message> {
@ -266,10 +236,10 @@ fn application<'a>() -> Element<'a, Message> {
.padding(10)
.align_items(Alignment::Center),
)
.style(|theme: &Theme| {
.style(|theme| {
let palette = theme.extended_palette();
container::Appearance::default()
container::Style::default()
.with_border(palette.background.strong.color, 1)
});
@ -280,8 +250,7 @@ fn application<'a>() -> Element<'a, Message> {
.width(200)
.align_items(Alignment::Center),
)
.style(theme::Container::Box)
.height(Length::Fill)
.style(container::rounded_box)
.center_y();
let content = container(
@ -304,38 +273,6 @@ fn application<'a>() -> Element<'a, Message> {
column![header, row![sidebar, content]].into()
}
fn nested_quotes<'a>() -> Element<'a, Message> {
(1..5)
.fold(column![text("Original text")].padding(10), |quotes, i| {
column![
container(
row![vertical_rule(2), quotes].height(Length::Shrink)
)
.style(|theme: &Theme| {
let palette = theme.extended_palette();
container::Appearance::default().with_background(
if palette.is_dark {
Color {
a: 0.01,
..Color::WHITE
}
} else {
Color {
a: 0.08,
..Color::BLACK
}
},
)
}),
text(format!("Reply {i}"))
]
.spacing(10)
.padding(10)
})
.into()
}
fn square<'a>(size: impl Into<Length> + Copy) -> Element<'a, Message> {
struct Square;

View file

@ -1,15 +1,14 @@
use iced::theme;
use iced::widget::{
button, column, horizontal_space, lazy, pick_list, row, scrollable, text,
text_input,
};
use iced::{Element, Length, Sandbox, Settings};
use iced::{Element, Length};
use std::collections::HashSet;
use std::hash::Hash;
pub fn main() -> iced::Result {
App::run(Settings::default())
iced::run("Lazy - Iced", App::update, App::view)
}
struct App {
@ -121,17 +120,7 @@ enum Message {
ItemColorChanged(Item, Color),
}
impl Sandbox for App {
type Message = Message;
fn new() -> Self {
Self::default()
}
fn title(&self) -> String {
String::from("Lazy - Iced")
}
impl App {
fn update(&mut self, message: Message) {
match message {
Message::InputChanged(input) => {
@ -181,11 +170,10 @@ impl Sandbox for App {
column(items.into_iter().map(|item| {
let button = button("Delete")
.on_press(Message::DeleteItem(item.clone()))
.style(theme::Button::Destructive);
.style(button::danger);
row![
text(&item.name)
.style(theme::Text::Color(item.color.into())),
text(item.name.clone()).color(item.color),
horizontal_space(),
pick_list(Color::ALL, Some(item.color), move |color| {
Message::ItemColorChanged(item.clone(), color)

View file

@ -358,7 +358,7 @@ where
|renderer| {
use iced::advanced::graphics::geometry::Renderer as _;
renderer.draw(vec![geometry]);
renderer.draw_geometry(geometry);
},
);
}

View file

@ -1,6 +1,5 @@
use iced::executor;
use iced::widget::{column, container, row, slider, text};
use iced::{Application, Command, Element, Length, Settings, Theme};
use iced::widget::{center, column, row, slider, text};
use iced::Element;
use std::time::Duration;
@ -12,51 +11,31 @@ use circular::Circular;
use linear::Linear;
pub fn main() -> iced::Result {
LoadingSpinners::run(Settings {
antialiasing: true,
..Default::default()
})
iced::program(
"Loading Spinners - Iced",
LoadingSpinners::update,
LoadingSpinners::view,
)
.antialiasing(true)
.run()
}
struct LoadingSpinners {
cycle_duration: f32,
}
impl Default for LoadingSpinners {
fn default() -> Self {
Self {
cycle_duration: 2.0,
}
}
}
#[derive(Debug, Clone, Copy)]
enum Message {
CycleDurationChanged(f32),
}
impl Application for LoadingSpinners {
type Message = Message;
type Flags = ();
type Executor = executor::Default;
type Theme = Theme;
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(Self::default(), Command::none())
}
fn title(&self) -> String {
String::from("Loading Spinners - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl LoadingSpinners {
fn update(&mut self, message: Message) {
match message {
Message::CycleDurationChanged(duration) => {
self.cycle_duration = duration;
}
}
Command::none()
}
fn view(&self) -> Element<Message> {
@ -94,7 +73,7 @@ impl Application for LoadingSpinners {
})
.spacing(20);
container(
center(
column.push(
row![
text("Cycle duration:"),
@ -108,10 +87,14 @@ impl Application for LoadingSpinners {
.spacing(20.0),
),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}
impl Default for LoadingSpinners {
fn default() -> Self {
Self {
cycle_duration: 2.0,
}
}
}

View file

@ -1,59 +1,46 @@
use iced::widget::{button, column, container, text};
use iced::{Alignment, Element, Length, Sandbox, Settings};
use iced::widget::{button, center, column, text};
use iced::{Alignment, Element};
use loupe::loupe;
pub fn main() -> iced::Result {
Counter::run(Settings::default())
iced::run("Loupe - Iced", Loupe::update, Loupe::view)
}
struct Counter {
value: i32,
#[derive(Default)]
struct Loupe {
value: i64,
}
#[derive(Debug, Clone, Copy)]
enum Message {
IncrementPressed,
DecrementPressed,
Increment,
Decrement,
}
impl Sandbox for Counter {
type Message = Message;
fn new() -> Self {
Self { value: 0 }
}
fn title(&self) -> String {
String::from("Counter - Iced")
}
impl Loupe {
fn update(&mut self, message: Message) {
match message {
Message::IncrementPressed => {
Message::Increment => {
self.value += 1;
}
Message::DecrementPressed => {
Message::Decrement => {
self.value -= 1;
}
}
}
fn view(&self) -> Element<Message> {
container(loupe(
center(loupe(
3.0,
column![
button("Increment").on_press(Message::IncrementPressed),
button("Increment").on_press(Message::Increment),
text(self.value).size(50),
button("Decrement").on_press(Message::DecrementPressed)
button("Decrement").on_press(Message::Decrement)
]
.padding(20)
.align_items(Alignment::Center),
))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}
@ -168,7 +155,7 @@ mod loupe {
if cursor.is_over(layout.bounds()) {
mouse::Interaction::ZoomIn
} else {
mouse::Interaction::Idle
mouse::Interaction::None
}
}
}

View file

@ -1,21 +1,18 @@
use iced::event::{self, Event};
use iced::executor;
use iced::keyboard;
use iced::keyboard::key;
use iced::theme;
use iced::widget::{
self, button, column, container, horizontal_space, pick_list, row, text,
text_input,
};
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
self, button, center, column, container, horizontal_space, mouse_area,
opaque, pick_list, row, stack, text, text_input,
};
use iced::{Alignment, Color, Command, Element, Length, Subscription};
use modal::Modal;
use std::fmt;
pub fn main() -> iced::Result {
App::run(Settings::default())
iced::program("Modal - Iced", App::update, App::view)
.subscription(App::subscription)
.run()
}
#[derive(Default)]
@ -37,21 +34,8 @@ enum Message {
Event(Event),
}
impl Application for App {
type Executor = executor::Default;
type Message = Message;
type Theme = iced::Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(App::default(), Command::none())
}
fn title(&self) -> String {
String::from("Modal - Iced")
}
fn subscription(&self) -> Subscription<Self::Message> {
impl App {
fn subscription(&self) -> Subscription<Message> {
event::listen().map(Message::Event)
}
@ -114,13 +98,7 @@ impl Application for App {
row![text("Top Left"), horizontal_space(), text("Top Right")]
.align_items(Alignment::Start)
.height(Length::Fill),
container(
button(text("Show Modal")).on_press(Message::ShowModal)
)
.center_x()
.center_y()
.width(Length::Fill)
.height(Length::Fill),
center(button(text("Show Modal")).on_press(Message::ShowModal)),
row![
text("Bottom Left"),
horizontal_space(),
@ -131,12 +109,10 @@ impl Application for App {
]
.height(Length::Fill),
)
.padding(10)
.width(Length::Fill)
.height(Length::Fill);
.padding(10);
if self.show_modal {
let modal = container(
let signup = container(
column![
text("Sign Up").size(24),
column![
@ -175,11 +151,9 @@ impl Application for App {
)
.width(300)
.padding(10)
.style(theme::Container::Box);
.style(container::rounded_box);
Modal::new(content, modal)
.on_blur(Message::HideModal)
.into()
modal(content, signup, Message::HideModal)
} else {
content.into()
}
@ -218,326 +192,29 @@ impl fmt::Display for Plan {
}
}
mod modal {
use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay;
use iced::advanced::renderer;
use iced::advanced::widget::{self, Widget};
use iced::advanced::{self, Clipboard, Shell};
use iced::alignment::Alignment;
use iced::event;
use iced::mouse;
use iced::{Color, Element, Event, Length, Point, Rectangle, Size, Vector};
/// A widget that centers a modal element over some base element
pub struct Modal<'a, Message, Theme, Renderer> {
base: Element<'a, Message, Theme, Renderer>,
modal: Element<'a, Message, Theme, Renderer>,
on_blur: Option<Message>,
}
impl<'a, Message, Theme, Renderer> Modal<'a, Message, Theme, Renderer> {
/// Returns a new [`Modal`]
pub fn new(
base: impl Into<Element<'a, Message, Theme, Renderer>>,
modal: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Self {
Self {
base: base.into(),
modal: modal.into(),
on_blur: None,
}
}
/// Sets the message that will be produces when the background
/// of the [`Modal`] is pressed
pub fn on_blur(self, on_blur: Message) -> Self {
Self {
on_blur: Some(on_blur),
..self
}
}
}
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Modal<'a, Message, Theme, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
{
fn children(&self) -> Vec<widget::Tree> {
vec![
widget::Tree::new(&self.base),
widget::Tree::new(&self.modal),
]
}
fn diff(&self, tree: &mut widget::Tree) {
tree.diff_children(&[&self.base, &self.modal]);
}
fn size(&self) -> Size<Length> {
self.base.as_widget().size()
}
fn layout(
&self,
tree: &mut widget::Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.base.as_widget().layout(
&mut tree.children[0],
renderer,
limits,
)
}
fn on_event(
&mut self,
state: &mut widget::Tree,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) -> event::Status {
self.base.as_widget_mut().on_event(
&mut state.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
)
}
fn draw(
&self,
state: &widget::Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.base.as_widget().draw(
&state.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn overlay<'b>(
&'b mut self,
state: &'b mut widget::Tree,
layout: Layout<'_>,
_renderer: &Renderer,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
Some(overlay::Element::new(Box::new(Overlay {
position: layout.position() + translation,
content: &mut self.modal,
tree: &mut state.children[1],
size: layout.bounds().size(),
on_blur: self.on_blur.clone(),
})))
}
fn mouse_interaction(
&self,
state: &widget::Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.base.as_widget().mouse_interaction(
&state.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn operate(
&self,
state: &mut widget::Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>,
) {
self.base.as_widget().operate(
&mut state.children[0],
layout,
renderer,
operation,
);
}
}
struct Overlay<'a, 'b, Message, Theme, Renderer> {
position: Point,
content: &'b mut Element<'a, Message, Theme, Renderer>,
tree: &'b mut widget::Tree,
size: Size,
on_blur: Option<Message>,
}
impl<'a, 'b, Message, Theme, Renderer>
overlay::Overlay<Message, Theme, Renderer>
for Overlay<'a, 'b, Message, Theme, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
{
fn layout(
&mut self,
renderer: &Renderer,
_bounds: Size,
) -> layout::Node {
let limits = layout::Limits::new(Size::ZERO, self.size)
.width(Length::Fill)
.height(Length::Fill);
let child = self
.content
.as_widget()
.layout(self.tree, renderer, &limits)
.align(Alignment::Center, Alignment::Center, limits.max());
layout::Node::with_children(self.size, vec![child])
.move_to(self.position)
}
fn on_event(
&mut self,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
) -> event::Status {
let content_bounds = layout.children().next().unwrap().bounds();
if let Some(message) = self.on_blur.as_ref() {
if let Event::Mouse(mouse::Event::ButtonPressed(
mouse::Button::Left,
)) = &event
{
if !cursor.is_over(content_bounds) {
shell.publish(message.clone());
return event::Status::Captured;
fn modal<'a, Message>(
base: impl Into<Element<'a, Message>>,
content: impl Into<Element<'a, Message>>,
on_blur: Message,
) -> Element<'a, Message>
where
Message: Clone + 'a,
{
stack![
base.into(),
mouse_area(center(opaque(content)).style(|_theme| {
container::Style {
background: Some(
Color {
a: 0.8,
..Color::BLACK
}
}
.into(),
),
..container::Style::default()
}
self.content.as_widget_mut().on_event(
self.tree,
event,
layout.children().next().unwrap(),
cursor,
renderer,
clipboard,
shell,
&layout.bounds(),
)
}
fn draw(
&self,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
) {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
..renderer::Quad::default()
},
Color {
a: 0.80,
..Color::BLACK
},
);
self.content.as_widget().draw(
self.tree,
renderer,
theme,
style,
layout.children().next().unwrap(),
cursor,
&layout.bounds(),
);
}
fn operate(
&mut self,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>,
) {
self.content.as_widget().operate(
self.tree,
layout.children().next().unwrap(),
renderer,
operation,
);
}
fn mouse_interaction(
&self,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
self.tree,
layout.children().next().unwrap(),
cursor,
viewport,
renderer,
)
}
fn overlay<'c>(
&'c mut self,
layout: Layout<'_>,
renderer: &Renderer,
) -> Option<overlay::Element<'c, Message, Theme, Renderer>> {
self.content.as_widget_mut().overlay(
self.tree,
layout.children().next().unwrap(),
renderer,
Vector::ZERO,
)
}
}
impl<'a, Message, Theme, Renderer> From<Modal<'a, Message, Theme, Renderer>>
for Element<'a, Message, Theme, Renderer>
where
Theme: 'a,
Message: 'a + Clone,
Renderer: 'a + advanced::Renderer,
{
fn from(modal: Modal<'a, Message, Theme, Renderer>) -> Self {
Element::new(modal)
}
}
}))
.on_press(on_blur)
]
.into()
}

View file

@ -1,7 +1,9 @@
use iced::event;
use iced::executor;
use iced::multi_window::{self, Application};
use iced::widget::{button, column, container, scrollable, text, text_input};
use iced::widget::{
button, center, column, container, scrollable, text, text_input,
};
use iced::window;
use iced::{
Alignment, Command, Element, Length, Point, Settings, Subscription, Theme,
@ -128,12 +130,7 @@ impl multi_window::Application for Example {
fn view(&self, window: window::Id) -> Element<Message> {
let content = self.windows.get(&window).unwrap().view(window);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
fn theme(&self, window: window::Id) -> Self::Theme {
@ -210,6 +207,6 @@ impl Window {
.align_items(Alignment::Center),
);
container(content).width(200).center_x().into()
container(content).center_x().width(200).into()
}
}

View file

@ -2,101 +2,58 @@
//! a circle around each fingertip. This only works on touch-enabled
//! computers like Microsoft Surface.
use iced::mouse;
use iced::touch;
use iced::widget::canvas::event;
use iced::widget::canvas::stroke::{self, Stroke};
use iced::widget::canvas::{self, Canvas, Geometry};
use iced::{
executor, touch, window, Application, Color, Command, Element, Length,
Point, Rectangle, Renderer, Settings, Subscription, Theme,
};
use iced::{Color, Element, Length, Point, Rectangle, Renderer, Theme};
use std::collections::HashMap;
pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
Multitouch::run(Settings {
antialiasing: true,
window: window::Settings {
position: window::Position::Centered,
..window::Settings::default()
},
..Settings::default()
})
iced::program("Multitouch - Iced", Multitouch::update, Multitouch::view)
.antialiasing(true)
.centered()
.run()
}
#[derive(Default)]
struct Multitouch {
state: State,
}
#[derive(Debug)]
struct State {
cache: canvas::Cache,
fingers: HashMap<touch::Finger, Point>,
}
impl State {
fn new() -> Self {
Self {
cache: canvas::Cache::new(),
fingers: HashMap::new(),
}
}
}
#[derive(Debug)]
enum Message {
FingerPressed { id: touch::Finger, position: Point },
FingerLifted { id: touch::Finger },
}
impl Application for Multitouch {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Multitouch {
state: State::new(),
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Multitouch - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl Multitouch {
fn update(&mut self, message: Message) {
match message {
Message::FingerPressed { id, position } => {
self.state.fingers.insert(id, position);
self.state.cache.clear();
self.fingers.insert(id, position);
self.cache.clear();
}
Message::FingerLifted { id } => {
self.state.fingers.remove(&id);
self.state.cache.clear();
self.fingers.remove(&id);
self.cache.clear();
}
}
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
Subscription::none()
}
fn view(&self) -> Element<Message> {
Canvas::new(&self.state)
Canvas::new(self)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
}
impl canvas::Program<Message> for State {
impl canvas::Program<Message> for Multitouch {
type State = ();
fn update(

View file

@ -1,17 +1,15 @@
use iced::alignment::{self, Alignment};
use iced::executor;
use iced::keyboard;
use iced::theme::{self, Theme};
use iced::widget::pane_grid::{self, PaneGrid};
use iced::widget::{
button, column, container, responsive, row, scrollable, text,
};
use iced::{
Application, Color, Command, Element, Length, Settings, Size, Subscription,
};
use iced::{Color, Element, Length, Size, Subscription};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::program("Pane Grid - Iced", Example::update, Example::view)
.subscription(Example::subscription)
.run()
}
struct Example {
@ -35,30 +33,18 @@ enum Message {
CloseFocused,
}
impl Application for Example {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
impl Example {
fn new() -> Self {
let (panes, _) = pane_grid::State::new(Pane::new(0));
(
Example {
panes,
panes_created: 1,
focus: None,
},
Command::none(),
)
Example {
panes,
panes_created: 1,
focus: None,
}
}
fn title(&self) -> String {
String::from("Pane grid - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
fn update(&mut self, message: Message) {
match message {
Message::Split(axis, pane) => {
let result =
@ -132,8 +118,6 @@ impl Application for Example {
}
}
}
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
@ -162,7 +146,7 @@ impl Application for Example {
let title = row![
pin_button,
"Pane",
text(pane.id.to_string()).style(if is_focused {
text(pane.id.to_string()).color(if is_focused {
PANE_ID_COLOR_FOCUSED
} else {
PANE_ID_COLOR_UNFOCUSED
@ -209,6 +193,12 @@ impl Application for Example {
}
}
impl Default for Example {
fn default() -> Self {
Example::new()
}
}
const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb(
0xFF as f32 / 255.0,
0xC7 as f32 / 255.0,
@ -287,10 +277,7 @@ fn view_content<'a>(
)
]
.push_maybe(if total_panes > 1 && !is_pinned {
Some(
button("Close", Message::Close(pane))
.style(theme::Button::Destructive),
)
Some(button("Close", Message::Close(pane)).style(button::danger))
} else {
None
})
@ -304,12 +291,7 @@ fn view_content<'a>(
.spacing(10)
.align_items(Alignment::Center);
container(scrollable(content))
.width(Length::Fill)
.height(Length::Fill)
.padding(5)
.center_y()
.into()
container(scrollable(content)).center_y().padding(5).into()
}
fn view_controls<'a>(
@ -327,7 +309,7 @@ fn view_controls<'a>(
Some(
button(text(content).size(14))
.style(theme::Button::Secondary)
.style(button::secondary)
.padding(3)
.on_press(message),
)
@ -336,7 +318,7 @@ fn view_controls<'a>(
});
let close = button(text("Close").size(14))
.style(theme::Button::Destructive)
.style(button::danger)
.padding(3)
.on_press_maybe(if total_panes > 1 && !is_pinned {
Some(Message::Close(pane))
@ -351,30 +333,30 @@ mod style {
use iced::widget::container;
use iced::{Border, Theme};
pub fn title_bar_active(theme: &Theme) -> container::Appearance {
pub fn title_bar_active(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
container::Appearance {
container::Style {
text_color: Some(palette.background.strong.text),
background: Some(palette.background.strong.color.into()),
..Default::default()
}
}
pub fn title_bar_focused(theme: &Theme) -> container::Appearance {
pub fn title_bar_focused(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
container::Appearance {
container::Style {
text_color: Some(palette.primary.strong.text),
background: Some(palette.primary.strong.color.into()),
..Default::default()
}
}
pub fn pane_active(theme: &Theme) -> container::Appearance {
pub fn pane_active(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
container::Appearance {
container::Style {
background: Some(palette.background.weak.color.into()),
border: Border {
width: 2.0,
@ -385,10 +367,10 @@ mod style {
}
}
pub fn pane_focused(theme: &Theme) -> container::Appearance {
pub fn pane_focused(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
container::Appearance {
container::Style {
background: Some(palette.background.weak.color.into()),
border: Border {
width: 2.0,

View file

@ -1,8 +1,8 @@
use iced::widget::{column, pick_list, scrollable, vertical_space};
use iced::{Alignment, Element, Length, Sandbox, Settings};
use iced::{Alignment, Element, Length};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Pick List - Iced", Example::update, Example::view)
}
#[derive(Default)]
@ -15,17 +15,7 @@ enum Message {
LanguageSelected(Language),
}
impl Sandbox for Example {
type Message = Message;
fn new() -> Self {
Self::default()
}
fn title(&self) -> String {
String::from("Pick list - Iced")
}
impl Example {
fn update(&mut self, message: Message) {
match message {
Message::LanguageSelected(language) => {

View file

@ -1,17 +1,20 @@
use iced::futures;
use iced::widget::{self, column, container, image, row, text};
use iced::{
Alignment, Application, Color, Command, Element, Length, Settings, Theme,
};
use iced::widget::{self, center, column, image, row, text};
use iced::{Alignment, Command, Element, Length};
pub fn main() -> iced::Result {
Pokedex::run(Settings::default())
iced::program(Pokedex::title, Pokedex::update, Pokedex::view)
.load(Pokedex::search)
.run()
}
#[derive(Debug)]
#[derive(Debug, Default)]
enum Pokedex {
#[default]
Loading,
Loaded { pokemon: Pokemon },
Loaded {
pokemon: Pokemon,
},
Errored,
}
@ -21,17 +24,9 @@ enum Message {
Search,
}
impl Application for Pokedex {
type Message = Message;
type Theme = Theme;
type Executor = iced::executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Pokedex, Command<Message>) {
(
Pokedex::Loading,
Command::perform(Pokemon::search(), Message::PokemonFound),
)
impl Pokedex {
fn search() -> Command<Message> {
Command::perform(Pokemon::search(), Message::PokemonFound)
}
fn title(&self) -> String {
@ -61,7 +56,7 @@ impl Application for Pokedex {
_ => {
*self = Pokedex::Loading;
Command::perform(Pokemon::search(), Message::PokemonFound)
Self::search()
}
},
}
@ -88,12 +83,7 @@ impl Application for Pokedex {
.align_items(Alignment::End),
};
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
}
@ -116,7 +106,7 @@ impl Pokemon {
text(&self.name).size(30).width(Length::Fill),
text(format!("#{}", self.number))
.size(20)
.style(Color::from([0.5, 0.5, 0.5])),
.color([0.5, 0.5, 0.5]),
]
.align_items(Alignment::Center)
.spacing(20),
@ -193,7 +183,7 @@ impl Pokemon {
{
let bytes = reqwest::get(&url).await?.bytes().await?;
Ok(image::Handle::from_memory(bytes))
Ok(image::Handle::from_bytes(bytes))
}
#[cfg(target_arch = "wasm32")]

View file

@ -1,8 +1,8 @@
use iced::widget::{column, progress_bar, slider};
use iced::{Element, Sandbox, Settings};
use iced::Element;
pub fn main() -> iced::Result {
Progress::run(Settings::default())
iced::run("Progress Bar - Iced", Progress::update, Progress::view)
}
#[derive(Default)]
@ -15,17 +15,7 @@ enum Message {
SliderChanged(f32),
}
impl Sandbox for Progress {
type Message = Message;
fn new() -> Self {
Self::default()
}
fn title(&self) -> String {
String::from("A simple Progressbar")
}
impl Progress {
fn update(&mut self, message: Message) {
match message {
Message::SliderChanged(x) => self.value = x,

View file

@ -1,10 +1,14 @@
use iced::widget::{
column, container, pick_list, qr_code, row, text, text_input,
};
use iced::{Alignment, Element, Length, Sandbox, Settings, Theme};
use iced::widget::{center, column, pick_list, qr_code, row, text, text_input};
use iced::{Alignment, Element, Theme};
pub fn main() -> iced::Result {
QRGenerator::run(Settings::default())
iced::program(
"QR Code Generator - Iced",
QRGenerator::update,
QRGenerator::view,
)
.theme(QRGenerator::theme)
.run()
}
#[derive(Default)]
@ -20,17 +24,7 @@ enum Message {
ThemeChanged(Theme),
}
impl Sandbox for QRGenerator {
type Message = Message;
fn new() -> Self {
QRGenerator::default()
}
fn title(&self) -> String {
String::from("QR Code Generator - Iced")
}
impl QRGenerator {
fn update(&mut self, message: Message) {
match message {
Message::DataChanged(mut data) => {
@ -76,13 +70,7 @@ impl Sandbox for QRGenerator {
.spacing(20)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
center(content).padding(20).into()
}
fn theme(&self) -> Theme {

View file

@ -1,13 +1,10 @@
use iced::alignment;
use iced::executor;
use iced::keyboard;
use iced::theme;
use iced::widget::{button, column, container, image, row, text, text_input};
use iced::window;
use iced::window::screenshot::{self, Screenshot};
use iced::{
Alignment, Application, Command, ContentFit, Element, Length, Rectangle,
Subscription, Theme,
Alignment, Command, ContentFit, Element, Length, Rectangle, Subscription,
};
use ::image as img;
@ -16,9 +13,12 @@ use ::image::ColorType;
fn main() -> iced::Result {
tracing_subscriber::fmt::init();
Example::run(iced::Settings::default())
iced::program("Screenshot - Iced", Example::update, Example::view)
.subscription(Example::subscription)
.run()
}
#[derive(Default)]
struct Example {
screenshot: Option<Screenshot>,
saved_png_path: Option<Result<String, PngError>>,
@ -43,33 +43,8 @@ enum Message {
HeightInputChanged(Option<u32>),
}
impl Application for Example {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, Command<Self::Message>) {
(
Example {
screenshot: None,
saved_png_path: None,
png_saving: false,
crop_error: None,
x_input_value: None,
y_input_value: None,
width_input_value: None,
height_input_value: None,
},
Command::none(),
)
}
fn title(&self) -> String {
"Screenshot".to_string()
}
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
impl Example {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Screenshot => {
return iced::window::screenshot(
@ -131,10 +106,10 @@ impl Application for Example {
Command::none()
}
fn view(&self) -> Element<'_, Self::Message> {
fn view(&self) -> Element<'_, Message> {
let image: Element<Message> = if let Some(screenshot) = &self.screenshot
{
image(image::Handle::from_pixels(
image(image::Handle::from_rgba(
screenshot.size.width,
screenshot.size.height,
screenshot.clone(),
@ -148,12 +123,10 @@ impl Application for Example {
};
let image = container(image)
.center_y()
.padding(10)
.style(theme::Container::Box)
.width(Length::FillPortion(2))
.height(Length::Fill)
.center_x()
.center_y();
.style(container::rounded_box)
.width(Length::FillPortion(2));
let crop_origin_controls = row![
text("X:")
@ -216,9 +189,9 @@ impl Application for Example {
)
} else {
button(centered_text("Saving..."))
.style(theme::Button::Secondary)
.style(button::secondary)
}
.style(theme::Button::Secondary)
.style(button::secondary)
.padding([10, 20, 10, 20])
.width(Length::Fill)
]
@ -227,7 +200,7 @@ impl Application for Example {
crop_controls,
button(centered_text("Crop"))
.on_press(Message::Crop)
.style(theme::Button::Destructive)
.style(button::danger)
.padding([10, 20, 10, 20])
.width(Length::Fill),
]
@ -238,12 +211,7 @@ impl Application for Example {
.spacing(40)
};
let side_content = container(controls)
.align_x(alignment::Horizontal::Center)
.width(Length::FillPortion(1))
.height(Length::Fill)
.center_y()
.center_x();
let side_content = container(controls).center_y();
let content = row![side_content, image]
.spacing(10)
@ -251,16 +219,10 @@ impl Application for Example {
.height(Length::Fill)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(10)
.center_x()
.center_y()
.into()
container(content).padding(10).into()
}
fn subscription(&self) -> Subscription<Self::Message> {
fn subscription(&self) -> Subscription<Message> {
use keyboard::key;
keyboard::on_key_press(|key, _modifiers| {

View file

@ -1,19 +1,22 @@
use iced::executor;
use iced::widget::scrollable::Properties;
use iced::widget::{
button, column, container, horizontal_space, progress_bar, radio, row,
scrollable, slider, text, vertical_space, Scrollable,
};
use iced::{
Alignment, Application, Color, Command, Element, Length, Settings, Theme,
};
use iced::{Alignment, Border, Color, Command, Element, Length, Theme};
use once_cell::sync::Lazy;
static SCROLLABLE_ID: Lazy<scrollable::Id> = Lazy::new(scrollable::Id::unique);
pub fn main() -> iced::Result {
ScrollableDemo::run(Settings::default())
iced::program(
"Scrollable - Iced",
ScrollableDemo::update,
ScrollableDemo::view,
)
.theme(ScrollableDemo::theme)
.run()
}
struct ScrollableDemo {
@ -44,28 +47,16 @@ enum Message {
Scrolled(scrollable::Viewport),
}
impl Application for ScrollableDemo {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
ScrollableDemo {
scrollable_direction: Direction::Vertical,
scrollbar_width: 10,
scrollbar_margin: 0,
scroller_width: 10,
current_scroll_offset: scrollable::RelativeOffset::START,
alignment: scrollable::Alignment::Start,
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Scrollable - Iced")
impl ScrollableDemo {
fn new() -> Self {
ScrollableDemo {
scrollable_direction: Direction::Vertical,
scrollbar_width: 10,
scrollbar_margin: 0,
scroller_width: 10,
current_scroll_offset: scrollable::RelativeOffset::START,
alignment: scrollable::Alignment::Start,
}
}
fn update(&mut self, message: Message) -> Command<Message> {
@ -336,18 +327,24 @@ impl Application for ScrollableDemo {
.spacing(10)
.into();
container(content).padding(20).center_x().center_y().into()
container(content).padding(20).into()
}
fn theme(&self) -> Self::Theme {
fn theme(&self) -> Theme {
Theme::Dark
}
}
fn progress_bar_custom_style(theme: &Theme) -> progress_bar::Appearance {
progress_bar::Appearance {
background: theme.extended_palette().background.strong.color.into(),
bar: Color::from_rgb8(250, 85, 134).into(),
border_radius: 0.0.into(),
impl Default for ScrollableDemo {
fn default() -> Self {
Self::new()
}
}
fn progress_bar_custom_style(theme: &Theme) -> progress_bar::Style {
progress_bar::Style {
background: theme.extended_palette().background.strong.color.into(),
bar: Color::from_rgb8(250, 85, 134).into(),
border: Border::default(),
}
}

View file

@ -1,25 +1,23 @@
use std::fmt::Debug;
use iced::executor;
use iced::mouse;
use iced::widget::canvas::event::{self, Event};
use iced::widget::canvas::{self, Canvas};
use iced::widget::canvas::{self, Canvas, Geometry};
use iced::widget::{column, row, slider, text};
use iced::{
Application, Color, Command, Length, Point, Rectangle, Renderer, Settings,
Size, Theme,
};
use iced::{Color, Length, Point, Rectangle, Renderer, Size, Theme};
use rand::Rng;
use std::fmt::Debug;
fn main() -> iced::Result {
SierpinskiEmulator::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program(
"Sierpinski Triangle - Iced",
SierpinskiEmulator::update,
SierpinskiEmulator::view,
)
.antialiasing(true)
.run()
}
#[derive(Debug)]
#[derive(Debug, Default)]
struct SierpinskiEmulator {
graph: SierpinskiGraph,
}
@ -31,27 +29,8 @@ pub enum Message {
PointRemoved,
}
impl Application for SierpinskiEmulator {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, iced::Command<Self::Message>) {
let emulator = SierpinskiEmulator {
graph: SierpinskiGraph::new(),
};
(emulator, Command::none())
}
fn title(&self) -> String {
"Sierpinski Triangle Emulator".to_string()
}
fn update(
&mut self,
message: Self::Message,
) -> iced::Command<Self::Message> {
impl SierpinskiEmulator {
fn update(&mut self, message: Message) {
match message {
Message::IterationSet(cur_iter) => {
self.graph.iteration = cur_iter;
@ -67,11 +46,9 @@ impl Application for SierpinskiEmulator {
}
self.graph.redraw();
Command::none()
}
fn view(&self) -> iced::Element<'_, Self::Message> {
fn view(&self) -> iced::Element<'_, Message> {
column![
Canvas::new(&self.graph)
.width(Length::Fill)
@ -134,7 +111,7 @@ impl canvas::Program<Message> for SierpinskiGraph {
_theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry> {
) -> Vec<Geometry> {
let geom = self.cache.draw(renderer, bounds.size(), |frame| {
frame.stroke(
&canvas::Path::rectangle(Point::ORIGIN, frame.size()),
@ -167,10 +144,6 @@ impl canvas::Program<Message> for SierpinskiGraph {
}
impl SierpinskiGraph {
fn new() -> SierpinskiGraph {
SierpinskiGraph::default()
}
fn redraw(&mut self) {
self.cache.clear();
}

View file

@ -1,8 +1,8 @@
use iced::widget::{column, container, slider, text, vertical_slider};
use iced::{Element, Length, Sandbox, Settings};
use iced::widget::{center, column, container, slider, text, vertical_slider};
use iced::Element;
pub fn main() -> iced::Result {
Slider::run(Settings::default())
iced::run("Slider - Iced", Slider::update, Slider::view)
}
#[derive(Debug, Clone)]
@ -17,10 +17,8 @@ pub struct Slider {
shift_step: u8,
}
impl Sandbox for Slider {
type Message = Message;
fn new() -> Slider {
impl Slider {
fn new() -> Self {
Slider {
value: 50,
default: 50,
@ -29,10 +27,6 @@ impl Sandbox for Slider {
}
}
fn title(&self) -> String {
String::from("Slider - Iced")
}
fn update(&mut self, message: Message) {
match message {
Message::SliderChanged(value) => {
@ -60,18 +54,20 @@ impl Sandbox for Slider {
let text = text(self.value);
container(
center(
column![
container(v_slider).width(Length::Fill).center_x(),
container(h_slider).width(Length::Fill).center_x(),
container(text).width(Length::Fill).center_x(),
container(v_slider).center_x(),
container(h_slider).center_x(),
container(text).center_x()
]
.spacing(25),
)
.height(Length::Fill)
.width(Length::Fill)
.center_x()
.center_y()
.into()
}
}
impl Default for Slider {
fn default() -> Self {
Self::new()
}
}

View file

@ -6,18 +6,15 @@
//! Inspired by the example found in the MDN docs[1].
//!
//! [1]: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations#An_animated_solar_system
use iced::application;
use iced::executor;
use iced::mouse;
use iced::theme::{self, Theme};
use iced::widget::canvas;
use iced::widget::canvas::gradient;
use iced::widget::canvas::stroke::{self, Stroke};
use iced::widget::canvas::Path;
use iced::widget::canvas::{Geometry, Path};
use iced::window;
use iced::{
Application, Color, Command, Element, Length, Point, Rectangle, Renderer,
Settings, Size, Subscription, Vector,
Color, Element, Length, Point, Rectangle, Renderer, Size, Subscription,
Theme, Vector,
};
use std::time::Instant;
@ -25,12 +22,17 @@ use std::time::Instant;
pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
SolarSystem::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program(
"Solar System - Iced",
SolarSystem::update,
SolarSystem::view,
)
.subscription(SolarSystem::subscription)
.theme(SolarSystem::theme)
.run()
}
#[derive(Default)]
struct SolarSystem {
state: State,
}
@ -40,33 +42,13 @@ enum Message {
Tick(Instant),
}
impl Application for SolarSystem {
type Executor = executor::Default;
type Message = Message;
type Theme = Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
SolarSystem {
state: State::new(),
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Solar system - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl SolarSystem {
fn update(&mut self, message: Message) {
match message {
Message::Tick(instant) => {
self.state.update(instant);
}
}
Command::none()
}
fn view(&self) -> Element<Message> {
@ -77,18 +59,7 @@ impl Application for SolarSystem {
}
fn theme(&self) -> Theme {
Theme::Dark
}
fn style(&self) -> theme::Application {
fn dark_background(_theme: &Theme) -> application::Appearance {
application::Appearance {
background_color: Color::BLACK,
text_color: Color::WHITE,
}
}
theme::Application::custom(dark_background)
Theme::Moonfly
}
fn subscription(&self) -> Subscription<Message> {
@ -159,7 +130,7 @@ impl<Message> canvas::Program<Message> for State {
_theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry> {
) -> Vec<Geometry> {
use std::f32::consts::PI;
let background =
@ -229,3 +200,9 @@ impl<Message> canvas::Program<Message> for State {
vec![background, system]
}
}
impl Default for State {
fn default() -> Self {
Self::new()
}
}

View file

@ -1,27 +1,31 @@
use iced::alignment;
use iced::executor;
use iced::keyboard;
use iced::theme::{self, Theme};
use iced::time;
use iced::widget::{button, column, container, row, text};
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
};
use iced::widget::{button, center, column, row, text};
use iced::{Alignment, Element, Subscription, Theme};
use std::time::{Duration, Instant};
pub fn main() -> iced::Result {
Stopwatch::run(Settings::default())
iced::program("Stopwatch - Iced", Stopwatch::update, Stopwatch::view)
.subscription(Stopwatch::subscription)
.theme(Stopwatch::theme)
.run()
}
#[derive(Default)]
struct Stopwatch {
duration: Duration,
state: State,
}
#[derive(Default)]
enum State {
#[default]
Idle,
Ticking { last_tick: Instant },
Ticking {
last_tick: Instant,
},
}
#[derive(Debug, Clone)]
@ -31,27 +35,8 @@ enum Message {
Tick(Instant),
}
impl Application for Stopwatch {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Stopwatch, Command<Message>) {
(
Stopwatch {
duration: Duration::default(),
state: State::Idle,
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Stopwatch - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl Stopwatch {
fn update(&mut self, message: Message) {
match message {
Message::Toggle => match self.state {
State::Idle => {
@ -73,8 +58,6 @@ impl Application for Stopwatch {
self.duration = Duration::default();
}
}
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
@ -136,7 +119,7 @@ impl Application for Stopwatch {
};
let reset_button = button("Reset")
.style(theme::Button::Destructive)
.style(button::danger)
.on_press(Message::Reset);
let controls = row![toggle_button, reset_button].spacing(20);
@ -145,12 +128,7 @@ impl Application for Stopwatch {
.align_items(Alignment::Center)
.spacing(20);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
fn theme(&self) -> Theme {

View file

@ -1,12 +1,14 @@
use iced::widget::{
button, checkbox, column, container, horizontal_rule, pick_list,
progress_bar, row, scrollable, slider, text, text_input, toggler,
vertical_rule, vertical_space,
button, center, checkbox, column, horizontal_rule, pick_list, progress_bar,
row, scrollable, slider, text, text_input, toggler, vertical_rule,
vertical_space,
};
use iced::{Alignment, Element, Length, Sandbox, Settings, Theme};
use iced::{Alignment, Element, Length, Theme};
pub fn main() -> iced::Result {
Styling::run(Settings::default())
iced::program("Styling - Iced", Styling::update, Styling::view)
.theme(Styling::theme)
.run()
}
#[derive(Default)]
@ -28,17 +30,7 @@ enum Message {
TogglerToggled(bool),
}
impl Sandbox for Styling {
type Message = Message;
fn new() -> Self {
Styling::default()
}
fn title(&self) -> String {
String::from("Styling - Iced")
}
impl Styling {
fn update(&mut self, message: Message) {
match message {
Message::ThemeChanged(theme) => {
@ -114,12 +106,7 @@ impl Sandbox for Styling {
.padding(20)
.max_width(600);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content).into()
}
fn theme(&self) -> Theme {

View file

@ -1,9 +1,8 @@
use iced::theme;
use iced::widget::{checkbox, column, container, svg};
use iced::{color, Element, Length, Sandbox, Settings};
use iced::widget::{center, checkbox, column, container, svg};
use iced::{color, Element, Length};
pub fn main() -> iced::Result {
Tiger::run(Settings::default())
iced::run("SVG - Iced", Tiger::update, Tiger::view)
}
#[derive(Debug, Default)]
@ -16,18 +15,8 @@ pub enum Message {
ToggleColorFilter(bool),
}
impl Sandbox for Tiger {
type Message = Message;
fn new() -> Self {
Tiger::default()
}
fn title(&self) -> String {
String::from("SVG - Iced")
}
fn update(&mut self, message: Self::Message) {
impl Tiger {
fn update(&mut self, message: Message) {
match message {
Message::ToggleColorFilter(apply_color_filter) => {
self.apply_color_filter = apply_color_filter;
@ -35,19 +24,19 @@ impl Sandbox for Tiger {
}
}
fn view(&self) -> Element<Self::Message> {
fn view(&self) -> Element<Message> {
let handle = svg::Handle::from_path(format!(
"{}/resources/tiger.svg",
env!("CARGO_MANIFEST_DIR")
));
let svg = svg(handle).width(Length::Fill).height(Length::Fill).style(
if self.apply_color_filter {
theme::Svg::custom_fn(|_theme| svg::Appearance {
color: Some(color!(0x0000ff)),
})
} else {
theme::Svg::Default
|_theme, _status| svg::Style {
color: if self.apply_color_filter {
Some(color!(0x0000ff))
} else {
None
},
},
);
@ -55,19 +44,12 @@ impl Sandbox for Tiger {
checkbox("Apply a color filter", self.apply_color_filter)
.on_toggle(Message::ToggleColorFilter);
container(
column![
svg,
container(apply_color_filter).width(Length::Fill).center_x()
]
.spacing(20)
.height(Length::Fill),
center(
column![svg, container(apply_color_filter).center_x()]
.spacing(20)
.height(Length::Fill),
)
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
}
}

View file

@ -1,18 +1,19 @@
use iced::widget::{button, column, container, text};
use iced::{
executor, system, Application, Command, Element, Length, Settings, Theme,
};
use bytesize::ByteSize;
use iced::{system, Command, Element};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::program("System Information - Iced", Example::update, Example::view)
.run()
}
#[derive(Default)]
#[allow(clippy::large_enum_variant)]
enum Example {
#[default]
Loading,
Loaded { information: system::Information },
Loaded {
information: system::Information,
},
}
#[derive(Clone, Debug)]
@ -22,23 +23,7 @@ enum Message {
Refresh,
}
impl Application for Example {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Self::Loading,
system::fetch_information(Message::InformationReceived),
)
}
fn title(&self) -> String {
String::from("System Information - Iced")
}
impl Example {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Refresh => {
@ -55,6 +40,8 @@ impl Application for Example {
}
fn view(&self) -> Element<Message> {
use bytesize::ByteSize;
let content: Element<_> = match self {
Example::Loading => text("Loading...").size(40).into(),
Example::Loaded { information } => {
@ -149,11 +136,6 @@ impl Application for Example {
}
};
container(content)
.center_x()
.center_y()
.width(Length::Fill)
.height(Length::Fill)
.into()
container(content).center().into()
}
}

View file

@ -0,0 +1,13 @@
[package]
name = "the_matrix"
version = "0.1.0"
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
edition = "2021"
publish = false
[dependencies]
iced.workspace = true
iced.features = ["canvas", "tokio", "debug"]
rand = "0.8"
tracing-subscriber = "0.3"

View file

@ -0,0 +1,115 @@
use iced::mouse;
use iced::time::{self, Instant};
use iced::widget::canvas;
use iced::{
Color, Element, Font, Length, Point, Rectangle, Renderer, Subscription,
Theme,
};
use std::cell::RefCell;
pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
iced::program("The Matrix - Iced", TheMatrix::update, TheMatrix::view)
.subscription(TheMatrix::subscription)
.antialiasing(true)
.run()
}
#[derive(Default)]
struct TheMatrix {
tick: usize,
}
#[derive(Debug, Clone, Copy)]
enum Message {
Tick(Instant),
}
impl TheMatrix {
fn update(&mut self, message: Message) {
match message {
Message::Tick(_now) => {
self.tick += 1;
}
}
}
fn view(&self) -> Element<Message> {
canvas(self as &Self)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn subscription(&self) -> Subscription<Message> {
time::every(std::time::Duration::from_millis(50)).map(Message::Tick)
}
}
impl<Message> canvas::Program<Message> for TheMatrix {
type State = RefCell<Vec<canvas::Cache>>;
fn draw(
&self,
state: &Self::State,
renderer: &Renderer,
_theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry> {
use rand::distributions::Distribution;
use rand::Rng;
const CELL_SIZE: f32 = 10.0;
let mut caches = state.borrow_mut();
if caches.is_empty() {
let group = canvas::Group::unique();
caches.resize_with(30, || canvas::Cache::with_group(group));
}
vec![caches[self.tick % caches.len()].draw(
renderer,
bounds.size(),
|frame| {
frame.fill_rectangle(Point::ORIGIN, frame.size(), Color::BLACK);
let mut rng = rand::thread_rng();
let rows = (frame.height() / CELL_SIZE).ceil() as usize;
let columns = (frame.width() / CELL_SIZE).ceil() as usize;
for row in 0..rows {
for column in 0..columns {
let position = Point::new(
column as f32 * CELL_SIZE,
row as f32 * CELL_SIZE,
);
let alphas = [0.05, 0.1, 0.2, 0.5];
let weights = [10, 4, 2, 1];
let distribution =
rand::distributions::WeightedIndex::new(weights)
.expect("Create distribution");
frame.fill_text(canvas::Text {
content: rng.gen_range('!'..'z').to_string(),
position,
color: Color {
a: alphas[distribution.sample(&mut rng)],
g: 1.0,
..Color::BLACK
},
size: CELL_SIZE.into(),
font: Font::MONOSPACE,
..canvas::Text::default()
});
}
}
},
)]
}
}

View file

@ -1,21 +1,19 @@
use iced::event::{self, Event};
use iced::executor;
use iced::keyboard;
use iced::keyboard::key;
use iced::widget::{
self, button, column, container, pick_list, row, slider, text, text_input,
};
use iced::{
Alignment, Application, Command, Element, Length, Settings, Subscription,
self, button, center, column, pick_list, row, slider, text, text_input,
};
use iced::{Alignment, Command, Element, Length, Subscription};
use toast::{Status, Toast};
pub fn main() -> iced::Result {
App::run(Settings::default())
iced::program("Toast - Iced", App::update, App::view)
.subscription(App::subscription)
.run()
}
#[derive(Default)]
struct App {
toasts: Vec<Toast>,
editing: Toast,
@ -34,32 +32,20 @@ enum Message {
Event(Event),
}
impl Application for App {
type Executor = executor::Default;
type Message = Message;
type Theme = iced::Theme;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(
App {
toasts: vec![Toast {
title: "Example Toast".into(),
body: "Add more toasts in the form below!".into(),
status: Status::Primary,
}],
timeout_secs: toast::DEFAULT_TIMEOUT,
..Default::default()
},
Command::none(),
)
impl App {
fn new() -> Self {
App {
toasts: vec![Toast {
title: "Example Toast".into(),
body: "Add more toasts in the form below!".into(),
status: Status::Primary,
}],
timeout_secs: toast::DEFAULT_TIMEOUT,
editing: Toast::default(),
}
}
fn title(&self) -> String {
String::from("Toast - Iced")
}
fn subscription(&self) -> Subscription<Self::Message> {
fn subscription(&self) -> Subscription<Message> {
event::listen().map(Message::Event)
}
@ -106,8 +92,8 @@ impl Application for App {
}
}
fn view<'a>(&'a self) -> Element<'a, Message> {
let subtitle = |title, content: Element<'a, Message>| {
fn view(&self) -> Element<'_, Message> {
let subtitle = |title, content: Element<'static, Message>| {
column![text(title).size(14), content].spacing(5)
};
@ -116,7 +102,7 @@ impl Application for App {
.then_some(Message::Add),
);
let content = container(
let content = center(
column![
subtitle(
"Title",
@ -160,11 +146,7 @@ impl Application for App {
]
.spacing(10)
.max_width(200),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y();
);
toast::Manager::new(content, &self.toasts, Message::Close)
.timeout(self.timeout_secs)
@ -172,6 +154,12 @@ impl Application for App {
}
}
impl Default for App {
fn default() -> Self {
Self::new()
}
}
mod toast {
use std::fmt;
use std::time::{Duration, Instant};
@ -209,27 +197,6 @@ mod toast {
&[Self::Primary, Self::Secondary, Self::Success, Self::Danger];
}
impl container::StyleSheet for Status {
type Style = Theme;
fn appearance(&self, theme: &Theme) -> container::Appearance {
let palette = theme.extended_palette();
let pair = match self {
Status::Primary => palette.primary.weak,
Status::Secondary => palette.secondary.weak,
Status::Success => palette.success.weak,
Status::Danger => palette.danger.weak,
};
container::Appearance {
background: Some(pair.color.into()),
text_color: pair.text.into(),
..Default::default()
}
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@ -282,14 +249,17 @@ mod toast {
)
.width(Length::Fill)
.padding(5)
.style(
theme::Container::Custom(Box::new(toast.status))
),
.style(match toast.status {
Status::Primary => primary,
Status::Secondary => secondary,
Status::Success => success,
Status::Danger => danger,
}),
horizontal_rule(1),
container(text(toast.body.as_str()))
.width(Length::Fill)
.padding(5)
.style(theme::Container::Box),
.style(container::rounded_box),
])
.max_width(200)
.into()
@ -676,4 +646,36 @@ mod toast {
Element::new(manager)
}
}
fn styled(pair: theme::palette::Pair) -> container::Style {
container::Style {
background: Some(pair.color.into()),
text_color: pair.text.into(),
..Default::default()
}
}
fn primary(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
styled(palette.primary.weak)
}
fn secondary(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
styled(palette.secondary.weak)
}
fn success(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
styled(palette.success.weak)
}
fn danger(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
styled(palette.danger.weak)
}
}

View file

@ -1,14 +1,11 @@
use iced::alignment::{self, Alignment};
use iced::font::{self, Font};
use iced::keyboard;
use iced::theme::{self, Theme};
use iced::widget::{
self, button, checkbox, column, container, keyed_column, row, scrollable,
text, text_input, Text,
self, button, center, checkbox, column, container, keyed_column, row,
scrollable, text, text_input, Text,
};
use iced::window;
use iced::{Application, Element};
use iced::{Color, Command, Length, Settings, Size, Subscription};
use iced::{Command, Element, Font, Length, Subscription};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
@ -20,17 +17,17 @@ pub fn main() -> iced::Result {
#[cfg(not(target_arch = "wasm32"))]
tracing_subscriber::fmt::init();
Todos::run(Settings {
window: window::Settings {
size: Size::new(500.0, 800.0),
..window::Settings::default()
},
..Settings::default()
})
iced::program(Todos::title, Todos::update, Todos::view)
.load(Todos::load)
.subscription(Todos::subscription)
.font(include_bytes!("../fonts/icons.ttf").as_slice())
.window_size((500.0, 800.0))
.run()
}
#[derive(Debug)]
#[derive(Default, Debug)]
enum Todos {
#[default]
Loading,
Loaded(State),
}
@ -47,7 +44,6 @@ struct State {
#[derive(Debug, Clone)]
enum Message {
Loaded(Result<SavedState, LoadError>),
FontLoaded(Result<(), font::Error>),
Saved(Result<(), SaveError>),
InputChanged(String),
CreateTask,
@ -57,21 +53,9 @@ enum Message {
ToggleFullscreen(window::Mode),
}
impl Application for Todos {
type Message = Message;
type Theme = Theme;
type Executor = iced::executor::Default;
type Flags = ();
fn new(_flags: ()) -> (Todos, Command<Message>) {
(
Todos::Loading,
Command::batch(vec![
font::load(include_bytes!("../fonts/icons.ttf").as_slice())
.map(Message::FontLoaded),
Command::perform(SavedState::load(), Message::Loaded),
]),
)
impl Todos {
fn load() -> Command<Message> {
Command::perform(SavedState::load(), Message::Loaded)
}
fn title(&self) -> String {
@ -168,7 +152,7 @@ impl Application for Todos {
Message::ToggleFullscreen(mode) => {
window::change_mode(window::Id::MAIN, mode)
}
_ => Command::none(),
Message::Loaded(_) => Command::none(),
};
if !saved {
@ -209,7 +193,7 @@ impl Application for Todos {
let title = text("todos")
.width(Length::Fill)
.size(100)
.style(Color::from([0.5, 0.5, 0.5]))
.color([0.5, 0.5, 0.5])
.horizontal_alignment(alignment::Horizontal::Center);
let input = text_input("What needs to be done?", input_value)
@ -254,7 +238,7 @@ impl Application for Todos {
.spacing(20)
.max_width(800);
scrollable(container(content).padding(40).center_x()).into()
scrollable(container(content).center_x().padding(40)).into()
}
}
}
@ -355,6 +339,7 @@ impl Task {
let checkbox = checkbox(&self.description, self.completed)
.on_toggle(TaskMessage::Completed)
.width(Length::Fill)
.size(17)
.text_shaping(text::Shaping::Advanced);
row![
@ -362,7 +347,7 @@ impl Task {
button(edit_icon())
.on_press(TaskMessage::Edit)
.padding(10)
.style(theme::Button::Text),
.style(button::text),
]
.spacing(20)
.align_items(Alignment::Center)
@ -385,7 +370,7 @@ impl Task {
)
.on_press(TaskMessage::Delete)
.padding(10)
.style(theme::Button::Destructive)
.style(button::danger)
]
.spacing(20)
.align_items(Alignment::Center)
@ -402,9 +387,9 @@ fn view_controls(tasks: &[Task], current_filter: Filter) -> Element<Message> {
let label = text(label);
let button = button(label).style(if filter == current_filter {
theme::Button::Primary
button::primary
} else {
theme::Button::Text
button::text
});
button.on_press(Message::FilterChanged(filter)).padding(8)
@ -450,27 +435,23 @@ impl Filter {
}
fn loading_message<'a>() -> Element<'a, Message> {
container(
center(
text("Loading...")
.horizontal_alignment(alignment::Horizontal::Center)
.size(50),
)
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.into()
}
fn empty_message(message: &str) -> Element<'_, Message> {
container(
center(
text(message)
.width(Length::Fill)
.size(25)
.horizontal_alignment(alignment::Horizontal::Center)
.style(Color::from([0.7, 0.7, 0.7])),
.color([0.7, 0.7, 0.7]),
)
.height(200)
.center_y()
.into()
}

View file

@ -1,13 +1,13 @@
use iced::theme;
use iced::widget::tooltip::Position;
use iced::widget::{button, container, tooltip};
use iced::{Element, Length, Sandbox, Settings};
use iced::widget::{button, center, container, tooltip};
use iced::Element;
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::run("Tooltip - Iced", Tooltip::update, Tooltip::view)
}
struct Example {
#[derive(Default)]
struct Tooltip {
position: Position,
}
@ -16,28 +16,16 @@ enum Message {
ChangePosition,
}
impl Sandbox for Example {
type Message = Message;
fn new() -> Self {
Self {
position: Position::Bottom,
}
}
fn title(&self) -> String {
String::from("Tooltip - Iced")
}
impl Tooltip {
fn update(&mut self, message: Message) {
match message {
Message::ChangePosition => {
let position = match &self.position {
Position::FollowCursor => Position::Top,
Position::Top => Position::Bottom,
Position::Bottom => Position::Left,
Position::Left => Position::Right,
Position::Right => Position::FollowCursor,
Position::FollowCursor => Position::Top,
};
self.position = position;
@ -53,14 +41,9 @@ impl Sandbox for Example {
self.position,
)
.gap(10)
.style(theme::Container::Box);
.style(container::rounded_box);
container(tooltip)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(tooltip).into()
}
}

View file

@ -1,11 +1,10 @@
use iced::alignment::{self, Alignment};
use iced::theme;
use iced::widget::{
checkbox, column, container, horizontal_space, image, radio, row,
button, checkbox, column, container, horizontal_space, image, radio, row,
scrollable, slider, text, text_input, toggler, vertical_space,
};
use iced::widget::{Button, Column, Container, Slider};
use iced::{Color, Element, Font, Length, Pixels, Sandbox, Settings};
use iced::{Color, Element, Font, Length, Pixels};
pub fn main() -> iced::Result {
#[cfg(target_arch = "wasm32")]
@ -17,24 +16,18 @@ pub fn main() -> iced::Result {
#[cfg(not(target_arch = "wasm32"))]
tracing_subscriber::fmt::init();
Tour::run(Settings::default())
iced::program(Tour::title, Tour::update, Tour::view)
.centered()
.run()
}
#[derive(Default)]
pub struct Tour {
steps: Steps,
debug: bool,
}
impl Sandbox for Tour {
type Message = Message;
fn new() -> Tour {
Tour {
steps: Steps::new(),
debug: false,
}
}
impl Tour {
fn title(&self) -> String {
format!("{} - Iced", self.steps.title())
}
@ -56,18 +49,17 @@ impl Sandbox for Tour {
fn view(&self) -> Element<Message> {
let Tour { steps, .. } = self;
let controls = row![]
.push_maybe(steps.has_previous().then(|| {
button("Back")
.on_press(Message::BackPressed)
.style(theme::Button::Secondary)
}))
.push(horizontal_space())
.push_maybe(
steps
.can_continue()
.then(|| button("Next").on_press(Message::NextPressed)),
);
let controls =
row![]
.push_maybe(steps.has_previous().then(|| {
padded_button("Back")
.on_press(Message::BackPressed)
.style(button::secondary)
}))
.push(horizontal_space())
.push_maybe(steps.can_continue().then(|| {
padded_button("Next").on_press(Message::NextPressed)
}));
let content: Element<_> = column![
steps.view(self.debug).map(Message::StepMessage),
@ -84,11 +76,10 @@ impl Sandbox for Tour {
} else {
content
})
.width(Length::Fill)
.center_x(),
);
container(scrollable).height(Length::Fill).center_y().into()
container(scrollable).center_y().into()
}
}
@ -173,6 +164,12 @@ impl Steps {
}
}
impl Default for Steps {
fn default() -> Self {
Steps::new()
}
}
enum Step {
Welcome,
Slider {
@ -359,7 +356,7 @@ impl<'a> Step {
.into()
}
fn container(title: &str) -> Column<'a, StepMessage> {
fn container(title: &str) -> Column<'_, StepMessage> {
column![text(title).size(50)].spacing(20)
}
@ -474,7 +471,7 @@ impl<'a> Step {
let color_section = column![
"And its color:",
text(format!("{color:?}")).style(color),
text(format!("{color:?}")).color(color),
color_sliders,
]
.padding(20)
@ -591,7 +588,7 @@ impl<'a> Step {
value: &str,
is_secure: bool,
is_showing_icon: bool,
) -> Column<'a, StepMessage> {
) -> Column<'_, StepMessage> {
let mut text_input = text_input("Type something to continue...", value)
.on_input(StepMessage::InputChanged)
.padding(10)
@ -672,12 +669,11 @@ fn ferris<'a>(
.filter_method(filter_method)
.width(width),
)
.width(Length::Fill)
.center_x()
}
fn button<'a, Message: Clone>(label: &str) -> Button<'a, Message> {
iced::widget::button(text(label)).padding([12, 24])
fn padded_button<Message: Clone>(label: &str) -> Button<'_, Message> {
button(text(label)).padding([12, 24])
}
fn color_slider<'a>(

View file

@ -1,12 +1,11 @@
use iced::event::{self, Event};
use iced::executor;
use iced::widget::{container, text};
use iced::{
Application, Command, Element, Length, Settings, Subscription, Theme,
};
use iced::widget::{center, text};
use iced::{Element, Subscription};
pub fn main() -> iced::Result {
App::run(Settings::default())
iced::program("URL Handler - Iced", App::update, App::view)
.subscription(App::subscription)
.run()
}
#[derive(Debug, Default)]
@ -19,21 +18,8 @@ enum Message {
EventOccurred(Event),
}
impl Application for App {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();
fn new(_flags: ()) -> (App, Command<Message>) {
(App::default(), Command::none())
}
fn title(&self) -> String {
String::from("Url - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
impl App {
fn update(&mut self, message: Message) {
match message {
Message::EventOccurred(event) => {
if let Event::PlatformSpecific(
@ -45,9 +31,7 @@ impl Application for App {
self.url = Some(url);
}
}
};
Command::none()
}
}
fn subscription(&self) -> Subscription<Message> {
@ -60,11 +44,6 @@ impl Application for App {
None => text("No URL received yet!"),
};
container(content.size(48))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
center(content.size(48)).into()
}
}

View file

@ -3,18 +3,20 @@ use iced::mouse;
use iced::widget::{
canvas, checkbox, column, horizontal_space, row, slider, text,
};
use iced::{
Element, Length, Point, Rectangle, Renderer, Sandbox, Settings, Theme,
Vector,
};
use iced::{Element, Length, Point, Rectangle, Renderer, Theme, Vector};
pub fn main() -> iced::Result {
VectorialText::run(Settings {
antialiasing: true,
..Settings::default()
})
iced::program(
"Vectorial Text - Iced",
VectorialText::update,
VectorialText::view,
)
.theme(|_| Theme::Dark)
.antialiasing(true)
.run()
}
#[derive(Default)]
struct VectorialText {
state: State,
}
@ -27,19 +29,7 @@ enum Message {
ToggleJapanese(bool),
}
impl Sandbox for VectorialText {
type Message = Message;
fn new() -> Self {
Self {
state: State::new(),
}
}
fn title(&self) -> String {
String::from("Vectorial Text - Iced")
}
impl VectorialText {
fn update(&mut self, message: Message) {
match message {
Message::SizeChanged(size) => {
@ -106,10 +96,6 @@ impl Sandbox for VectorialText {
.padding(20)
.into()
}
fn theme(&self) -> Theme {
Theme::Dark
}
}
struct State {
@ -170,3 +156,9 @@ impl<Message> canvas::Program<Message> for State {
vec![geometry]
}
}
impl Default for State {
fn default() -> Self {
State::new()
}
}

View file

@ -1,20 +1,22 @@
use iced::event::{self, Event};
use iced::executor;
use iced::mouse;
use iced::theme::{self, Theme};
use iced::widget::{
column, container, horizontal_space, row, scrollable, text, vertical_space,
};
use iced::window;
use iced::{
Alignment, Application, Color, Command, Element, Font, Length, Point,
Rectangle, Settings, Subscription,
Alignment, Color, Command, Element, Font, Length, Point, Rectangle,
Subscription, Theme,
};
pub fn main() -> iced::Result {
Example::run(Settings::default())
iced::program("Visible Bounds - Iced", Example::update, Example::view)
.subscription(Example::subscription)
.theme(|_| Theme::Dark)
.run()
}
#[derive(Default)]
struct Example {
mouse_position: Option<Point>,
outer_bounds: Option<Rectangle>,
@ -30,27 +32,7 @@ enum Message {
InnerBoundsFetched(Option<Rectangle>),
}
impl Application for Example {
type Message = Message;
type Theme = Theme;
type Flags = ();
type Executor = executor::Default;
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
Self {
mouse_position: None,
outer_bounds: None,
inner_bounds: None,
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Visible bounds - Iced")
}
impl Example {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::MouseMoved(position) => {
@ -82,7 +64,10 @@ impl Application for Example {
row![
text(label),
horizontal_space(),
text(value).font(Font::MONOSPACE).size(14).style(color),
text(value)
.font(Font::MONOSPACE)
.size(14)
.color_maybe(color),
]
.height(40)
.align_items(Alignment::Center)
@ -102,13 +87,12 @@ impl Application for Example {
})
.unwrap_or_default()
{
Color {
Some(Color {
g: 1.0,
..Color::BLACK
}
.into()
})
} else {
theme::Text::Default
None
},
)
};
@ -120,7 +104,7 @@ impl Application for Example {
Some(Point { x, y }) => format!("({x}, {y})"),
None => "unknown".to_string(),
},
theme::Text::Default,
None,
),
view_bounds("Outer container", self.outer_bounds),
view_bounds("Inner container", self.inner_bounds),
@ -131,7 +115,7 @@ impl Application for Example {
container(text("I am the outer container!"))
.id(OUTER_CONTAINER.clone())
.padding(40)
.style(theme::Container::Box),
.style(container::rounded_box),
vertical_space().height(400),
scrollable(
column![
@ -140,7 +124,7 @@ impl Application for Example {
container(text("I am the inner container!"))
.id(INNER_CONTAINER.clone())
.padding(40)
.style(theme::Container::Box),
.style(container::rounded_box),
vertical_space().height(400),
]
.padding(20)
@ -171,10 +155,6 @@ impl Application for Example {
_ => None,
})
}
fn theme(&self) -> Theme {
Theme::Dark
}
}
use once_cell::sync::Lazy;

View file

@ -2,6 +2,7 @@ pub mod server;
use iced::futures;
use iced::subscription::{self, Subscription};
use iced::widget::text;
use futures::channel::mpsc;
use futures::sink::SinkExt;
@ -136,16 +137,24 @@ impl Message {
pub fn disconnected() -> Self {
Message::Disconnected
}
pub fn as_str(&self) -> &str {
match self {
Message::Connected => "Connected successfully!",
Message::Disconnected => "Connection lost... Retrying...",
Message::User(message) => message.as_str(),
}
}
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Message::Connected => write!(f, "Connected successfully!"),
Message::Disconnected => {
write!(f, "Connection lost... Retrying...")
}
Message::User(message) => write!(f, "{message}"),
}
f.write_str(self.as_str())
}
}
impl<'a> text::IntoFragment<'a> for &'a Message {
fn into_fragment(self) -> text::Fragment<'a> {
text::Fragment::Borrowed(self.as_str())
}
}

View file

@ -1,17 +1,17 @@
mod echo;
use iced::alignment::{self, Alignment};
use iced::executor;
use iced::widget::{
button, column, container, row, scrollable, text, text_input,
};
use iced::{
Application, Color, Command, Element, Length, Settings, Subscription, Theme,
self, button, center, column, row, scrollable, text, text_input,
};
use iced::{color, Command, Element, Length, Subscription};
use once_cell::sync::Lazy;
pub fn main() -> iced::Result {
WebSocket::run(Settings::default())
iced::program("WebSocket - Iced", WebSocket::update, WebSocket::view)
.load(WebSocket::load)
.subscription(WebSocket::subscription)
.run()
}
#[derive(Default)]
@ -29,21 +29,12 @@ enum Message {
Server,
}
impl Application for WebSocket {
type Message = Message;
type Theme = Theme;
type Flags = ();
type Executor = executor::Default;
fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
(
Self::default(),
impl WebSocket {
fn load() -> Command<Message> {
Command::batch([
Command::perform(echo::server::run(), |_| Message::Server),
)
}
fn title(&self) -> String {
String::from("WebSocket - Iced")
widget::focus_next(),
])
}
fn update(&mut self, message: Message) -> Command<Message> {
@ -97,21 +88,15 @@ impl Application for WebSocket {
fn view(&self) -> Element<Message> {
let message_log: Element<_> = if self.messages.is_empty() {
container(
center(
text("Your messages will appear here...")
.style(Color::from_rgb8(0x88, 0x88, 0x88)),
.color(color!(0x888888)),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} else {
scrollable(
column(
self.messages.iter().cloned().map(text).map(Element::from),
)
.spacing(10),
column(self.messages.iter().map(text).map(Element::from))
.spacing(10),
)
.id(MESSAGE_LOG.clone())
.height(Length::Fill)