From 332874f12aa3f2f8f65986e54b4a2957227fb295 Mon Sep 17 00:00:00 2001 From: Hojjat Date: Fri, 24 Apr 2026 15:31:34 -0600 Subject: [PATCH] Remove `max_width` limit for `rustfmt` Following upstream: https://github.com/iced-rs/iced/commit/feb996f2d9b526752387d687187ebf5b6160547a --- accessibility/src/a11y_tree.rs | 4 +- accessibility/src/id.rs | 20 +- accessibility/src/node.rs | 3 +- beacon/src/client.rs | 26 +- beacon/src/lib.rs | 215 ++- beacon/src/span.rs | 17 +- benches/wgpu.rs | 62 +- core/src/animation.rs | 6 +- core/src/background.rs | 4 +- core/src/clipboard.rs | 28 +- core/src/color.rs | 16 +- core/src/element.rs | 72 +- core/src/event/wayland/output.rs | 4 +- core/src/event/wayland/overlap_notify.rs | 5 +- core/src/gradient.rs | 18 +- core/src/id.rs | 20 +- core/src/image.rs | 17 +- core/src/layout.rs | 20 +- core/src/layout/flex.rs | 62 +- core/src/layout/limits.rs | 29 +- core/src/layout/node.rs | 14 +- core/src/mouse/click.rs | 10 +- core/src/mouse/cursor.rs | 16 +- core/src/overlay/element.rs | 26 +- core/src/overlay/group.rs | 16 +- core/src/overlay/nested.rs | 28 +- core/src/rectangle.rs | 29 +- core/src/renderer.rs | 24 +- core/src/renderer/null.rs | 45 +- core/src/shell.rs | 21 +- core/src/size.rs | 9 +- core/src/text.rs | 9 +- core/src/text/paragraph.rs | 7 +- core/src/theme.rs | 9 +- core/src/theme/palette.rs | 30 +- core/src/transformation.rs | 9 +- core/src/widget/operation.rs | 211 +-- core/src/widget/operation/focusable.rs | 75 +- core/src/widget/operation/scrollable.rs | 17 +- core/src/widget/operation/search_id.rs | 12 +- core/src/widget/operation/text_input.rs | 41 +- core/src/widget/text.rs | 31 +- core/src/widget/tree.rs | 116 +- core/src/window/icon.rs | 6 +- core/src/window/screenshot.rs | 32 +- debug/src/lib.rs | 30 +- devtools/src/comet.rs | 10 +- devtools/src/lib.rs | 62 +- examples/arc/src/main.rs | 9 +- examples/bezier_tool/src/main.rs | 33 +- examples/changelog/src/changelog.rs | 12 +- examples/changelog/src/main.rs | 110 +- examples/checkbox/src/main.rs | 3 +- examples/clock/src/main.rs | 35 +- examples/color_palette/src/main.rs | 35 +- examples/counter/src/main.rs | 4 +- examples/custom_quad/src/main.rs | 22 +- examples/custom_shader/src/scene.rs | 6 +- examples/custom_shader/src/scene/camera.rs | 7 +- examples/custom_shader/src/scene/pipeline.rs | 470 +++---- .../custom_shader/src/scene/pipeline/cube.rs | 6 +- examples/custom_widget/src/main.rs | 3 +- examples/delineate/src/main.rs | 23 +- examples/download_progress/src/main.rs | 34 +- examples/editor/src/main.rs | 34 +- examples/ferris/src/main.rs | 33 +- examples/gallery/src/civitai.rs | 14 +- examples/gallery/src/main.rs | 111 +- examples/game_of_life/src/main.rs | 170 +-- examples/game_of_life/src/preset.rs | 4 +- examples/geometry/src/main.rs | 18 +- examples/gradient/src/main.rs | 15 +- examples/layout/src/main.rs | 37 +- examples/lazy/src/main.rs | 15 +- examples/list/src/main.rs | 13 +- examples/loading_spinners/src/circular.rs | 72 +- examples/loading_spinners/src/easing.rs | 20 +- examples/loading_spinners/src/linear.rs | 22 +- examples/loading_spinners/src/main.rs | 12 +- examples/loupe/src/main.rs | 14 +- examples/markdown/src/main.rs | 18 +- examples/modal/src/main.rs | 17 +- examples/multi_window/src/main.rs | 27 +- examples/multitouch/src/main.rs | 14 +- examples/pane_grid/src/main.rs | 55 +- examples/pokedex/src/main.rs | 7 +- examples/progress_bar/src/main.rs | 17 +- examples/qr_code/src/main.rs | 29 +- examples/screenshot/src/main.rs | 70 +- examples/scrollable/src/main.rs | 219 ++- examples/sctk_drag/src/dnd_destination.rs | 148 +- examples/sctk_drag/src/dnd_source.rs | 90 +- examples/sctk_drag/src/main.rs | 26 +- examples/sctk_lazy/src/main.rs | 17 +- examples/sctk_session_lock/src/main.rs | 13 +- examples/sctk_subsurface/src/main.rs | 47 +- .../src/subsurface_container.rs | 74 +- examples/sctk_subsurface/src/wayland.rs | 4 +- examples/sctk_subsurface_gst/src/pipewire.rs | 11 +- examples/sctk_subsurface_img/Cargo.toml | 2 +- examples/sctk_subsurface_img/src/main.rs | 30 +- examples/sctk_todos/src/main.rs | 41 +- examples/sierpinski_triangle/src/main.rs | 17 +- examples/solar_system/src/main.rs | 48 +- examples/stopwatch/src/main.rs | 16 +- examples/styling/src/main.rs | 86 +- examples/svg/src/main.rs | 21 +- examples/table/src/main.rs | 25 +- examples/the_matrix/src/main.rs | 25 +- examples/toast/src/main.rs | 83 +- examples/todos/src/main.rs | 90 +- examples/tooltip/src/main.rs | 3 +- examples/tour/src/main.rs | 33 +- examples/websocket/src/echo.rs | 6 +- examples/websocket/src/main.rs | 26 +- futures/src/backend/default.rs | 11 +- futures/src/backend/native/smol.rs | 4 +- futures/src/backend/native/tokio.rs | 4 +- futures/src/backend/wasm/wasm_bindgen.rs | 4 +- futures/src/runtime.rs | 29 +- futures/src/stream.rs | 5 +- futures/src/subscription.rs | 27 +- futures/src/subscription/tracker.rs | 16 +- graphics/src/cache.rs | 10 +- graphics/src/compositor.rs | 29 +- graphics/src/geometry/cache.rs | 4 +- graphics/src/geometry/frame.rs | 48 +- graphics/src/geometry/path.rs | 6 +- graphics/src/geometry/path/builder.rs | 23 +- graphics/src/geometry/text.rs | 36 +- graphics/src/gradient.rs | 27 +- graphics/src/image.rs | 24 +- graphics/src/mesh.rs | 5 +- graphics/src/settings.rs | 6 +- graphics/src/text.rs | 48 +- graphics/src/text/cache.rs | 13 +- graphics/src/text/editor.rs | 157 +-- graphics/src/text/paragraph.rs | 62 +- graphics/src/viewport.rs | 5 +- highlighter/src/lib.rs | 50 +- program/src/lib.rs | 165 +-- renderer/src/fallback.rs | 150 +- renderer/src/lib.rs | 5 +- runtime/src/clipboard.rs | 6 +- runtime/src/dnd.rs | 6 +- runtime/src/image.rs | 4 +- runtime/src/lib.rs | 4 +- .../platform_specific/wayland/activation.rs | 2 +- .../wayland/layer_surface.rs | 35 +- runtime/src/platform_specific/wayland/mod.rs | 24 +- .../src/platform_specific/wayland/popup.rs | 18 +- .../platform_specific/wayland/subsurface.rs | 12 +- runtime/src/system.rs | 4 +- runtime/src/task.rs | 85 +- runtime/src/user_interface.rs | 213 ++- runtime/src/widget/operation.rs | 14 +- runtime/src/widget/selector.rs | 4 +- runtime/src/window.rs | 70 +- rustfmt.toml | 2 - selector/src/find.rs | 53 +- selector/src/target.rs | 5 +- src/application.rs | 68 +- src/application/timed.rs | 42 +- src/daemon.rs | 79 +- src/error.rs | 8 +- src/lib.rs | 38 +- src/time.rs | 6 +- test/src/emulator.rs | 43 +- test/src/error.rs | 4 +- test/src/ice.rs | 13 +- test/src/instruction.rs | 255 ++-- test/src/lib.rs | 19 +- test/src/simulator.rs | 47 +- tester/src/lib.rs | 249 ++-- tester/src/recorder.rs | 80 +- tiny_skia/src/engine.rs | 252 ++-- tiny_skia/src/geometry.rs | 70 +- tiny_skia/src/layer.rs | 40 +- tiny_skia/src/lib.rs | 86 +- tiny_skia/src/raster.rs | 19 +- tiny_skia/src/text.rs | 56 +- tiny_skia/src/vector.rs | 40 +- tiny_skia/src/window/compositor.rs | 51 +- wgpu/src/buffer.rs | 17 +- wgpu/src/color.rs | 222 ++- wgpu/src/engine.rs | 17 +- wgpu/src/geometry.rs | 283 ++-- wgpu/src/image/atlas.rs | 90 +- wgpu/src/image/cache.rs | 98 +- wgpu/src/image/mod.rs | 399 +++--- wgpu/src/image/raster.rs | 6 +- wgpu/src/image/vector.rs | 28 +- wgpu/src/layer.rs | 55 +- wgpu/src/lib.rs | 289 ++-- wgpu/src/primitive.rs | 28 +- wgpu/src/quad.rs | 47 +- wgpu/src/quad/gradient.rs | 160 +-- wgpu/src/quad/solid.rs | 149 +- wgpu/src/text.rs | 242 ++-- wgpu/src/triangle.rs | 377 +++--- wgpu/src/triangle/msaa.rs | 224 ++- wgpu/src/window.rs | 6 +- wgpu/src/window/compositor.rs | 93 +- wgpu/src/window/wayland.rs | 13 +- wgpu/src/window/x11.rs | 46 +- widget/src/action.rs | 4 +- widget/src/button.rs | 93 +- widget/src/canvas.rs | 55 +- widget/src/checkbox.rs | 39 +- widget/src/column.rs | 63 +- widget/src/combo_box.rs | 132 +- widget/src/container.rs | 73 +- widget/src/float.rs | 24 +- widget/src/grid.rs | 59 +- widget/src/helpers.rs | 117 +- widget/src/image.rs | 32 +- widget/src/image/viewer.rs | 51 +- widget/src/keyed/column.rs | 64 +- widget/src/lazy.rs | 76 +- widget/src/lazy/component.rs | 83 +- widget/src/list.rs | 186 +-- widget/src/markdown.rs | 155 +-- widget/src/mouse_area.rs | 77 +- widget/src/overlay/menu.rs | 93 +- widget/src/pane_grid.rs | 195 +-- widget/src/pane_grid/axis.rs | 25 +- widget/src/pane_grid/content.rs | 74 +- widget/src/pane_grid/controls.rs | 12 +- widget/src/pane_grid/node.rs | 32 +- widget/src/pane_grid/state.rs | 52 +- widget/src/pane_grid/title_bar.rs | 142 +- widget/src/pick_list.rs | 89 +- widget/src/pin.rs | 15 +- widget/src/progress_bar.rs | 15 +- widget/src/qr_code.rs | 42 +- widget/src/radio.rs | 23 +- widget/src/responsive.rs | 26 +- widget/src/row.rs | 59 +- widget/src/rule.rs | 10 +- widget/src/scrollable.rs | 613 +++------ widget/src/sensor.rs | 57 +- widget/src/shader.rs | 15 +- widget/src/slider.rs | 131 +- widget/src/space.rs | 3 +- widget/src/stack.rs | 79 +- widget/src/svg.rs | 32 +- widget/src/table.rs | 76 +- widget/src/text/rich.rs | 104 +- widget/src/text_editor.rs | 239 +--- widget/src/text_input.rs | 351 ++--- widget/src/text_input/cursor.rs | 26 +- widget/src/text_input/value.rs | 28 +- widget/src/themer.rs | 19 +- widget/src/toggler.rs | 58 +- widget/src/tooltip.rs | 92 +- widget/src/vertical_slider.rs | 50 +- winit/src/a11y.rs | 13 +- winit/src/application/drag_resize.rs | 31 +- winit/src/clipboard.rs | 94 +- winit/src/conversion.rs | 995 ++++++-------- winit/src/lib.rs | 684 ++++------ winit/src/platform_specific/mod.rs | 38 +- .../wayland/commands/activation.rs | 21 +- .../wayland/commands/corner_radius.rs | 9 +- .../commands/keyboard_shortcuts_inhibit.rs | 4 +- .../wayland/commands/layer_surface.rs | 14 +- .../wayland/commands/overlap_notify.rs | 7 +- .../wayland/commands/popup.rs | 24 +- .../wayland/commands/session_lock.rs | 9 +- .../wayland/commands/subsurface.rs | 14 +- .../platform_specific/wayland/conversion.rs | 4 +- .../wayland/event_loop/mod.rs | 361 +++-- .../wayland/event_loop/proxy.rs | 22 +- .../wayland/event_loop/state.rs | 1201 +++++++++-------- .../wayland/handlers/compositor.rs | 3 +- .../wayland/handlers/ext_background_effect.rs | 19 +- .../wayland/handlers/output.rs | 4 +- .../wayland/handlers/overlap.rs | 16 +- .../wayland/handlers/seat/keyboard.rs | 151 +-- .../seat/keyboard_shortcuts_inhibit.rs | 7 +- .../wayland/handlers/seat/pointer.rs | 38 +- .../wayland/handlers/seat/seat.rs | 42 +- .../wayland/handlers/seat/touch.rs | 37 +- .../wayland/handlers/session_lock.rs | 26 +- .../wayland/handlers/shell/corner_radius.rs | 30 +- .../wayland/handlers/shell/layer.rs | 36 +- .../wayland/handlers/shell/mod.rs | 2 +- .../wayland/handlers/shell/xdg_popup.rs | 47 +- .../wayland/handlers/shell/xdg_window.rs | 4 +- .../wayland/handlers/text_input.rs | 45 +- .../wayland/handlers/toplevel.rs | 4 +- .../wayland/handlers/wp_fractional_scaling.rs | 14 +- .../wayland/handlers/wp_viewporter.rs | 6 +- winit/src/platform_specific/wayland/keymap.rs | 62 +- winit/src/platform_specific/wayland/mod.rs | 106 +- .../platform_specific/wayland/sctk_event.rs | 1009 +++++--------- .../wayland/subsurface_widget.rs | 143 +- .../platform_specific/wayland/winit_window.rs | 88 +- winit/src/proxy.rs | 18 +- winit/src/window.rs | 90 +- winit/src/window/state.rs | 30 +- 301 files changed, 7204 insertions(+), 13130 deletions(-) delete mode 100644 rustfmt.toml diff --git a/accessibility/src/a11y_tree.rs b/accessibility/src/a11y_tree.rs index 031c105364..915c55ce75 100644 --- a/accessibility/src/a11y_tree.rs +++ b/accessibility/src/a11y_tree.rs @@ -25,9 +25,7 @@ impl A11yTree { /// Helper for creating an A11y tree with a single root node and some children pub fn node_with_child_tree(mut root: A11yNode, child_tree: Self) -> Self { - root.add_children( - child_tree.root.iter().map(|n| n.id()).cloned().collect(), - ); + root.add_children(child_tree.root.iter().map(|n| n.id()).cloned().collect()); Self { root: vec![root], children: child_tree diff --git a/accessibility/src/id.rs b/accessibility/src/id.rs index 1d80bbd84a..ed97983315 100644 --- a/accessibility/src/id.rs +++ b/accessibility/src/id.rs @@ -36,9 +36,7 @@ impl From for A11yId { impl IdEq for A11yId { fn eq(&self, other: &Self) -> bool { match (self, other) { - (A11yId::Widget(self_), A11yId::Widget(other)) => { - IdEq::eq(self_, other) - } + (A11yId::Widget(self_), A11yId::Widget(other)) => IdEq::eq(self_, other), _ => self == other, } } @@ -150,8 +148,7 @@ impl std::fmt::Display for Id { // XXX WIndow IDs are made unique by adding u32::MAX to them /// get window node id that won't conflict with other node ids for the duration of the program pub fn window_node_id() -> u64 { - u32::MAX as u64 - + NEXT_WINDOW_ID.fetch_add(1, atomic::Ordering::Relaxed) as u64 + u32::MAX as u64 + NEXT_WINDOW_ID.fetch_add(1, atomic::Ordering::Relaxed) as u64 } // TODO refactor to make panic impossible? @@ -189,17 +186,14 @@ impl IdEq for Internal { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Unique(l0), Self::Unique(r0)) => l0 == r0, - (Self::Custom(l0, l1), Self::Custom(r0, r1)) => { - l0 == r0 || l1 == r1 - } + (Self::Custom(l0, l1), Self::Custom(r0, r1)) => l0 == r0 || l1 == r1, // allow custom ids to be equal to unique ids - (Self::Unique(l0), Self::Custom(r0, _)) - | (Self::Custom(l0, _), Self::Unique(r0)) => l0 == r0, + (Self::Unique(l0), Self::Custom(r0, _)) | (Self::Custom(l0, _), Self::Unique(r0)) => { + l0 == r0 + } (Self::Set(l0), Self::Set(r0)) => l0 == r0, // allow set ids to just be equal to any of their members - (Self::Set(l0), r) | (r, Self::Set(l0)) => { - l0.iter().any(|l| l == r) - } + (Self::Set(l0), r) | (r, Self::Set(l0)) => l0.iter().any(|l| l == r), } } } diff --git a/accessibility/src/node.rs b/accessibility/src/node.rs index ceb2fb3fcf..e762af5134 100644 --- a/accessibility/src/node.rs +++ b/accessibility/src/node.rs @@ -27,8 +27,7 @@ impl A11yNode { } pub fn add_children(&mut self, children: Vec) { - let mut children = - children.into_iter().map(|id| id.into()).collect::>(); + let mut children = children.into_iter().map(|id| id.into()).collect::>(); children.extend_from_slice(self.node.children()); self.node.set_children(children); } diff --git a/beacon/src/client.rs b/beacon/src/client.rs index 6ad5fd7827..ba658ef8e2 100644 --- a/beacon/src/client.rs +++ b/beacon/src/client.rs @@ -119,8 +119,7 @@ async fn run( is_connected: Arc, mut receiver: mpsc::Receiver, ) { - let version = semver::Version::parse(env!("CARGO_PKG_VERSION")) - .expect("Parse package version"); + let version = semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("Parse package version"); let command_sender = { // Discard by default @@ -158,8 +157,7 @@ async fn run( match receive(&mut reader, &mut buffer).await { Ok(command) => { match command { - Command::RewindTo { .. } - | Command::GoLive + Command::RewindTo { .. } | Command::GoLive if !metadata.can_time_travel => { continue; @@ -191,17 +189,11 @@ async fn run( match send(&mut writer, message).await { Ok(()) => {} Err(error) => { - if error.kind() != io::ErrorKind::BrokenPipe - { - log::warn!( - "Error sending message to server: {error}" - ); + if error.kind() != io::ErrorKind::BrokenPipe { + log::warn!("Error sending message to server: {error}"); } - is_connected.store( - false, - atomic::Ordering::Relaxed, - ); + is_connected.store(false, atomic::Ordering::Relaxed); break; } } @@ -229,8 +221,7 @@ async fn run( pub fn server_address_from_env() -> String { const DEFAULT_ADDRESS: &str = "127.0.0.1:9167"; - std::env::var("ICED_BEACON_SERVER_ADDRESS") - .unwrap_or_else(|_| String::from(DEFAULT_ADDRESS)) + std::env::var("ICED_BEACON_SERVER_ADDRESS").unwrap_or_else(|_| String::from(DEFAULT_ADDRESS)) } async fn _connect() -> Result { @@ -243,10 +234,7 @@ async fn _connect() -> Result { Ok(stream) } -async fn send( - stream: &mut net::tcp::OwnedWriteHalf, - message: Message, -) -> Result<(), io::Error> { +async fn send(stream: &mut net::tcp::OwnedWriteHalf, message: Message) -> Result<(), io::Error> { let bytes = bincode::serialize(&message).expect("Encode input message"); let size = bytes.len() as u64; diff --git a/beacon/src/lib.rs b/beacon/src/lib.rs index c2d888570b..fc877d220c 100644 --- a/beacon/src/lib.rs +++ b/beacon/src/lib.rs @@ -27,10 +27,7 @@ pub struct Connection { } impl Connection { - pub fn rewind_to<'a>( - &self, - message: usize, - ) -> impl Future + 'a { + pub fn rewind_to<'a>(&self, message: usize) -> impl Future + 'a { let commands = self.commands.clone(); async move { @@ -99,9 +96,7 @@ pub fn run() -> impl Stream { let mut buffer = Vec::new(); let server = loop { - match net::TcpListener::bind(client::server_address_from_env()) - .await - { + match net::TcpListener::bind(client::server_address_from_env()).await { Ok(server) => break server, Err(error) => { if error.kind() == io::ErrorKind::AddrInUse { @@ -152,10 +147,9 @@ pub fn run() -> impl Stream { } } - let _ = - send(&mut writer, command).await.inspect_err(|error| { - log::error!("Error when sending command: {error}") - }); + let _ = send(&mut writer, command) + .await + .inspect_err(|error| log::error!("Error when sending command: {error}")); } })); @@ -183,129 +177,88 @@ pub fn run() -> impl Stream { }) .await; } - client::Message::EventLogged { at, event } => { - match event { - client::Event::ThemeChanged(palette) => { - let _ = output - .send(Event::ThemeChanged { - at, - palette, - }) - .await; - } - client::Event::SubscriptionsTracked( - amount_alive, - ) => { - last_subscriptions = amount_alive; - } - client::Event::MessageLogged { - number, - message, - } => { - last_update_number = number; - last_message = message; - } - client::Event::CommandsSpawned( - commands, - ) => { - last_tasks = commands; - } - client::Event::LayersRendered(layers) => { - last_present_layers = layers; - } - client::Event::SpanStarted( - span::Stage::Update, - ) => { - last_message.clear(); - last_tasks = 0; - } - client::Event::SpanStarted(_) => {} - client::Event::SpanFinished( - stage, - duration, - ) => { - let span = match stage { - span::Stage::Boot => Span::Boot, - span::Stage::Update => { - Span::Update { - number: last_update_number, - message: last_message - .clone(), - tasks: last_tasks, - subscriptions: - last_subscriptions, + client::Message::EventLogged { at, event } => match event { + client::Event::ThemeChanged(palette) => { + let _ = output.send(Event::ThemeChanged { at, palette }).await; + } + client::Event::SubscriptionsTracked(amount_alive) => { + last_subscriptions = amount_alive; + } + client::Event::MessageLogged { number, message } => { + last_update_number = number; + last_message = message; + } + client::Event::CommandsSpawned(commands) => { + last_tasks = commands; + } + client::Event::LayersRendered(layers) => { + last_present_layers = layers; + } + client::Event::SpanStarted(span::Stage::Update) => { + last_message.clear(); + last_tasks = 0; + } + client::Event::SpanStarted(_) => {} + client::Event::SpanFinished(stage, duration) => { + let span = match stage { + span::Stage::Boot => Span::Boot, + span::Stage::Update => Span::Update { + number: last_update_number, + message: last_message.clone(), + tasks: last_tasks, + subscriptions: last_subscriptions, + }, + span::Stage::View(window) => Span::View { window }, + span::Stage::Layout(window) => Span::Layout { window }, + span::Stage::Interact(window) => Span::Interact { window }, + span::Stage::Draw(window) => Span::Draw { window }, + span::Stage::Prepare(primitive) + | span::Stage::Render(primitive) => { + let stage = if matches!(stage, span::Stage::Prepare(_),) + { + &mut last_prepare + } else { + &mut last_render + }; + + let primitive = match primitive { + present::Primitive::Quad => &mut stage.quads, + present::Primitive::Triangle => { + &mut stage.triangles } - } - span::Stage::View(window) => { - Span::View { window } - } - span::Stage::Layout(window) => { - Span::Layout { window } - } - span::Stage::Interact(window) => { - Span::Interact { window } - } - span::Stage::Draw(window) => { - Span::Draw { window } - } - span::Stage::Prepare(primitive) - | span::Stage::Render(primitive) => { - let stage = if matches!( - stage, - span::Stage::Prepare(_), - ) { - &mut last_prepare - } else { - &mut last_render - }; - - let primitive = match primitive { - present::Primitive::Quad => &mut stage.quads, - present::Primitive::Triangle => &mut stage.triangles, - present::Primitive::Shader => &mut stage.shaders, - present::Primitive::Text => &mut stage.text, - present::Primitive::Image => &mut stage.images, - }; - - *primitive += duration; - - continue; - } - span::Stage::Present(window) => { - let span = Span::Present { - window, - prepare: last_prepare, - render: last_render, - layers: last_present_layers, - }; - - last_prepare = - present::Stage::default(); - last_render = - present::Stage::default(); - last_present_layers = 0; - - span - } - span::Stage::Custom(name) => { - Span::Custom { name } - } - }; - - let _ = output - .send(Event::SpanFinished { - at, - duration, - span, - }) - .await; - } + present::Primitive::Shader => &mut stage.shaders, + present::Primitive::Text => &mut stage.text, + present::Primitive::Image => &mut stage.images, + }; + + *primitive += duration; + + continue; + } + span::Stage::Present(window) => { + let span = Span::Present { + window, + prepare: last_prepare, + render: last_render, + layers: last_present_layers, + }; + + last_prepare = present::Stage::default(); + last_render = present::Stage::default(); + last_present_layers = 0; + + span + } + span::Stage::Custom(name) => Span::Custom { name }, + }; + + let _ = output + .send(Event::SpanFinished { at, duration, span }) + .await; } - } + }, client::Message::Quit { at } => { - let _ = output - .send(Event::QuitRequested { at }) - .await; + let _ = output.send(Event::QuitRequested { at }).await; } }; } diff --git a/beacon/src/span.rs b/beacon/src/span.rs index 690982cc4b..7465424200 100644 --- a/beacon/src/span.rs +++ b/beacon/src/span.rs @@ -34,9 +34,7 @@ pub enum Span { }, } -#[derive( - Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, -)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Stage { Boot, Update, @@ -81,18 +79,7 @@ pub mod present { pub images: Duration, } - #[derive( - Debug, - Clone, - Copy, - PartialEq, - Eq, - PartialOrd, - Ord, - Hash, - Serialize, - Deserialize, - )] + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Primitive { Quad, Triangle, diff --git a/benches/wgpu.rs b/benches/wgpu.rs index d931c25aeb..70ace55ae8 100644 --- a/benches/wgpu.rs +++ b/benches/wgpu.rs @@ -4,9 +4,7 @@ use criterion::{Bencher, Criterion, criterion_group, criterion_main}; use iced::alignment; use iced::mouse; use iced::widget::{canvas, scrollable, stack, text}; -use iced::{ - Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Theme, -}; +use iced::{Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Theme}; use iced_wgpu::Renderer; use iced_wgpu::wgpu; @@ -23,25 +21,22 @@ pub fn wgpu_benchmark(c: &mut Criterion) { ..Default::default() }); - let adapter = executor::block_on(instance.request_adapter( - &wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::HighPerformance, - compatible_surface: None, - force_fallback_adapter: false, - }, - )) + let adapter = executor::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: None, + force_fallback_adapter: false, + })) .expect("request adapter"); - let (device, queue) = - executor::block_on(adapter.request_device(&wgpu::DeviceDescriptor { - label: None, - required_features: wgpu::Features::empty(), - required_limits: wgpu::Limits::default(), - memory_hints: wgpu::MemoryHints::MemoryUsage, - trace: wgpu::Trace::Off, - experimental_features: wgpu::ExperimentalFeatures::disabled(), - })) - .expect("request device"); + let (device, queue) = executor::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: None, + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::default(), + memory_hints: wgpu::MemoryHints::MemoryUsage, + trace: wgpu::Trace::Off, + experimental_features: wgpu::ExperimentalFeatures::disabled(), + })) + .expect("request device"); c.bench_function("wgpu — canvas (light)", |b| { benchmark(b, &adapter, &device, &queue, |_| scene(10)); @@ -100,8 +95,7 @@ fn benchmark<'a>( let mut renderer = Renderer::new(engine, Font::DEFAULT, Pixels::from(16)); - let viewport = - graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0); + let viewport = graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -118,8 +112,7 @@ fn benchmark<'a>( view_formats: &[], }); - let texture_view = - texture.create_view(&wgpu::TextureViewDescriptor::default()); + let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let mut i = 0; let mut cache = Some(runtime::user_interface::Cache::default()); @@ -143,12 +136,7 @@ fn benchmark<'a>( cache = Some(user_interface.into_cache()); - let submission = renderer.present( - Some(Color::BLACK), - format, - &texture_view, - &viewport, - ); + let submission = renderer.present(Some(Color::BLACK), format, &texture_view, &viewport); let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(submission), @@ -208,19 +196,14 @@ fn scene<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> { .into() } -fn layered_text<'a, Message: 'a>( - n: usize, -) -> Element<'a, Message, Theme, Renderer> { +fn layered_text<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> { stack((0..n).map(|i| text!("I am paragraph {i}!").into())) .width(Length::Fill) .height(Length::Fill) .into() } -fn dynamic_text<'a, Message: 'a>( - n: usize, - i: usize, -) -> Element<'a, Message, Theme, Renderer> { +fn dynamic_text<'a, Message: 'a>(n: usize, i: usize) -> Element<'a, Message, Theme, Renderer> { const LOREM_IPSUM: &str = include_str!("ipsum.txt"); scrollable( @@ -236,10 +219,7 @@ fn dynamic_text<'a, Message: 'a>( .into() } -fn advanced_shaping<'a, Message: 'a>( - n: usize, - i: usize, -) -> Element<'a, Message, Theme, Renderer> { +fn advanced_shaping<'a, Message: 'a>(n: usize, i: usize) -> Element<'a, Message, Theme, Renderer> { const LOREM_IPSUM: &str = include_str!("ipsum.txt"); scrollable( diff --git a/core/src/animation.rs b/core/src/animation.rs index fa82c1dc7c..381ee00796 100644 --- a/core/src/animation.rs +++ b/core/src/animation.rs @@ -141,10 +141,6 @@ impl Animation { /// Returns the remaining [`Duration`] of the [`Animation`]. pub fn remaining(&self, at: Instant) -> Duration { - Duration::from_secs_f32(self.interpolate( - self.duration.as_secs_f32(), - 0.0, - at, - )) + Duration::from_secs_f32(self.interpolate(self.duration.as_secs_f32(), 0.0, at)) } } diff --git a/core/src/background.rs b/core/src/background.rs index 0362222481..2ee65b2811 100644 --- a/core/src/background.rs +++ b/core/src/background.rs @@ -17,9 +17,7 @@ impl Background { pub fn scale_alpha(self, factor: f32) -> Self { match self { Self::Color(color) => Self::Color(color.scale_alpha(factor)), - Self::Gradient(gradient) => { - Self::Gradient(gradient.scale_alpha(factor)) - } + Self::Gradient(gradient) => Self::Gradient(gradient.scale_alpha(factor)), } } } diff --git a/core/src/clipboard.rs b/core/src/clipboard.rs index bef85f27f5..5e9532e492 100644 --- a/core/src/clipboard.rs +++ b/core/src/clipboard.rs @@ -17,11 +17,7 @@ pub struct IconSurface { pub type DynIconSurface = IconSurface>; impl IconSurface> { - pub fn new( - element: Element<'static, (), T, R>, - state: State, - offset: Vector, - ) -> Self { + pub fn new(element: Element<'static, (), T, R>, state: State, offset: Vector) -> Self { Self { element, state, @@ -42,9 +38,7 @@ impl DynIconSurface { /// Downcast `element` to concrete type `Element<(), T, R>` /// /// Panics if type doesn't match - pub fn downcast( - self, - ) -> IconSurface> { + pub fn downcast(self) -> IconSurface> { IconSurface { element: *self .element @@ -67,11 +61,7 @@ pub trait Clipboard { /// Consider using [`read_data`] instead /// Reads the current content of the [`Clipboard`] as text. - fn read_data( - &self, - _kind: Kind, - _mimes: Vec, - ) -> Option<(Vec, String)> { + fn read_data(&self, _kind: Kind, _mimes: Vec) -> Option<(Vec, String)> { None } @@ -79,9 +69,7 @@ pub trait Clipboard { fn write_data( &mut self, _kind: Kind, - _contents: ClipboardStoreData< - Box, - >, + _contents: ClipboardStoreData>, ) { } @@ -165,18 +153,14 @@ impl Clipboard for Null { } /// Reads the current content of the [`Clipboard`]. -pub fn read_data( - clipboard: &mut dyn Clipboard, -) -> Option { +pub fn read_data(clipboard: &mut dyn Clipboard) -> Option { clipboard .read_data(Kind::Standard, T::allowed().into()) .and_then(|data| T::try_from(data).ok()) } /// Reads the current content of the primary [`Clipboard`]. -pub fn read_primary_data( - clipboard: &mut dyn Clipboard, -) -> Option { +pub fn read_primary_data(clipboard: &mut dyn Clipboard) -> Option { clipboard .read_data(Kind::Primary, T::allowed().into()) .and_then(|data| T::try_from(data).ok()) diff --git a/core/src/color.rs b/core/src/color.rs index 5b0de0cf63..a8e4210294 100644 --- a/core/src/color.rs +++ b/core/src/color.rs @@ -206,9 +206,7 @@ pub enum ParseError { #[error(transparent)] ParseIntError(#[from] std::num::ParseIntError), /// The string is of invalid length. - #[error( - "expected hex string of length 3, 4, 6 or 8 excluding optional prefix '#', found {0}" - )] + #[error("expected hex string of length 3, 4, 6 or 8 excluding optional prefix '#', found {0}")] InvalidLength(usize), } @@ -218,14 +216,12 @@ impl std::str::FromStr for Color { fn from_str(s: &str) -> Result { let hex = s.strip_prefix('#').unwrap_or(s); - let parse_channel = - |from: usize, to: usize| -> Result { - let num = - usize::from_str_radix(&hex[from..=to], 16)? as f32 / 255.0; + let parse_channel = |from: usize, to: usize| -> Result { + let num = usize::from_str_radix(&hex[from..=to], 16)? as f32 / 255.0; - // If we only got half a byte (one letter), expand it into a full byte (two letters) - Ok(if from == to { num + num * 16.0 } else { num }) - }; + // If we only got half a byte (one letter), expand it into a full byte (two letters) + Ok(if from == to { num + num * 16.0 } else { num }) + }; let val = match hex.len() { 3 => Color::from_rgb( diff --git a/core/src/element.rs b/core/src/element.rs index f97ed6bc17..7befabfbf2 100644 --- a/core/src/element.rs +++ b/core/src/element.rs @@ -6,10 +6,7 @@ use crate::overlay; use crate::renderer; use crate::widget; use crate::widget::tree::{self, Tree}; -use crate::{ - Border, Clipboard, Color, Layout, Length, Rectangle, Shell, Size, Vector, - Widget, -}; +use crate::{Border, Clipboard, Color, Layout, Length, Rectangle, Shell, Size, Vector, Widget}; use std::borrow::{Borrow, BorrowMut}; @@ -43,9 +40,7 @@ impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> { } /// Returns a mutable reference to the [`Widget`] of the [`Element`], - pub fn as_widget_mut( - &mut self, - ) -> &mut dyn Widget { + pub fn as_widget_mut(&mut self) -> &mut dyn Widget { self.widget.as_mut() } @@ -188,10 +183,7 @@ impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> { /// } /// } /// ``` - pub fn map( - self, - f: impl Fn(Message) -> B + 'a, - ) -> Element<'a, B, Theme, Renderer> + pub fn map(self, f: impl Fn(Message) -> B + 'a) -> Element<'a, B, Theme, Renderer> where Message: 'a, Theme: 'a, @@ -207,10 +199,7 @@ impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> { /// This can be very useful for debugging your layout! /// /// [`Renderer`]: crate::Renderer - pub fn explain>( - self, - color: C, - ) -> Element<'a, Message, Theme, Renderer> + pub fn explain>(self, color: C) -> Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, @@ -222,8 +211,7 @@ impl<'a, Message, Theme, Renderer> Element<'a, Message, Theme, Renderer> { } } -impl<'a, Message, Theme, Renderer> - Borrow + 'a> +impl<'a, Message, Theme, Renderer> Borrow + 'a> for Element<'a, Message, Theme, Renderer> { fn borrow(&self) -> &(dyn Widget + 'a) { @@ -231,8 +219,7 @@ impl<'a, Message, Theme, Renderer> } } -impl<'a, Message, Theme, Renderer> - Borrow + 'a> +impl<'a, Message, Theme, Renderer> Borrow + 'a> for &Element<'a, Message, Theme, Renderer> { fn borrow(&self) -> &(dyn Widget + 'a) { @@ -240,8 +227,7 @@ impl<'a, Message, Theme, Renderer> } } -impl<'a, Message, Theme, Renderer> - Borrow + 'a> +impl<'a, Message, Theme, Renderer> Borrow + 'a> for &mut Element<'a, Message, Theme, Renderer> { fn borrow(&self) -> &(dyn Widget + 'a) { @@ -249,24 +235,18 @@ impl<'a, Message, Theme, Renderer> } } -impl<'a, Message, Theme, Renderer> - BorrowMut + 'a> +impl<'a, Message, Theme, Renderer> BorrowMut + 'a> for &mut Element<'a, Message, Theme, Renderer> { - fn borrow_mut( - &mut self, - ) -> &mut (dyn Widget + 'a) { + fn borrow_mut(&mut self) -> &mut (dyn Widget + 'a) { self.widget.borrow_mut() } } -impl<'a, Message, Theme, Renderer> - BorrowMut + 'a> +impl<'a, Message, Theme, Renderer> BorrowMut + 'a> for Element<'a, Message, Theme, Renderer> { - fn borrow_mut( - &mut self, - ) -> &mut (dyn Widget + 'a) { + fn borrow_mut(&mut self) -> &mut (dyn Widget + 'a) { self.widget.borrow_mut() } } @@ -291,8 +271,7 @@ impl<'a, A, B, Theme, Renderer> Map<'a, A, B, Theme, Renderer> { } } -impl<'a, A, B, Theme, Renderer> Widget - for Map<'a, A, B, Theme, Renderer> +impl<'a, A, B, Theme, Renderer> Widget for Map<'a, A, B, Theme, Renderer> where Renderer: crate::Renderer + 'a, A: 'a, @@ -449,10 +428,7 @@ impl<'a, Message, Theme, Renderer> Explain<'a, Message, Theme, Renderer> where Renderer: crate::Renderer, { - fn new( - element: Element<'a, Message, Theme, Renderer>, - color: Color, - ) -> Self { + fn new(element: Element<'a, Message, Theme, Renderer>, color: Color) -> Self { Explain { element, color } } } @@ -586,13 +562,9 @@ where viewport: &Rectangle, translation: Vector, ) -> Option> { - self.element.widget.overlay( - tree, - layout, - renderer, - viewport, - translation, - ) + self.element + .widget + .overlay(tree, layout, renderer, viewport, translation) } fn id(&self) -> Option { @@ -610,17 +582,13 @@ where renderer: &Renderer, dnd_rectangles: &mut crate::clipboard::DndDestinationRectangles, ) { - self.element.widget.drag_destinations( - state, - layout, - renderer, - dnd_rectangles, - ); + self.element + .widget + .drag_destinations(state, layout, renderer, dnd_rectangles); } // TODO maybe a11y_nodes } -impl<'a, T, Message, Theme, Renderer> From> - for Element<'a, Message, Theme, Renderer> +impl<'a, T, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where T: Into, Renderer: crate::Renderer, diff --git a/core/src/event/wayland/output.rs b/core/src/event/wayland/output.rs index 4c7b6976dc..6f3a3b1834 100644 --- a/core/src/event/wayland/output.rs +++ b/core/src/event/wayland/output.rs @@ -26,9 +26,7 @@ impl PartialEq for OutputEvent { (Self::InfoUpdate(l0), Self::InfoUpdate(r0)) => { l0.id == r0.id && l0.make == r0.make && l0.model == r0.model } - _ => { - core::mem::discriminant(self) == core::mem::discriminant(other) - } + _ => core::mem::discriminant(self) == core::mem::discriminant(other), } } } diff --git a/core/src/event/wayland/overlap_notify.rs b/core/src/event/wayland/overlap_notify.rs index 60f790d8f0..904aabbe35 100644 --- a/core/src/event/wayland/overlap_notify.rs +++ b/core/src/event/wayland/overlap_notify.rs @@ -1,4 +1,7 @@ -use cctk::{sctk::shell::wlr_layer::Layer, wayland_protocols::ext::foreign_toplevel_list::v1::client::ext_foreign_toplevel_handle_v1::ExtForeignToplevelHandleV1}; +use cctk::{ + sctk::shell::wlr_layer::Layer, + wayland_protocols::ext::foreign_toplevel_list::v1::client::ext_foreign_toplevel_handle_v1::ExtForeignToplevelHandleV1, +}; #[derive(Debug, Clone, PartialEq)] pub enum OverlapNotifyEvent { diff --git a/core/src/gradient.rs b/core/src/gradient.rs index 722c3c5c20..503394c9e1 100644 --- a/core/src/gradient.rs +++ b/core/src/gradient.rs @@ -15,9 +15,7 @@ impl Gradient { /// Scales the alpha channel of the [`Gradient`] by the given factor. pub fn scale_alpha(self, factor: f32) -> Self { match self { - Gradient::Linear(linear) => { - Gradient::Linear(linear.scale_alpha(factor)) - } + Gradient::Linear(linear) => Gradient::Linear(linear.scale_alpha(factor)), } } } @@ -67,11 +65,10 @@ impl Linear { /// Any stop added after the 8th will be silently ignored. pub fn add_stop(mut self, offset: f32, color: Color) -> Self { if offset.is_finite() && (0.0..=1.0).contains(&offset) { - let (Ok(index) | Err(index)) = - self.stops.binary_search_by(|stop| match stop { - None => Ordering::Greater, - Some(stop) => stop.offset.total_cmp(&offset), - }); + let (Ok(index) | Err(index)) = self.stops.binary_search_by(|stop| match stop { + None => Ordering::Greater, + Some(stop) => stop.offset.total_cmp(&offset), + }); if index < 8 { self.stops[index] = Some(ColorStop { offset, color }); @@ -86,10 +83,7 @@ impl Linear { /// Adds multiple [`ColorStop`]s to the gradient. /// /// Any stop added after the 8th will be silently ignored. - pub fn add_stops( - mut self, - stops: impl IntoIterator, - ) -> Self { + pub fn add_stops(mut self, stops: impl IntoIterator) -> Self { for stop in stops { self = self.add_stop(stop.offset, stop.color); } diff --git a/core/src/id.rs b/core/src/id.rs index 2b6927bb8a..4e47e5e35f 100644 --- a/core/src/id.rs +++ b/core/src/id.rs @@ -63,9 +63,7 @@ impl From for NonZeroU128 { fn from(id: Id) -> NonZeroU128 { match &id.0 { Internal::Unique(id) => NonZeroU128::try_from(*id as u128).unwrap(), - Internal::Custom(id, _) => { - NonZeroU128::try_from(*id as u128).unwrap() - } + Internal::Custom(id, _) => NonZeroU128::try_from(*id as u128).unwrap(), // this is a set id, which is not a valid id and will not ever be converted to a NonZeroU128 // so we panic Internal::Set(_) => { @@ -89,8 +87,7 @@ impl std::fmt::Display for Id { /// get window node id that won't conflict with other node ids for the duration of the program pub fn window_node_id() -> NonZeroU128 { std::num::NonZeroU128::try_from( - u64::MAX as u128 - + NEXT_WINDOW_ID.fetch_add(1, atomic::Ordering::Relaxed) as u128, + u64::MAX as u128 + NEXT_WINDOW_ID.fetch_add(1, atomic::Ordering::Relaxed) as u128, ) .unwrap() } @@ -131,17 +128,14 @@ impl IdEq for Internal { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Unique(l0), Self::Unique(r0)) => l0 == r0, - (Self::Custom(l0, l1), Self::Custom(r0, r1)) => { - l0 == r0 || l1 == r1 - } + (Self::Custom(l0, l1), Self::Custom(r0, r1)) => l0 == r0 || l1 == r1, // allow custom ids to be equal to unique ids - (Self::Unique(l0), Self::Custom(r0, _)) - | (Self::Custom(l0, _), Self::Unique(r0)) => l0 == r0, + (Self::Unique(l0), Self::Custom(r0, _)) | (Self::Custom(l0, _), Self::Unique(r0)) => { + l0 == r0 + } (Self::Set(l0), Self::Set(r0)) => l0 == r0, // allow set ids to just be equal to any of their members - (Self::Set(l0), r) | (r, Self::Set(l0)) => { - l0.iter().any(|l| l == r) - } + (Self::Set(l0), r) | (r, Self::Set(l0)) => l0.iter().any(|l| l == r), } } } diff --git a/core/src/image.rs b/core/src/image.rs index fb0cdc5c4c..b4b28379a0 100644 --- a/core/src/image.rs +++ b/core/src/image.rs @@ -145,11 +145,7 @@ impl Handle { /// `width * height * 4`. /// /// This is useful if you have already decoded your image. - pub fn from_rgba( - width: u32, - height: u32, - pixels: impl Into, - ) -> Handle { + pub fn from_rgba(width: u32, height: u32, pixels: impl Into) -> Handle { Self::Rgba { id: Id::unique(), width, @@ -161,9 +157,7 @@ impl Handle { /// Returns the unique identifier of the [`Handle`]. pub fn id(&self) -> Id { match self { - Handle::Path(id, _) - | Handle::Bytes(id, _) - | Handle::Rgba { id, .. } => *id, + Handle::Path(id, _) | Handle::Bytes(id, _) | Handle::Rgba { id, .. } => *id, } } } @@ -329,12 +323,7 @@ pub trait Renderer: crate::Renderer { /// /// If you need to draw an image right away, consider using [`Renderer::load_image`] /// and hold on to an [`Allocation`] first. - fn draw_image( - &mut self, - image: Image, - bounds: Rectangle, - clip_bounds: Rectangle, - ); + fn draw_image(&mut self, image: Image, bounds: Rectangle, clip_bounds: Rectangle); } /// An image loading error. diff --git a/core/src/layout.rs b/core/src/layout.rs index 868e018457..f412fe7038 100644 --- a/core/src/layout.rs +++ b/core/src/layout.rs @@ -70,14 +70,9 @@ impl<'a> Layout<'a> { } /// Returns an iterator over the children of this [`Layout`]. - pub fn children( - self, - ) -> impl DoubleEndedIterator> + ExactSizeIterator { + pub fn children(self) -> impl DoubleEndedIterator> + ExactSizeIterator { self.node.children().iter().map(move |node| { - Layout::with_offset( - Vector::new(self.position.x, self.position.y), - node, - ) + Layout::with_offset(Vector::new(self.position.x, self.position.y), node) }) } @@ -130,11 +125,7 @@ pub fn next_to_each_other( /// Computes the resulting [`Node`] that fits the [`Limits`] given /// some width and height requirements and no intrinsic size. -pub fn atomic( - limits: &Limits, - width: impl Into, - height: impl Into, -) -> Node { +pub fn atomic(limits: &Limits, width: impl Into, height: impl Into) -> Node { let width = width.into(); let height = height.into(); @@ -174,10 +165,7 @@ pub fn contained( let limits = limits.width(width).height(height); let content = f(&limits); - Node::with_children( - limits.resolve(width, height, content.size()), - vec![content], - ) + Node::with_children(limits.resolve(width, height, content.size()), vec![content]) } /// Computes the [`Node`] that fits the [`Limits`] given some width, height, and diff --git a/core/src/layout/flex.rs b/core/src/layout/flex.rs index 33dfe6e8cc..26a753355b 100644 --- a/core/src/layout/flex.rs +++ b/core/src/layout/flex.rs @@ -100,17 +100,14 @@ where // We lay out non-fluid elements in the main axis. // If we need to compress the cross axis, then we skip any of these elements // that are also fluid in the cross axis. - for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() - { + for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (fill_main_factor, fill_cross_factor) = { let size = child.as_widget().size(); axis.pack(size.width.fill_factor(), size.height.fill_factor()) }; - if (main_compress || fill_main_factor == 0) - && (!cross_compress || fill_cross_factor == 0) - { + if (main_compress || fill_main_factor == 0) && (!cross_compress || fill_cross_factor == 0) { let (max_width, max_height) = axis.pack( available, if fill_cross_factor == 0 { @@ -120,14 +117,10 @@ where }, ); - let child_limits = Limits::with_compression( - Size::ZERO, - Size::new(max_width, max_height), - compression, - ); + let child_limits = + Limits::with_compression(Size::ZERO, Size::new(max_width, max_height), compression); - let layout = - child.as_widget_mut().layout(tree, renderer, &child_limits); + let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); available -= axis.main(size); @@ -151,18 +144,14 @@ where // We can defer the layout of any elements that have a fixed size in the main axis, // allowing them to use the cross calculations of the next pass. if cross_compress && some_fill_cross { - for (i, (child, tree)) in - items.iter_mut().zip(trees.iter_mut()).enumerate() - { + for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (main_size, cross_size) = { let size = child.as_widget().size(); axis.pack(size.width, size.height) }; - if (main_compress || main_size.fill_factor() == 0) - && cross_size.fill_factor() != 0 - { + if (main_compress || main_size.fill_factor() == 0) && cross_size.fill_factor() != 0 { if let Length::Fixed(main) = main_size { available -= main; continue; @@ -176,8 +165,7 @@ where compression, ); - let layout = - child.as_widget_mut().layout(tree, renderer, &child_limits); + let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); available -= axis.main(size); @@ -194,9 +182,7 @@ where // We lay out the elements that are fluid in the main axis. // We use the remaining space to evenly allocate space based on fill factors. if !main_compress { - for (i, (child, tree)) in - items.iter_mut().zip(trees.iter_mut()).enumerate() - { + for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() { let (fill_main_factor, fill_cross_factor) = { let size = child.as_widget().size(); @@ -204,8 +190,7 @@ where }; if fill_main_factor != 0 { - let max_main = - remaining * fill_main_factor as f32 / fill_main_sum as f32; + let max_main = remaining * fill_main_factor as f32 / fill_main_sum as f32; let max_main = if max_main.is_nan() { f32::INFINITY @@ -235,8 +220,7 @@ where compression, ); - let layout = - child.as_widget_mut().layout(tree, renderer, &child_limits); + let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); cross = cross.max(axis.cross(layout.size())); nodes[i] = layout; @@ -263,11 +247,9 @@ where let (max_width, max_height) = axis.pack(main, cross); - let child_limits = - Limits::new(Size::ZERO, Size::new(max_width, max_height)); + let child_limits = Limits::new(Size::ZERO, Size::new(max_width, max_height)); - let layout = - child.as_widget_mut().layout(tree, renderer, &child_limits); + let layout = child.as_widget_mut().layout(tree, renderer, &child_limits); let size = layout.size(); cross = cross.max(axis.cross(size)); @@ -293,18 +275,10 @@ where match axis { Axis::Horizontal => { - node.align_mut( - Alignment::Start, - align_items, - Size::new(0.0, cross), - ); + node.align_mut(Alignment::Start, align_items, Size::new(0.0, cross)); } Axis::Vertical => { - node.align_mut( - align_items, - Alignment::Start, - Size::new(cross, 0.0), - ); + node.align_mut(align_items, Alignment::Start, Size::new(cross, 0.0)); } } @@ -314,11 +288,7 @@ where } let (intrinsic_width, intrinsic_height) = axis.pack(main - pad.0, cross); - let size = limits.resolve( - width, - height, - Size::new(intrinsic_width, intrinsic_height), - ); + let size = limits.resolve(width, height, Size::new(intrinsic_width, intrinsic_height)); Node::with_children(size.expand(padding), nodes) } diff --git a/core/src/layout/limits.rs b/core/src/layout/limits.rs index 11c6729465..06e7c686a6 100644 --- a/core/src/layout/limits.rs +++ b/core/src/layout/limits.rs @@ -24,11 +24,7 @@ impl Limits { /// Creates new [`Limits`] with the given minimun and maximum [`Size`], and /// whether fluid lengths should be compressed to intrinsic dimensions. - pub const fn with_compression( - min: Size, - max: Size, - compress: Size, - ) -> Self { + pub const fn with_compression(min: Size, max: Size, compress: Size) -> Self { Limits { min, max, @@ -77,8 +73,7 @@ impl Limits { self.compression.height = true; } Length::Fixed(amount) => { - let new_height = - amount.min(self.max.height).max(self.min.height); + let new_height = amount.min(self.max.height).max(self.min.height); self.min.height = new_height; self.max.height = new_height; @@ -158,26 +153,14 @@ impl Limits { intrinsic_size: Size, ) -> Size { let width = match width.into() { - Length::Fill | Length::FillPortion(_) - if !self.compression.width => - { - self.max.width - } - Length::Fixed(amount) => { - amount.min(self.max.width).max(self.min.width) - } + Length::Fill | Length::FillPortion(_) if !self.compression.width => self.max.width, + Length::Fixed(amount) => amount.min(self.max.width).max(self.min.width), _ => intrinsic_size.width.min(self.max.width).max(self.min.width), }; let height = match height.into() { - Length::Fill | Length::FillPortion(_) - if !self.compression.height => - { - self.max.height - } - Length::Fixed(amount) => { - amount.min(self.max.height).max(self.min.height) - } + Length::Fill | Length::FillPortion(_) if !self.compression.height => self.max.height, + Length::Fixed(amount) => amount.min(self.max.height).max(self.min.height), _ => intrinsic_size .height .min(self.max.height) diff --git a/core/src/layout/node.rs b/core/src/layout/node.rs index 6fb5d39578..ee08df43af 100644 --- a/core/src/layout/node.rs +++ b/core/src/layout/node.rs @@ -50,23 +50,13 @@ impl Node { } /// Aligns the [`Node`] in the given space. - pub fn align( - mut self, - align_x: Alignment, - align_y: Alignment, - space: Size, - ) -> Self { + pub fn align(mut self, align_x: Alignment, align_y: Alignment, space: Size) -> Self { self.align_mut(align_x, align_y, space); self } /// Mutable reference version of [`Self::align`]. - pub fn align_mut( - &mut self, - align_x: Alignment, - align_y: Alignment, - space: Size, - ) { + pub fn align_mut(&mut self, align_x: Alignment, align_y: Alignment, space: Size) { match align_x { Alignment::Start => {} Alignment::Center => { diff --git a/core/src/mouse/click.rs b/core/src/mouse/click.rs index 51f5fc9d1b..ba9545e6c2 100644 --- a/core/src/mouse/click.rs +++ b/core/src/mouse/click.rs @@ -40,16 +40,10 @@ impl Kind { impl Click { /// Creates a new [`Click`] with the given position and previous last /// [`Click`]. - pub fn new( - position: Point, - button: Button, - previous: Option, - ) -> Click { + pub fn new(position: Point, button: Button, previous: Option) -> Click { let time = Instant::now(); let kind = if let Some(previous) = previous { - if previous.is_consecutive(position, time) - && button == previous.button - { + if previous.is_consecutive(position, time) && button == previous.button { previous.kind.next() } else { Kind::Single diff --git a/core/src/mouse/cursor.rs b/core/src/mouse/cursor.rs index 3e1d2bf449..2dcce52b74 100644 --- a/core/src/mouse/cursor.rs +++ b/core/src/mouse/cursor.rs @@ -81,9 +81,7 @@ impl std::ops::Add for Cursor { fn add(self, translation: Vector) -> Self::Output { match self { Cursor::Available(point) => Cursor::Available(point + translation), - Cursor::Levitating(point) => { - Cursor::Levitating(point + translation) - } + Cursor::Levitating(point) => Cursor::Levitating(point + translation), Cursor::Unavailable => Cursor::Unavailable, } } @@ -95,9 +93,7 @@ impl std::ops::Sub for Cursor { fn sub(self, translation: Vector) -> Self::Output { match self { Cursor::Available(point) => Cursor::Available(point - translation), - Cursor::Levitating(point) => { - Cursor::Levitating(point - translation) - } + Cursor::Levitating(point) => Cursor::Levitating(point - translation), Cursor::Unavailable => Cursor::Unavailable, } } @@ -108,12 +104,8 @@ impl std::ops::Mul for Cursor { fn mul(self, transformation: Transformation) -> Self { match self { - Self::Available(position) => { - Self::Available(position * transformation) - } - Self::Levitating(position) => { - Self::Levitating(position * transformation) - } + Self::Available(position) => Self::Available(position * transformation), + Self::Levitating(position) => Self::Levitating(position * transformation), Self::Unavailable => Self::Unavailable, } } diff --git a/core/src/overlay/element.rs b/core/src/overlay/element.rs index e67a48bcb7..5fce3bb983 100644 --- a/core/src/overlay/element.rs +++ b/core/src/overlay/element.rs @@ -16,9 +16,7 @@ where Renderer: crate::Renderer, { /// Creates a new [`Element`] containing the given [`Overlay`]. - pub fn new( - overlay: Box + 'a>, - ) -> Self { + pub fn new(overlay: Box + 'a>) -> Self { Self { overlay } } @@ -28,17 +26,12 @@ where } /// Returns a mutable reference to the [`Overlay`] of the [`Element`], - pub fn as_overlay_mut( - &mut self, - ) -> &mut dyn Overlay { + pub fn as_overlay_mut(&mut self) -> &mut dyn Overlay { self.overlay.as_mut() } /// Applies a transformation to the produced message of the [`Element`]. - pub fn map( - self, - f: &'a dyn Fn(Message) -> B, - ) -> Element<'a, B, Theme, Renderer> + pub fn map(self, f: &'a dyn Fn(Message) -> B) -> Element<'a, B, Theme, Renderer> where Message: 'a, Theme: 'a, @@ -65,8 +58,7 @@ impl<'a, A, B, Theme, Renderer> Map<'a, A, B, Theme, Renderer> { } } -impl Overlay - for Map<'_, A, B, Theme, Renderer> +impl Overlay for Map<'_, A, B, Theme, Renderer> where Renderer: crate::Renderer, { @@ -95,14 +87,8 @@ where let mut local_messages = Vec::new(); let mut local_shell = Shell::new(&mut local_messages); - self.content.update( - event, - layout, - cursor, - renderer, - clipboard, - &mut local_shell, - ); + self.content + .update(event, layout, cursor, renderer, clipboard, &mut local_shell); shell.merge(local_shell, self.mapper); } diff --git a/core/src/overlay/group.rs b/core/src/overlay/group.rs index ec0906e7e9..03d65acc66 100644 --- a/core/src/overlay/group.rs +++ b/core/src/overlay/group.rs @@ -44,8 +44,7 @@ where } } -impl<'a, Message, Theme, Renderer> Default - for Group<'a, Message, Theme, Renderer> +impl<'a, Message, Theme, Renderer> Default for Group<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, @@ -127,11 +126,12 @@ where operation: &mut dyn widget::Operation, ) { operation.traverse(&mut |operation| { - self.children.iter_mut().zip(layout.children()).for_each( - |(child, layout)| { + self.children + .iter_mut() + .zip(layout.children()) + .for_each(|(child, layout)| { child.as_overlay_mut().operate(layout, renderer, operation); - }, - ); + }); }); } @@ -144,9 +144,7 @@ where .children .iter_mut() .zip(layout.children()) - .filter_map(|(child, layout)| { - child.as_overlay_mut().overlay(layout, renderer) - }) + .filter_map(|(child, layout)| child.as_overlay_mut().overlay(layout, renderer)) .collect::>(); (!children.is_empty()).then(|| Group::with_children(children).overlay()) diff --git a/core/src/overlay/nested.rs b/core/src/overlay/nested.rs index 2b90a900aa..2f57d8d173 100644 --- a/core/src/overlay/nested.rs +++ b/core/src/overlay/nested.rs @@ -16,20 +16,14 @@ where Renderer: renderer::Renderer, { /// Creates a nested overlay from the provided [`overlay::Element`] - pub fn new( - element: overlay::Element<'a, Message, Theme, Renderer>, - ) -> Self { + pub fn new(element: overlay::Element<'a, Message, Theme, Renderer>) -> Self { Self { overlay: element } } /// Returns the layout [`Node`] of the [`Nested`] overlay. /// /// [`Node`]: layout::Node - pub fn layout( - &mut self, - renderer: &Renderer, - bounds: Size, - ) -> layout::Node { + pub fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { fn recurse( element: &mut overlay::Element<'_, Message, Theme, Renderer>, renderer: &Renderer, @@ -47,10 +41,7 @@ where .map(|nested| recurse(nested, renderer, bounds)); if let Some(nested_node) = nested_node { - layout::Node::with_children( - node.size(), - vec![node, nested_node], - ) + layout::Node::with_children(node.size(), vec![node, nested_node]) } else { layout::Node::with_children(node.size(), vec![node]) } @@ -115,14 +106,7 @@ where if let Some((mut nested, nested_layout)) = overlay.overlay(layout, renderer).zip(nested_layout) { - recurse( - &mut nested, - nested_layout, - renderer, - theme, - style, - cursor, - ); + recurse(&mut nested, nested_layout, renderer, theme, style, cursor); } } } @@ -280,9 +264,7 @@ where .and_then(|(mut overlay, layout)| { recurse(&mut overlay, layout, cursor, renderer) }) - .unwrap_or_else(|| { - overlay.mouse_interaction(layout, cursor, renderer) - }), + .unwrap_or_else(|| overlay.mouse_interaction(layout, cursor, renderer)), ) } diff --git a/core/src/rectangle.rs b/core/src/rectangle.rs index 0fa013d6f9..4a4e37f601 100644 --- a/core/src/rectangle.rs +++ b/core/src/rectangle.rs @@ -72,11 +72,9 @@ impl Rectangle { ) -> (Rectangle, Radians) { let width = (top_right.x - top_left.x).hypot(top_right.y - top_left.y); - let height = - (bottom_left.x - top_left.x).hypot(bottom_left.y - top_left.y); + let height = (bottom_left.x - top_left.x).hypot(bottom_left.y - top_left.y); - let rotation = - (top_right.y - top_left.y).atan2(top_right.x - top_left.x); + let rotation = (top_right.y - top_left.y).atan2(top_right.x - top_left.x); let rotation = if rotation < 0.0 { 2.0 * std::f32::consts::PI + rotation @@ -153,11 +151,9 @@ impl Rectangle { pub fn distance(&self, point: Point) -> f32 { let center = self.center(); - let distance_x = - ((point.x - center.x).abs() - self.width / 2.0).max(0.0); + let distance_x = ((point.x - center.x).abs() - self.width / 2.0).max(0.0); - let distance_y = - ((point.y - center.y).abs() - self.height / 2.0).max(0.0); + let distance_y = ((point.y - center.y).abs() - self.height / 2.0).max(0.0); distance_x.hypot(distance_y) } @@ -212,16 +208,11 @@ impl Rectangle { /// not be on the border. pub fn is_within_strict(&self, container: &Rectangle) -> bool { container.contains_strict(self.position()) - && container.contains_strict( - self.position() + Vector::new(self.width, self.height), - ) + && container.contains_strict(self.position() + Vector::new(self.width, self.height)) } /// Computes the intersection with the given [`Rectangle`]. - pub fn intersection( - &self, - other: &Rectangle, - ) -> Option> { + pub fn intersection(&self, other: &Rectangle) -> Option> { let x = self.x.max(other.x); let y = self.y.max(other.y); @@ -345,17 +336,13 @@ impl Rectangle { ) -> Point { let x = match align_x.into() { alignment::Horizontal::Left => self.x, - alignment::Horizontal::Center => { - self.x + (self.width - size.width) / 2.0 - } + alignment::Horizontal::Center => self.x + (self.width - size.width) / 2.0, alignment::Horizontal::Right => self.x + self.width - size.width, }; let y = match align_y.into() { alignment::Vertical::Top => self.y, - alignment::Vertical::Center => { - self.y + (self.height - size.height) / 2.0 - } + alignment::Vertical::Center => self.y + (self.height - size.height) / 2.0, alignment::Vertical::Bottom => self.y + self.height - size.height, }; diff --git a/core/src/renderer.rs b/core/src/renderer.rs index eac7b06995..8882558713 100644 --- a/core/src/renderer.rs +++ b/core/src/renderer.rs @@ -4,8 +4,7 @@ mod null; use crate::image; use crate::{ - Background, Border, Color, Font, Pixels, Rectangle, Shadow, Size, - Transformation, Vector, + Background, Border, Color, Font, Pixels, Rectangle, Shadow, Size, Transformation, Vector, }; /// A component that can be used by widgets to draw themselves on a screen. @@ -36,26 +35,15 @@ pub trait Renderer { fn end_transformation(&mut self); /// Applies a [`Transformation`] to the primitives recorded in the given closure. - fn with_transformation( - &mut self, - transformation: Transformation, - f: impl FnOnce(&mut Self), - ) { + fn with_transformation(&mut self, transformation: Transformation, f: impl FnOnce(&mut Self)) { self.start_transformation(transformation); f(self); self.end_transformation(); } /// Applies a translation to the primitives recorded in the given closure. - fn with_translation( - &mut self, - translation: Vector, - f: impl FnOnce(&mut Self), - ) { - self.with_transformation( - Transformation::translate(translation.x, translation.y), - f, - ); + fn with_translation(&mut self, translation: Vector, f: impl FnOnce(&mut Self)) { + self.with_transformation(Transformation::translate(translation.x, translation.y), f); } /// Fills a [`Quad`] with the provided [`Background`]. @@ -68,9 +56,7 @@ pub trait Renderer { fn allocate_image( &mut self, handle: &image::Handle, - callback: impl FnOnce(Result) - + Send - + 'static, + callback: impl FnOnce(Result) + Send + 'static, ); } diff --git a/core/src/renderer/null.rs b/core/src/renderer/null.rs index 52d49c6440..4c7aa14f99 100644 --- a/core/src/renderer/null.rs +++ b/core/src/renderer/null.rs @@ -3,9 +3,7 @@ use crate::image::{self, Image}; use crate::renderer::{self, Renderer}; use crate::svg; use crate::text::{self, Text}; -use crate::{ - Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, -}; +use crate::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation}; impl Renderer for () { fn start_layer(&mut self, _bounds: Rectangle) {} @@ -18,19 +16,12 @@ impl Renderer for () { fn reset(&mut self, _new_bounds: Rectangle) {} - fn fill_quad( - &mut self, - _quad: renderer::Quad, - _background: impl Into, - ) { - } + fn fill_quad(&mut self, _quad: renderer::Quad, _background: impl Into) {} fn allocate_image( &mut self, handle: &image::Handle, - callback: impl FnOnce(Result) - + Send - + 'static, + callback: impl FnOnce(Result) + Send + 'static, ) { #[allow(unsafe_code)] callback(Ok(unsafe { image::allocate(handle, Size::new(100, 100)) })); @@ -95,10 +86,7 @@ impl text::Paragraph for () { fn with_text(_text: Text<&str>) -> Self {} - fn with_spans( - _text: Text<&[text::Span<'_, Link, Self::Font>], Self::Font>, - ) -> Self { - } + fn with_spans(_text: Text<&[text::Span<'_, Link, Self::Font>], Self::Font>) -> Self {} fn resize(&mut self, _new_bounds: Size) {} @@ -230,9 +218,7 @@ impl text::Editor for () { &mut self, _font: Self::Font, _highlighter: &mut H, - _format_highlight: impl Fn( - &H::Highlight, - ) -> text::highlighter::Format, + _format_highlight: impl Fn(&H::Highlight) -> text::highlighter::Format, ) { } } @@ -240,10 +226,7 @@ impl text::Editor for () { impl image::Renderer for () { type Handle = image::Handle; - fn load_image( - &self, - handle: &Self::Handle, - ) -> Result { + fn load_image(&self, handle: &Self::Handle) -> Result { #[allow(unsafe_code)] Ok(unsafe { image::allocate(handle, Size::new(100, 100)) }) } @@ -252,13 +235,7 @@ impl image::Renderer for () { Some(Size::new(100, 100)) } - fn draw_image( - &mut self, - _image: Image, - _bounds: Rectangle, - _clip_bounds: Rectangle, - ) { - } + fn draw_image(&mut self, _image: Image, _bounds: Rectangle, _clip_bounds: Rectangle) {} } impl svg::Renderer for () { @@ -266,13 +243,7 @@ impl svg::Renderer for () { Size::default() } - fn draw_svg( - &mut self, - _svg: svg::Svg, - _bounds: Rectangle, - _clip_bounds: Rectangle, - ) { - } + fn draw_svg(&mut self, _svg: svg::Svg, _bounds: Rectangle, _clip_bounds: Rectangle) {} } impl renderer::Headless for () { diff --git a/core/src/shell.rs b/core/src/shell.rs index 31659bfbb8..120837aaa1 100644 --- a/core/src/shell.rs +++ b/core/src/shell.rs @@ -68,10 +68,7 @@ impl<'a, Message> Shell<'a, Message> { } /// Requests a new frame to be drawn at the given [`window::RedrawRequest`]. - pub fn request_redraw_at( - &mut self, - redraw_request: impl Into, - ) { + pub fn request_redraw_at(&mut self, redraw_request: impl Into) { self.redraw_request = self.redraw_request.min(redraw_request.into()); } @@ -86,10 +83,7 @@ impl<'a, Message> Shell<'a, Message> { /// This is useful if you want to overwrite the redraw request to a previous value. /// Since it's a fairly advanced use case and should rarely be used, it is a static /// method. - pub fn replace_redraw_request( - shell: &mut Self, - redraw_request: window::RedrawRequest, - ) { + pub fn replace_redraw_request(shell: &mut Self, redraw_request: window::RedrawRequest) { shell.redraw_request = redraw_request; } @@ -97,10 +91,7 @@ impl<'a, Message> Shell<'a, Message> { /// /// __Important__: This request will only be honored by the /// [`Shell`] only during a [`window::Event::RedrawRequested`]. - pub fn request_input_method>( - &mut self, - ime: &InputMethod, - ) { + pub fn request_input_method>(&mut self, ime: &InputMethod) { self.input_method.merge(ime); } @@ -160,11 +151,9 @@ impl<'a, Message> Shell<'a, Message> { pub fn merge(&mut self, other: Shell<'_, B>, f: impl Fn(B) -> Message) { self.messages.extend(other.messages.drain(..).map(f)); - self.is_layout_invalid = - self.is_layout_invalid || other.is_layout_invalid; + self.is_layout_invalid = self.is_layout_invalid || other.is_layout_invalid; - self.are_widgets_invalid = - self.are_widgets_invalid || other.are_widgets_invalid; + self.are_widgets_invalid = self.are_widgets_invalid || other.are_widgets_invalid; self.redraw_request = self.redraw_request.min(other.redraw_request); self.event_status = self.event_status.merge(other.event_status); diff --git a/core/src/size.rs b/core/src/size.rs index 3285509076..61c83603fb 100644 --- a/core/src/size.rs +++ b/core/src/size.rs @@ -58,10 +58,8 @@ impl Size { let radians = f32::from(rotation); Size { - width: (self.width * radians.cos()).abs() - + (self.height * radians.sin()).abs(), - height: (self.width * radians.sin()).abs() - + (self.height * radians.cos()).abs(), + width: (self.width * radians.cos()).abs() + (self.height * radians.sin()).abs(), + height: (self.width * radians.sin()).abs() + (self.height * radians.cos()).abs(), } } @@ -79,8 +77,7 @@ impl Size { /// Returns true if either `width` or `height` are 0-sized. #[inline] pub fn is_void(&self) -> bool { - matches!(self.width, Length::Fixed(0.0)) - || matches!(self.height, Length::Fixed(0.0)) + matches!(self.width, Length::Fixed(0.0)) || matches!(self.height, Length::Fixed(0.0)) } } diff --git a/core/src/text.rs b/core/src/text.rs index 674eccf911..aa32208279 100644 --- a/core/src/text.rs +++ b/core/src/text.rs @@ -8,9 +8,7 @@ pub use highlighter::Highlighter; pub use paragraph::Paragraph; use crate::alignment; -use crate::{ - Background, Border, Color, Padding, Pixels, Point, Rectangle, Size, -}; +use crate::{Background, Border, Color, Padding, Pixels, Point, Rectangle, Size}; use std::borrow::Cow; use std::hash::{Hash, Hasher}; @@ -526,10 +524,7 @@ impl<'a, Link, Font> Span<'a, Link, Font> { } /// Sets the [`Background`] of the [`Span`], if any. - pub fn background_maybe( - mut self, - background: Option>, - ) -> Self { + pub fn background_maybe(mut self, background: Option>) -> Self { let Some(background) = background else { return self; }; diff --git a/core/src/text/paragraph.rs b/core/src/text/paragraph.rs index 685c3b37e4..2dbdabb3f0 100644 --- a/core/src/text/paragraph.rs +++ b/core/src/text/paragraph.rs @@ -1,8 +1,7 @@ //! Draw paragraphs. use crate::alignment; use crate::text::{ - Affinity, Alignment, Difference, Hit, LineHeight, Shaping, Span, Text, - Wrapping, + Affinity, Alignment, Difference, Hit, LineHeight, Shaping, Span, Text, Wrapping, }; use crate::{Pixels, Point, Rectangle, Size}; @@ -17,9 +16,7 @@ pub trait Paragraph: Sized + Default { fn with_text(text: Text<&str, Self::Font>) -> Self; /// Creates a new [`Paragraph`] laid out with the given [`Text`]. - fn with_spans( - text: Text<&[Span<'_, Link, Self::Font>], Self::Font>, - ) -> Self; + fn with_spans(text: Text<&[Span<'_, Link, Self::Font>], Self::Font>) -> Self; /// Lays out the [`Paragraph`] with some new boundaries. fn resize(&mut self, new_bounds: Size); diff --git a/core/src/theme.rs b/core/src/theme.rs index ead3015a5f..8890e62ffc 100644 --- a/core/src/theme.rs +++ b/core/src/theme.rs @@ -88,10 +88,7 @@ impl Theme { ]; /// Creates a new custom [`Theme`] from the given [`Palette`]. - pub fn custom( - name: impl Into>, - palette: Palette, - ) -> Self { + pub fn custom(name: impl Into>, palette: Palette) -> Self { Self::custom_with_fn(name, palette, palette::Extended::generate) } @@ -147,9 +144,7 @@ impl Theme { Self::GruvboxDark => &palette::EXTENDED_GRUVBOX_DARK, Self::CatppuccinLatte => &palette::EXTENDED_CATPPUCCIN_LATTE, Self::CatppuccinFrappe => &palette::EXTENDED_CATPPUCCIN_FRAPPE, - Self::CatppuccinMacchiato => { - &palette::EXTENDED_CATPPUCCIN_MACCHIATO - } + Self::CatppuccinMacchiato => &palette::EXTENDED_CATPPUCCIN_MACCHIATO, Self::CatppuccinMocha => &palette::EXTENDED_CATPPUCCIN_MOCHA, Self::TokyoNight => &palette::EXTENDED_TOKYO_NIGHT, Self::TokyoNightStorm => &palette::EXTENDED_TOKYO_NIGHT_STORM, diff --git a/core/src/theme/palette.rs b/core/src/theme/palette.rs index 57f4ff8275..86c45af0ed 100644 --- a/core/src/theme/palette.rs +++ b/core/src/theme/palette.rs @@ -307,16 +307,14 @@ pub static EXTENDED_LIGHT: LazyLock = LazyLock::new(|| Extended::generate(Palette::LIGHT)); /// The built-in dark variant of an [`Extended`] palette. -pub static EXTENDED_DARK: LazyLock = - LazyLock::new(|| Extended::generate(Palette::DARK)); +pub static EXTENDED_DARK: LazyLock = LazyLock::new(|| Extended::generate(Palette::DARK)); /// The built-in Dracula variant of an [`Extended`] palette. pub static EXTENDED_DRACULA: LazyLock = LazyLock::new(|| Extended::generate(Palette::DRACULA)); /// The built-in Nord variant of an [`Extended`] palette. -pub static EXTENDED_NORD: LazyLock = - LazyLock::new(|| Extended::generate(Palette::NORD)); +pub static EXTENDED_NORD: LazyLock = LazyLock::new(|| Extended::generate(Palette::NORD)); /// The built-in Solarized Light variant of an [`Extended`] palette. pub static EXTENDED_SOLARIZED_LIGHT: LazyLock = @@ -395,27 +393,11 @@ impl Extended { pub fn generate(palette: Palette) -> Self { Self { background: Background::new(palette.background, palette.text), - primary: Primary::generate( - palette.primary, - palette.background, - palette.text, - ), + primary: Primary::generate(palette.primary, palette.background, palette.text), secondary: Secondary::generate(palette.background, palette.text), - success: Success::generate( - palette.success, - palette.background, - palette.text, - ), - warning: Warning::generate( - palette.warning, - palette.background, - palette.text, - ), - danger: Danger::generate( - palette.danger, - palette.background, - palette.text, - ), + success: Success::generate(palette.success, palette.background, palette.text), + warning: Warning::generate(palette.warning, palette.background, palette.text), + danger: Danger::generate(palette.danger, palette.background, palette.text), is_dark: is_dark(palette.background), } } diff --git a/core/src/transformation.rs b/core/src/transformation.rs index 09287e227e..c27f3f45b7 100644 --- a/core/src/transformation.rs +++ b/core/src/transformation.rs @@ -89,12 +89,9 @@ impl Mul for Size { type Output = Self; fn mul(self, transformation: Transformation) -> Self { - let new_size = transformation.0.mul_vec4(Vec4::new( - self.width, - self.height, - 1.0, - 0.0, - )); + let new_size = transformation + .0 + .mul_vec4(Vec4::new(self.width, self.height, 1.0, 0.0)); Size::new(new_size.x, new_size.y) } diff --git a/core/src/widget/operation.rs b/core/src/widget/operation.rs index 40f010649d..ab7da5cb35 100644 --- a/core/src/widget/operation.rs +++ b/core/src/widget/operation.rs @@ -42,34 +42,16 @@ pub trait Operation: Send { } /// Operates on a widget that can be focused. - fn focusable( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - _state: &mut dyn Focusable, - ) { - } + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn Focusable) {} /// Operates on a widget that has text input. - fn text_input( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - _state: &mut dyn TextInput, - ) { - } + fn text_input(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn TextInput) {} /// Operates on a widget that contains some text. fn text(&mut self, _id: Option<&Id>, _bounds: Rectangle, _text: &str) {} /// Operates on a custom widget with some state. - fn custom( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - _state: &mut dyn Any, - ) { - } + fn custom(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn Any) {} /// Finishes the [`Operation`] and returns its [`Outcome`]. fn finish(&self) -> Outcome { @@ -89,12 +71,7 @@ where self.as_mut().container(id, bounds); } - fn focusable( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.as_mut().focusable(id, bounds, state); } @@ -106,21 +83,11 @@ where translation: Vector, state: &mut dyn Scrollable, ) { - self.as_mut().scrollable( - id, - bounds, - content_bounds, - translation, - state, - ); + self.as_mut() + .scrollable(id, bounds, content_bounds, translation, state); } - fn text_input( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.as_mut().text_input(id, bounds, state); } @@ -128,12 +95,7 @@ where self.as_mut().text(id, bounds, text); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.as_mut().custom(id, bounds, state); } @@ -168,9 +130,7 @@ where } /// Wraps the [`Operation`] in a black box, erasing its returning type. -pub fn black_box<'a, T, O>( - operation: &'a mut dyn Operation, -) -> impl Operation + 'a +pub fn black_box<'a, T, O>(operation: &'a mut dyn Operation) -> impl Operation + 'a where T: 'a, { @@ -192,12 +152,7 @@ where self.operation.container(id, bounds); } - fn focusable( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } @@ -209,21 +164,11 @@ where translation: Vector, state: &mut dyn Scrollable, ) { - self.operation.scrollable( - id, - bounds, - content_bounds, - translation, - state, - ); + self.operation + .scrollable(id, bounds, content_bounds, translation, state); } - fn text_input( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } @@ -231,12 +176,7 @@ where self.operation.text(id, bounds, text); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } @@ -274,10 +214,7 @@ where } impl Operation for MapRef<'_, A> { - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { self.operation.traverse(&mut |operation| { operate(&mut MapRef { operation }); }); @@ -297,13 +234,8 @@ where translation: Vector, state: &mut dyn Scrollable, ) { - self.operation.scrollable( - id, - bounds, - content_bounds, - translation, - state, - ); + self.operation + .scrollable(id, bounds, content_bounds, translation, state); } fn focusable( @@ -324,21 +256,11 @@ where self.operation.text_input(id, bounds, state); } - fn text( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - text: &str, - ) { + fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) { self.operation.text(id, bounds, text); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } } @@ -352,12 +274,7 @@ where self.operation.container(id, bounds); } - fn focusable( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } @@ -369,21 +286,11 @@ where translation: Vector, state: &mut dyn Scrollable, ) { - self.operation.scrollable( - id, - bounds, - content_bounds, - translation, - state, - ); + self.operation + .scrollable(id, bounds, content_bounds, translation, state); } - fn text_input( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } @@ -391,12 +298,7 @@ where self.operation.text(id, bounds, text); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } @@ -420,10 +322,7 @@ where /// Chains the output of an [`Operation`] with the provided function to /// build a new [`Operation`]. -pub fn then( - operation: impl Operation + 'static, - f: fn(A) -> O, -) -> impl Operation +pub fn then(operation: impl Operation + 'static, f: fn(A) -> O) -> impl Operation where A: 'static, B: Send + 'static, @@ -456,12 +355,7 @@ where self.operation.container(id, bounds); } - fn focusable( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { self.operation.focusable(id, bounds, state); } @@ -473,21 +367,11 @@ where translation: crate::Vector, state: &mut dyn Scrollable, ) { - self.operation.scrollable( - id, - bounds, - content_bounds, - translation, - state, - ); + self.operation + .scrollable(id, bounds, content_bounds, translation, state); } - fn text_input( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { self.operation.text_input(id, bounds, state); } @@ -495,24 +379,15 @@ where self.operation.text(id, bounds, text); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { self.operation.custom(id, bounds, state); } fn finish(&self) -> Outcome { match self.operation.finish() { Outcome::None => Outcome::None, - Outcome::Some(value) => { - Outcome::Chain(Box::new((self.next)(value))) - } - Outcome::Chain(operation) => { - Outcome::Chain(Box::new(then(operation, self.next))) - } + Outcome::Some(value) => Outcome::Chain(Box::new((self.next)(value))), + Outcome::Chain(operation) => Outcome::Chain(Box::new(then(operation, self.next))), } } } @@ -526,10 +401,7 @@ where /// Produces an [`Operation`] that applies the given [`Operation`] to the /// children of a container with the given [`Id`]. -pub fn scoped( - target: Id, - operation: impl Operation + 'static, -) -> impl Operation { +pub fn scoped(target: Id, operation: impl Operation + 'static) -> impl Operation { struct ScopedOperation { target: Id, current: Option, @@ -537,10 +409,7 @@ pub fn scoped( } impl Operation for ScopedOperation { - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { if self.current.as_ref() == Some(&self.target) { self.operation.as_mut().traverse(operate); } else { @@ -556,13 +425,11 @@ pub fn scoped( fn finish(&self) -> Outcome { match self.operation.finish() { - Outcome::Chain(next) => { - Outcome::Chain(Box::new(ScopedOperation { - target: self.target.clone(), - current: None, - operation: next, - })) - } + Outcome::Chain(next) => Outcome::Chain(Box::new(ScopedOperation { + target: self.target.clone(), + current: None, + operation: next, + })), outcome => outcome, } } diff --git a/core/src/widget/operation/focusable.rs b/core/src/widget/operation/focusable.rs index 0b86766a25..18c5f813ac 100644 --- a/core/src/widget/operation/focusable.rs +++ b/core/src/widget/operation/focusable.rs @@ -33,12 +33,7 @@ pub fn focus(target: Id) -> impl Operation { } impl Operation for Focus { - fn focusable( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { match id { Some(id) if IdEq::eq(&id.0, &self.target.0) => { state.focus(); @@ -62,12 +57,7 @@ pub fn unfocus() -> impl Operation { struct Unfocus; impl Operation for Unfocus { - fn focusable( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { state.unfocus(); } @@ -87,12 +77,7 @@ pub fn count() -> impl Operation { } impl Operation for CountFocusable { - fn focusable( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if state.is_focused() { self.count.focused = Some(self.count.total); } @@ -100,10 +85,7 @@ pub fn count() -> impl Operation { self.count.total += 1; } - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { operate(self); } @@ -130,12 +112,7 @@ where } impl Operation for FocusPrevious { - fn focusable( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if self.count.total == 0 { return; } @@ -144,9 +121,7 @@ where None if self.current == self.count.total - 1 => state.focus(), Some(0) if self.current == 0 && self.count.total == 1 => {} Some(0) if self.current == 0 => state.unfocus(), - Some(0) if self.current == self.count.total - 1 => { - state.focus() - } + Some(0) if self.current == self.count.total - 1 => state.focus(), Some(0) => {} Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused - 1 == self.current => state.focus(), @@ -177,21 +152,13 @@ where } impl Operation for FocusNext { - fn focusable( - &mut self, - _id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { match self.count.focused { None if self.current == 0 => state.focus(), - Some(focused) - if focused == self.current && self.count.total == 1 => {} + Some(focused) if focused == self.current && self.count.total == 1 => {} Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused + 1 == self.current => state.focus(), - Some(focused) - if focused == self.count.total - 1 && self.current == 0 => - { + Some(focused) if focused == self.count.total - 1 && self.current == 0 => { state.focus() } _ => {} @@ -216,21 +183,13 @@ pub fn find_focused() -> impl Operation { } impl Operation for FindFocused { - fn focusable( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if state.is_focused() && id.is_some() { self.focused = id.cloned(); } } - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { operate(self); } @@ -256,21 +215,13 @@ pub fn is_focused(target: Id) -> impl Operation { } impl Operation for IsFocused { - fn focusable( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) { if id.is_some_and(|id| *id == self.target) { self.is_focused = Some(state.is_focused()); } } - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { if self.is_focused.is_some() { return; } diff --git a/core/src/widget/operation/scrollable.rs b/core/src/widget/operation/scrollable.rs index 1a1ea24ff6..39957e448f 100644 --- a/core/src/widget/operation/scrollable.rs +++ b/core/src/widget/operation/scrollable.rs @@ -11,20 +11,12 @@ pub trait Scrollable { fn scroll_to(&mut self, offset: AbsoluteOffset>); /// Scroll the widget by the given [`AbsoluteOffset`] along the horizontal & vertical axis. - fn scroll_by( - &mut self, - offset: AbsoluteOffset, - bounds: Rectangle, - content_bounds: Rectangle, - ); + fn scroll_by(&mut self, offset: AbsoluteOffset, bounds: Rectangle, content_bounds: Rectangle); } /// Produces an [`Operation`] that snaps the widget with the given [`Id`] to /// the provided `percentage`. -pub fn snap_to( - target: Id, - offset: RelativeOffset>, -) -> impl Operation { +pub fn snap_to(target: Id, offset: RelativeOffset>) -> impl Operation { struct SnapTo { target: Id, offset: RelativeOffset>, @@ -54,10 +46,7 @@ pub fn snap_to( /// Produces an [`Operation`] that scrolls the widget with the given [`Id`] to /// the provided [`AbsoluteOffset`]. -pub fn scroll_to( - target: Id, - offset: AbsoluteOffset>, -) -> impl Operation { +pub fn scroll_to(target: Id, offset: AbsoluteOffset>) -> impl Operation { struct ScrollTo { target: Id, offset: AbsoluteOffset>, diff --git a/core/src/widget/operation/search_id.rs b/core/src/widget/operation/search_id.rs index 1286abafa7..bc3b2428dc 100644 --- a/core/src/widget/operation/search_id.rs +++ b/core/src/widget/operation/search_id.rs @@ -15,12 +15,7 @@ pub fn search_id(target: Id) -> impl Operation { } impl Operation for Find { - fn custom( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - _state: &mut dyn std::any::Any, - ) { + fn custom(&mut self, id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn std::any::Any) { if Some(&self.target) == id { self.found = true; } @@ -34,10 +29,7 @@ pub fn search_id(target: Id) -> impl Operation { } } - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { operate(self); } } diff --git a/core/src/widget/operation/text_input.rs b/core/src/widget/operation/text_input.rs index 6fbafb79ad..dfbee79930 100644 --- a/core/src/widget/operation/text_input.rs +++ b/core/src/widget/operation/text_input.rs @@ -33,12 +33,7 @@ pub fn move_cursor_to_front(target: Id) -> impl Operation { } impl Operation for MoveCursor { - fn text_input( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to_front(); @@ -63,12 +58,7 @@ pub fn move_cursor_to_end(target: Id) -> impl Operation { } impl Operation for MoveCursor { - fn text_input( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to_end(); @@ -94,12 +84,7 @@ pub fn move_cursor_to(target: Id, position: usize) -> impl Operation { } impl Operation for MoveCursor { - fn text_input( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.move_cursor_to(self.position); @@ -123,12 +108,7 @@ pub fn select_all(target: Id) -> impl Operation { } impl Operation for MoveCursor { - fn text_input( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.select_all(); @@ -146,11 +126,7 @@ pub fn select_all(target: Id) -> impl Operation { } /// Produces an [`Operation`] that selects the given content range of the widget with the given [`Id`]. -pub fn select_range( - target: Id, - start: usize, - end: usize, -) -> impl Operation { +pub fn select_range(target: Id, start: usize, end: usize) -> impl Operation { struct SelectRange { target: Id, start: usize, @@ -158,12 +134,7 @@ pub fn select_range( } impl Operation for SelectRange { - fn text_input( - &mut self, - id: Option<&Id>, - _bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) { match id { Some(id) if id == &self.target => { state.select_range(self.start, self.end); diff --git a/core/src/widget/text.rs b/core/src/widget/text.rs index 1e40bf9e2a..a2d95a32ee 100644 --- a/core/src/widget/text.rs +++ b/core/src/widget/text.rs @@ -27,9 +27,7 @@ use crate::renderer; use crate::text::paragraph::{self, Paragraph}; use crate::text::{self, Fragment}; use crate::widget::tree::{self, Tree}; -use crate::{ - Color, Element, Layout, Length, Pixels, Rectangle, Size, Theme, Widget, -}; +use crate::{Color, Element, Layout, Length, Pixels, Rectangle, Size, Theme, Widget}; use std::borrow::Cow; pub use text::{Alignment, Ellipsize, LineHeight, Shaping, Wrapping}; @@ -105,10 +103,7 @@ where /// Sets the [`Font`] of the [`Text`], if `Some`. /// /// [`Font`]: crate::text::Renderer::Font - pub fn font_maybe( - mut self, - font: Option>, - ) -> Self { + pub fn font_maybe(mut self, font: Option>) -> Self { self.format.font = font.map(Into::into); self } @@ -138,10 +133,7 @@ where } /// Sets the [`alignment::Vertical`] of the [`Text`]. - pub fn align_y( - mut self, - alignment: impl Into, - ) -> Self { + pub fn align_y(mut self, alignment: impl Into) -> Self { self.format.align_y = alignment.into(); self } @@ -204,8 +196,7 @@ where /// The internal state of a [`Text`] widget. pub type State

= paragraph::Plain

; -impl Widget - for Text<'_, Theme, Renderer> +impl Widget for Text<'_, Theme, Renderer> where Theme: Catalog, Renderer: text::Renderer, @@ -291,12 +282,7 @@ where width, height, } = layout.bounds(); - let bounds = Rect::new( - x as f64, - y as f64, - (x + width) as f64, - (y + height) as f64, - ); + let bounds = Rect::new(x as f64, y as f64, (x + width) as f64, (y + height) as f64); let mut node = Node::new(Role::Paragraph); @@ -419,9 +405,7 @@ where Theme: Catalog + 'a, Renderer: text::Renderer + 'a, { - fn from( - text: Text<'a, Theme, Renderer>, - ) -> Element<'a, Message, Theme, Renderer> { + fn from(text: Text<'a, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> { Element::new(text) } } @@ -459,8 +443,7 @@ where } } -impl<'a, Message, Theme, Renderer> From<&'a str> - for Element<'a, Message, Theme, Renderer> +impl<'a, Message, Theme, Renderer> From<&'a str> for Element<'a, Message, Theme, Renderer> where Theme: Catalog + 'a, Renderer: text::Renderer + 'a, diff --git a/core/src/widget/tree.rs b/core/src/widget/tree.rs index 7035c2c9d7..5d821aff7f 100644 --- a/core/src/widget/tree.rs +++ b/core/src/widget/tree.rs @@ -59,9 +59,7 @@ impl Tree { } /// Takes all named widgets from the tree. - pub fn take_all_named( - &mut self, - ) -> HashMap, (State, Vec<(usize, Tree)>)> { + pub fn take_all_named(&mut self) -> HashMap, (State, Vec<(usize, Tree)>)> { let mut named = HashMap::new(); struct Visit { parent: Cow<'static, str>, @@ -75,25 +73,21 @@ impl Tree { if let Some(Id(Internal::Custom(_, n))) = tree.id.clone() { let state = mem::replace(&mut tree.state, State::None); let children_count = tree.children.len(); - let children = - tree.children.iter_mut().enumerate().rev().map(|(i, c)| { - if matches!(c.id, Some(Id(Internal::Custom(_, _)))) { - (c, None) - } else { - ( - c, - Some(Visit { - index: i, - parent: n.clone(), - visited: false, - }), - ) - } - }); - _ = named.insert( - n.clone(), - (state, Vec::with_capacity(children_count)), - ); + let children = tree.children.iter_mut().enumerate().rev().map(|(i, c)| { + if matches!(c.id, Some(Id(Internal::Custom(_, _)))) { + (c, None) + } else { + ( + c, + Some(Visit { + index: i, + parent: n.clone(), + visited: false, + }), + ) + } + }); + _ = named.insert(n.clone(), (state, Vec::with_capacity(children_count))); stack.extend(children); } else if let Some(visit) = visit { if visit.visited { @@ -161,8 +155,7 @@ impl Tree { ) where Renderer: crate::Renderer, { - let borrowed: &mut dyn Widget = - new.borrow_mut(); + let borrowed: &mut dyn Widget = new.borrow_mut(); let mut tag_match = self.tag == borrowed.tag(); @@ -172,8 +165,7 @@ impl Tree { .with(|named| named.borrow_mut().remove(&n)) .or_else(|| { //check self.id - if let Some(Id(Internal::Custom(_, ref name))) = self.id - { + if let Some(Id(Internal::Custom(_, ref name))) = self.id { if name == &n { Some(( mem::replace(&mut self.state, State::None), @@ -207,8 +199,7 @@ impl Tree { self.children = widget_children; } else { for (old_i, mut old) in children { - let Some(my_state) = self.children.get_mut(old_i) - else { + let Some(my_state) = self.children.get_mut(old_i) else { continue; }; if my_state.tag != old.tag || { @@ -217,10 +208,9 @@ impl Tree { Some(Id(Internal::Custom(_, old_name))), Some(Id(Internal::Custom(_, my_name))), ) => old_name == my_name, - ( - Some(Id(Internal::Set(a))), - Some(Id(Internal::Set(b))), - ) => a.len() == b.len(), + (Some(Id(Internal::Set(a))), Some(Id(Internal::Set(b)))) => { + a.len() == b.len() + } ( Some(Id(Internal::Unique(_))), Some(Id(Internal::Unique(_))), @@ -256,9 +246,7 @@ impl Tree { /// Reconciles the children of the tree with the provided list of widgets. pub fn diff_children<'a, Message, Theme, Renderer>( &mut self, - new_children: &mut [impl BorrowMut< - dyn Widget + 'a, - >], + new_children: &mut [impl BorrowMut + 'a>], ) where Renderer: crate::Renderer, { @@ -291,30 +279,25 @@ impl Tree { } let children_len = self.children.len(); - let (mut id_map, mut id_list): ( - HashMap, - VecDeque<(usize, &mut Tree)>, - ) = self.children.iter_mut().enumerate().fold( - (HashMap::new(), VecDeque::with_capacity(children_len)), - |(mut id_map, mut id_list), (i, c)| { - if let Some(id) = c.id.as_ref() { - if let Internal::Custom(_, ref name) = id.0 { - let _ = id_map.insert(name.to_string(), c); + let (mut id_map, mut id_list): (HashMap, VecDeque<(usize, &mut Tree)>) = + self.children.iter_mut().enumerate().fold( + (HashMap::new(), VecDeque::with_capacity(children_len)), + |(mut id_map, mut id_list), (i, c)| { + if let Some(id) = c.id.as_ref() { + if let Internal::Custom(_, ref name) = id.0 { + let _ = id_map.insert(name.to_string(), c); + } else { + id_list.push_back((i, c)); + } } else { id_list.push_back((i, c)); } - } else { - id_list.push_back((i, c)); - } - (id_map, id_list) - }, - ); + (id_map, id_list) + }, + ); - let mut new_trees: Vec<(Tree, usize)> = - Vec::with_capacity(new_children.len()); - for (i, (new, new_id)) in - new_children.iter_mut().zip(new_ids.iter()).enumerate() - { + let mut new_trees: Vec<(Tree, usize)> = Vec::with_capacity(new_children.len()); + for (i, (new, new_id)) in new_children.iter_mut().zip(new_ids.iter()).enumerate() { let child_state = if let Some(c) = new_id.as_ref().and_then(|id| { if let Internal::Custom(_, ref name) = id.0 { id_map.remove(name.as_ref()) @@ -396,9 +379,7 @@ pub fn diff_children_custom_with_search( }; let _ = current_children.splice( - difference_index - ..difference_index - + (current_children.len() - new_children.len()), + difference_index..difference_index + (current_children.len() - new_children.len()), std::iter::empty(), ); } @@ -409,9 +390,7 @@ pub fn diff_children_custom_with_search( let last_maybe_changed = maybe_changed(current_children.len() - 1); if !first_maybe_changed && last_maybe_changed { - current_children.extend( - new_children[current_children.len()..].iter().map(new_state), - ); + current_children.extend(new_children[current_children.len()..].iter().map(new_state)); } else { let difference_index = if first_maybe_changed { 0 @@ -424,8 +403,7 @@ pub fn diff_children_custom_with_search( let _ = current_children.splice( difference_index..difference_index, new_children[difference_index - ..difference_index - + (new_children.len() - current_children.len())] + ..difference_index + (new_children.len() - current_children.len())] .iter() .map(new_state), ); @@ -433,9 +411,7 @@ pub fn diff_children_custom_with_search( } // TODO: Merge loop with extend logic (?) - for (child_state, new) in - current_children.iter_mut().zip(new_children.iter_mut()) - { + for (child_state, new) in current_children.iter_mut().zip(new_children.iter_mut()) { diff(child_state, new); } } @@ -487,9 +463,7 @@ impl State { { match self { State::None => panic!("Downcast on stateless state"), - State::Some(state) => { - state.downcast_ref().expect("Downcast widget state") - } + State::Some(state) => state.downcast_ref().expect("Downcast widget state"), } } @@ -503,9 +477,7 @@ impl State { { match self { State::None => panic!("Downcast on stateless state"), - State::Some(state) => { - state.downcast_mut().expect("Downcast widget state") - } + State::Some(state) => state.downcast_mut().expect("Downcast widget state"), } } } diff --git a/core/src/window/icon.rs b/core/src/window/icon.rs index fe4a7083f2..8c19c4dd51 100644 --- a/core/src/window/icon.rs +++ b/core/src/window/icon.rs @@ -4,11 +4,7 @@ use crate::Size; use std::mem; /// Builds an [`Icon`] from its RGBA pixels in the `sRGB` color space. -pub fn from_rgba( - rgba: Vec, - width: u32, - height: u32, -) -> Result { +pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { const PIXEL_SIZE: usize = mem::size_of::() * 4; if !rgba.len().is_multiple_of(PIXEL_SIZE) { diff --git a/core/src/window/screenshot.rs b/core/src/window/screenshot.rs index cc4fe00ef8..4f6e6855d3 100644 --- a/core/src/window/screenshot.rs +++ b/core/src/window/screenshot.rs @@ -31,11 +31,7 @@ impl Debug for Screenshot { impl Screenshot { /// Creates a new [`Screenshot`]. - pub fn new( - rgba: impl Into, - size: Size, - scale_factor: f32, - ) -> Self { + pub fn new(rgba: impl Into, size: Size, scale_factor: f32) -> Self { Self { rgba: rgba.into(), size, @@ -50,8 +46,7 @@ impl Screenshot { return Err(CropError::Zero); } - if region.x + region.width > self.size.width - || region.y + region.height > self.size.height + if region.x + region.width > self.size.width || region.y + region.height > self.size.height { return Err(CropError::OutOfBounds); } @@ -61,19 +56,20 @@ impl Screenshot { let bytes_per_row = self.size.width as usize * PIXEL_SIZE; let row_range = region.y as usize..(region.y + region.height) as usize; - let column_range = region.x as usize * PIXEL_SIZE - ..(region.x + region.width) as usize * PIXEL_SIZE; + let column_range = + region.x as usize * PIXEL_SIZE..(region.x + region.width) as usize * PIXEL_SIZE; - let chopped = self.rgba.chunks(bytes_per_row).enumerate().fold( - vec![], - |mut acc, (row, bytes)| { - if row_range.contains(&row) { - acc.extend(&bytes[column_range.clone()]); - } + let chopped = + self.rgba + .chunks(bytes_per_row) + .enumerate() + .fold(vec![], |mut acc, (row, bytes)| { + if row_range.contains(&row) { + acc.extend(&bytes[column_range.clone()]); + } - acc - }, - ); + acc + }); Ok(Self { rgba: Bytes::from(chopped), diff --git a/debug/src/lib.rs b/debug/src/lib.rs index e20c00e648..c195093d76 100644 --- a/debug/src/lib.rs +++ b/debug/src/lib.rs @@ -147,12 +147,11 @@ mod internal { pub fn init(metadata: Metadata) { let name = metadata.name.split("::").next().unwrap_or(metadata.name); - *METADATA.write().expect("Write application metadata") = - client::Metadata { - name, - theme: metadata.theme, - can_time_travel: metadata.can_time_travel, - }; + *METADATA.write().expect("Write application metadata") = client::Metadata { + name, + theme: metadata.theme, + can_time_travel: metadata.can_time_travel, + }; } pub fn quit() -> bool { @@ -170,9 +169,7 @@ mod internal { return; }; - if METADATA.read().expect("Read last palette").theme.as_ref() - != Some(&palette) - { + if METADATA.read().expect("Read last palette").theme.as_ref() != Some(&palette) { log(client::Event::ThemeChanged(palette)); METADATA.write().expect("Write last palette").theme = Some(palette); @@ -205,9 +202,7 @@ mod internal { let elapsed = start.elapsed(); if elapsed.as_millis() >= 1 { - log::warn!( - "Slow `Debug` implementation of `Message` (took {elapsed:?})!" - ); + log::warn!("Slow `Debug` implementation of `Message` (took {elapsed:?})!"); } let message = if message.len() > 49 { @@ -271,9 +266,7 @@ mod internal { stream::unfold(BEACON.subscribe(), async move |mut receiver| { let command = match receiver.recv().await? { - client::Command::RewindTo { message } => { - Command::RewindTo { message } - } + client::Command::RewindTo { message } => Command::RewindTo { message }, client::Command::GoLive => Command::GoLive, }; @@ -421,8 +414,7 @@ mod hot { static IS_STALE: AtomicBool = AtomicBool::new(false); - static HOT_FUNCTIONS_PENDING: Mutex> = - Mutex::new(BTreeSet::new()); + static HOT_FUNCTIONS_PENDING: Mutex> = Mutex::new(BTreeSet::new()); static HOT_FUNCTIONS: OnceLock> = OnceLock::new(); @@ -433,9 +425,7 @@ mod hot { if HOT_FUNCTIONS.get().is_none() { HOT_FUNCTIONS .set(std::mem::take( - &mut HOT_FUNCTIONS_PENDING - .lock() - .expect("Lock hot functions"), + &mut HOT_FUNCTIONS_PENDING.lock().expect("Lock hot functions"), )) .expect("Set hot functions"); } diff --git a/devtools/src/comet.rs b/devtools/src/comet.rs index 7b9f4b33fb..e2189dc52e 100644 --- a/devtools/src/comet.rs +++ b/devtools/src/comet.rs @@ -2,8 +2,7 @@ use crate::runtime::task::{self, Task}; use std::process; -pub const COMPATIBLE_REVISION: &str = - "3f75f3240edc1719df584810337bc7df010327d8"; +pub const COMPATIBLE_REVISION: &str = "3f75f3240edc1719df584810337bc7df010327d8"; pub fn launch() -> Task { task::try_blocking(|mut sender| { @@ -65,9 +64,7 @@ pub fn install() -> Task { .stderr(Stdio::piped()) .spawn()?; - let mut stderr = BufReader::new( - install.stderr.take().expect("stderr must be piped"), - ); + let mut stderr = BufReader::new(install.stderr.take().expect("stderr must be piped")); let mut log = String::new(); @@ -82,8 +79,7 @@ pub fn install() -> Task { } } - let _ = sender - .try_send(install::Event::Logged(log.trim_end().to_owned())); + let _ = sender.try_send(install::Event::Logged(log.trim_end().to_owned())); log.clear(); } diff --git a/devtools/src/lib.rs b/devtools/src/lib.rs index 9c84290bc6..7d53029c90 100644 --- a/devtools/src/lib.rs +++ b/devtools/src/lib.rs @@ -14,17 +14,15 @@ use crate::core::keyboard; use crate::core::theme::{self, Theme}; use crate::core::time::seconds; use crate::core::window; -use crate::core::{ - Alignment::Center, Color, Element, Font, Length::Fill, Settings, -}; +use crate::core::{Alignment::Center, Color, Element, Font, Length::Fill, Settings}; use crate::futures::Subscription; use crate::program::Program; use crate::program::message; use crate::runtime::task::{self, Task}; use crate::time_machine::TimeMachine; use crate::widget::{ - bottom_right, button, center, column, container, opaque, row, scrollable, - space, stack, text, themer, + bottom_right, button, center, column, container, opaque, row, scrollable, space, stack, text, + themer, }; use std::fmt; @@ -74,11 +72,7 @@ where ) } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { state.update(&self.program, message) } @@ -98,11 +92,7 @@ where state.subscription(&self.program) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { state.theme(&self.program, window) } @@ -220,16 +210,14 @@ where Task::none() } Message::InstallComet => { - self.mode = - Mode::Setup(Setup::Running { logs: Vec::new() }); + self.mode = Mode::Setup(Setup::Running { logs: Vec::new() }); comet::install() .map(Message::Installing) .map(Event::Message) } Message::Installing(Ok(installation)) => { - let Mode::Setup(Setup::Running { logs }) = &mut self.mode - else { + let Mode::Setup(Setup::Running { logs }) = &mut self.mode else { return Task::none(); }; @@ -245,8 +233,7 @@ where } } Message::Installing(Err(error)) => { - let Mode::Setup(Setup::Running { logs }) = &mut self.mode - else { + let Mode::Setup(Setup::Running { logs }) = &mut self.mode else { return Task::none(); }; @@ -339,10 +326,7 @@ where .style(container::bordered_box), ) .padding(10) - .style(|_theme| { - container::Style::default() - .background(Color::BLACK.scale_alpha(0.8)) - }); + .style(|_theme| container::Style::default().background(Color::BLACK.scale_alpha(0.8))); Some(themer(theme(), opaque(setup).map(Event::Message))) } else { @@ -353,19 +337,14 @@ where .show_notification .then(|| text("Press F12 to open debug metrics")) .or_else(|| { - debug::is_stale().then(|| { - text( - "Types have changed. Restart to re-enable hotpatching.", - ) - }) + debug::is_stale() + .then(|| text("Types have changed. Restart to re-enable hotpatching.")) }) .map(|notification| { themer( theme(), bottom_right(opaque( - container(notification) - .padding(10) - .style(container::dark), + container(notification).padding(10).style(container::dark), )), ) }); @@ -377,15 +356,13 @@ where } pub fn subscription(&self, program: &P) -> Subscription> { - let subscription = - program.subscription(&self.state).map(Event::Program); + let subscription = program.subscription(&self.state).map(Event::Program); debug::subscriptions_tracked(subscription.units()); let hotkeys = futures::keyboard::listen() .filter_map(|event| match event { keyboard::Event::KeyPressed { - modified_key: - keyboard::Key::Named(keyboard::key::Named::F12), + modified_key: keyboard::Key::Named(keyboard::key::Named::F12), .. } => Some(Message::ToggleComet), _ => None, @@ -527,9 +504,7 @@ where }) } -fn installation<'a, Renderer>( - logs: &'a [String], -) -> Element<'a, Message, Theme, Renderer> +fn installation<'a, Renderer>(logs: &'a [String]) -> Element<'a, Message, Theme, Renderer> where Renderer: program::Renderer + 'a, { @@ -537,9 +512,10 @@ where text("Installing comet...").size(20), container( scrollable( - column(logs.iter().map(|log| { - text(log).size(12).font(Font::MONOSPACE).into() - })) + column( + logs.iter() + .map(|log| { text(log).size(12).font(Font::MONOSPACE).into() }) + ) .spacing(3), ) .spacing(10) diff --git a/examples/arc/src/main.rs b/examples/arc/src/main.rs index 6f801d97c9..69a0fbb941 100644 --- a/examples/arc/src/main.rs +++ b/examples/arc/src/main.rs @@ -1,9 +1,7 @@ use std::{f32::consts::PI, time::Instant}; use iced::mouse; -use iced::widget::canvas::{ - self, Cache, Canvas, Geometry, Path, Stroke, stroke, -}; +use iced::widget::canvas::{self, Cache, Canvas, Geometry, Path, Stroke, stroke}; use iced::window; use iced::{Element, Fill, Point, Rectangle, Renderer, Subscription, Theme}; @@ -64,10 +62,7 @@ impl canvas::Program for Arc { let start = Point::new(center.x, center.y - radius); - let angle = (self.start.elapsed().as_millis() % 10_000) as f32 - / 10_000.0 - * 2.0 - * PI; + let angle = (self.start.elapsed().as_millis() % 10_000) as f32 / 10_000.0 * 2.0 * PI; let end = Point::new( center.x + radius * angle.cos(), diff --git a/examples/bezier_tool/src/main.rs b/examples/bezier_tool/src/main.rs index 2523924ab2..a56616fdfa 100644 --- a/examples/bezier_tool/src/main.rs +++ b/examples/bezier_tool/src/main.rs @@ -55,9 +55,7 @@ impl Example { mod bezier { use iced::mouse; - use iced::widget::canvas::{ - self, Canvas, Event, Frame, Geometry, Path, Stroke, - }; + use iced::widget::canvas::{self, Canvas, Event, Frame, Geometry, Path, Stroke}; use iced::{Element, Fill, Point, Rectangle, Renderer, Theme}; #[derive(Default)] @@ -99,9 +97,7 @@ mod bezier { let cursor_position = cursor.position_in(bounds)?; match event { - Event::Mouse(mouse::Event::ButtonPressed( - mouse::Button::Left, - )) => Some( + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => Some( match *state { None => { *state = Some(Pending::One { @@ -130,9 +126,7 @@ mod bezier { } .and_capture(), ), - Event::Mouse(mouse::Event::CursorMoved { .. }) - if state.is_some() => - { + Event::Mouse(mouse::Event::CursorMoved { .. }) if state.is_some() => { Some(canvas::Action::request_redraw()) } _ => None, @@ -147,17 +141,16 @@ mod bezier { bounds: Rectangle, cursor: mouse::Cursor, ) -> Vec { - let content = - self.state.cache.draw(renderer, bounds.size(), |frame| { - Curve::draw_all(self.curves, frame, theme); - - frame.stroke( - &Path::rectangle(Point::ORIGIN, frame.size()), - Stroke::default() - .with_width(2.0) - .with_color(theme.palette().text), - ); - }); + let content = self.state.cache.draw(renderer, bounds.size(), |frame| { + Curve::draw_all(self.curves, frame, theme); + + frame.stroke( + &Path::rectangle(Point::ORIGIN, frame.size()), + Stroke::default() + .with_width(2.0) + .with_color(theme.palette().text), + ); + }); if let Some(pending) = state { vec![content, pending.draw(renderer, theme, bounds, cursor)] diff --git a/examples/changelog/src/changelog.rs b/examples/changelog/src/changelog.rs index c40faf2d8e..f9026328d2 100644 --- a/examples/changelog/src/changelog.rs +++ b/examples/changelog/src/changelog.rs @@ -233,11 +233,7 @@ pub struct Entry { } impl Entry { - pub fn new( - title: &str, - category: Category, - pull_request: &PullRequest, - ) -> Option { + pub fn new(title: &str, category: Category, pull_request: &PullRequest) -> Option { let title = title.strip_suffix(".").unwrap_or(title); if title.is_empty() { @@ -262,8 +258,7 @@ pub enum Category { } impl Category { - pub const ALL: &'static [Self] = - &[Self::Added, Self::Changed, Self::Fixed, Self::Removed]; + pub const ALL: &'static [Self] = &[Self::Added, Self::Changed, Self::Fixed, Self::Removed]; pub fn guess(label: &str) -> Option { Some(match label { @@ -356,8 +351,7 @@ impl PullRequest { "Authorization", format!( "Bearer {}", - env::var("GITHUB_TOKEN") - .map_err(|_| Error::GitHubTokenNotFound)? + env::var("GITHUB_TOKEN").map_err(|_| Error::GitHubTokenNotFound)? ), ); diff --git a/examples/changelog/src/main.rs b/examples/changelog/src/main.rs index 93e717438a..0f547df407 100644 --- a/examples/changelog/src/main.rs +++ b/examples/changelog/src/main.rs @@ -4,8 +4,8 @@ use crate::changelog::Changelog; use iced::font; use iced::widget::{ - button, center, column, container, markdown, pick_list, progress_bar, - rich_text, row, scrollable, span, stack, text, text_input, + button, center, column, container, markdown, pick_list, progress_bar, rich_text, row, + scrollable, span, stack, text, text_input, }; use iced::{Center, Element, Fill, FillPortion, Font, Task, Theme}; @@ -41,9 +41,7 @@ enum State { #[derive(Debug, Clone)] enum Message { - ChangelogListed( - Result<(Changelog, Vec), changelog::Error>, - ), + ChangelogListed(Result<(Changelog, Vec), changelog::Error>), PullRequestFetched(Result), LinkClicked(markdown::Uri), TitleChanged(String), @@ -66,8 +64,7 @@ impl Generator { match message { Message::ChangelogListed(Ok((changelog, mut pending))) => { if let Some(contribution) = pending.pop() { - let preview = - markdown::parse(&changelog.to_string()).collect(); + let preview = markdown::parse(&changelog.to_string()).collect(); *self = Self::Reviewing { changelog, @@ -168,18 +165,12 @@ impl Generator { return Task::none(); }; - if let Some(entry) = - changelog::Entry::new(title, *category, pull_request) - { + if let Some(entry) = changelog::Entry::new(title, *category, pull_request) { changelog.push(entry); - let save = Task::perform( - changelog.clone().save(), - Message::ChangelogSaved, - ); + let save = Task::perform(changelog.clone().save(), Message::ChangelogSaved); - *preview = - markdown::parse(&changelog.to_string()).collect(); + *preview = markdown::parse(&changelog.to_string()).collect(); if let Some(contribution) = pending.pop() { *state = State::Loading(contribution.clone()); @@ -200,9 +191,7 @@ impl Generator { } } Message::OpenPullRequest(id) => { - let _ = webbrowser::open(&format!( - "https://github.com/iced-rs/iced/pull/{id}" - )); + let _ = webbrowser::open(&format!("https://github.com/iced-rs/iced/pull/{id}")); Task::none() } @@ -224,8 +213,7 @@ impl Generator { Self::Loading => center("Loading...").into(), Self::Done => center( column![ - text("Changelog is up-to-date! 🎉") - .shaping(text::Shaping::Advanced), + text("Changelog is up-to-date! 🎉").shaping(text::Shaping::Advanced), button("Quit").on_press(Message::Quit), ] .spacing(10) @@ -243,8 +231,7 @@ impl Generator { let total = pending.len() + changelog.len(); let percent = 100.0 * changelog.len() as f32 / total as f32; - let bar = progress_bar(0.0..=100.0, percent) - .style(progress_bar::secondary); + let bar = progress_bar(0.0..=100.0, percent).style(progress_bar::secondary); let label = text!( "{amount_reviewed} / {total} ({percent:.0}%)", @@ -257,9 +244,7 @@ impl Generator { }; let form: Element<_> = match state { - State::Loading(contribution) => { - text!("Loading #{}...", contribution.id).into() - } + State::Loading(contribution) => text!("Loading #{}...", contribution.id).into(), State::Loaded { pull_request, description, @@ -268,36 +253,27 @@ impl Generator { } => { let details = { let title = rich_text![ - span(&pull_request.title) - .size(24) - .link(pull_request.id), + span(&pull_request.title).size(24).link(pull_request.id), "\n", - span(format!(" by {}", pull_request.author)) - .font(Font { - style: font::Style::Italic, - ..Font::default() - }), + span(format!(" by {}", pull_request.author)).font(Font { + style: font::Style::Italic, + ..Font::default() + }), ] .on_link_click(Message::OpenPullRequest) .font(Font::MONOSPACE); let description = - markdown(description, self.theme()) - .map(Message::LinkClicked); - - let labels = - row(pull_request.labels.iter().map(|label| { - container( - text(label) - .size(10) - .font(Font::MONOSPACE), - ) + markdown(description, self.theme()).map(Message::LinkClicked); + + let labels = row(pull_request.labels.iter().map(|label| { + container(text(label).size(10).font(Font::MONOSPACE)) .padding(5) .style(container::rounded_box) .into() - })) - .spacing(10) - .wrap(); + })) + .spacing(10) + .wrap(); let created_at = text( timezone @@ -309,23 +285,15 @@ impl Generator { column![ title, - row![labels, created_at] - .align_y(Center) - .spacing(10), - scrollable(description) - .spacing(10) - .width(Fill) - .height(Fill) + row![labels, created_at].align_y(Center).spacing(10), + scrollable(description).spacing(10).width(Fill).height(Fill) ] .spacing(10) }; - let title = text_input( - "Type a changelog entry title...", - title, - ) - .on_input(Message::TitleChanged) - .on_submit(Message::Next); + let title = text_input("Type a changelog entry title...", title) + .on_input(Message::TitleChanged) + .on_submit(Message::Next); let category = pick_list( changelog::Category::ALL, @@ -337,32 +305,24 @@ impl Generator { .on_press(Message::Next) .style(button::success); - column![ - details, - row![title, category, next].spacing(10) - ] - .spacing(10) - .into() + column![details, row![title, category, next].spacing(10)] + .spacing(10) + .into() } }; let preview = if preview.is_empty() { center( - container( - text("The changelog is empty... so far!").size(12), - ) - .padding(10) - .style(container::rounded_box), + container(text("The changelog is empty... so far!").size(12)) + .padding(10) + .style(container::rounded_box), ) } else { container( scrollable( markdown( preview, - markdown::Settings::with_text_size( - 12, - self.theme(), - ), + markdown::Settings::with_text_size(12, self.theme()), ) .map(Message::LinkClicked), ) diff --git a/examples/checkbox/src/main.rs b/examples/checkbox/src/main.rs index 8dee153b30..6a7ee2cc9e 100644 --- a/examples/checkbox/src/main.rs +++ b/examples/checkbox/src/main.rs @@ -68,8 +68,7 @@ impl Example { shaping: text::Shaping::Basic, }); - let content = - column![default_checkbox, checkboxes, custom_checkbox].spacing(20); + let content = column![default_checkbox, checkboxes, custom_checkbox].spacing(20); center(content).into() } diff --git a/examples/clock/src/main.rs b/examples/clock/src/main.rs index a1050a764f..ef9cd5f24e 100644 --- a/examples/clock/src/main.rs +++ b/examples/clock/src/main.rs @@ -4,8 +4,8 @@ use iced::time::{self, milliseconds}; use iced::widget::canvas::{Cache, Geometry, LineCap, Path, Stroke, stroke}; use iced::widget::{canvas, container, text}; use iced::{ - Degrees, Element, Fill, Font, Point, Radians, Rectangle, Renderer, Size, - Subscription, Theme, Vector, + Degrees, Element, Fill, Font, Point, Radians, Rectangle, Renderer, Size, Subscription, Theme, + Vector, }; pub fn main() -> iced::Result { @@ -55,13 +55,11 @@ impl Clock { } fn subscription(&self) -> Subscription { - time::every(milliseconds(500)) - .map(|_| Message::Tick(chrono::offset::Local::now())) + time::every(milliseconds(500)).map(|_| Message::Tick(chrono::offset::Local::now())) } fn theme(&self) -> Theme { - Theme::ALL[(self.now.timestamp() as usize / 10) % Theme::ALL.len()] - .clone() + Theme::ALL[(self.now.timestamp() as usize / 10) % Theme::ALL.len()].clone() } } @@ -87,11 +85,9 @@ impl canvas::Program for Clock { let background = Path::circle(center, radius); frame.fill(&background, palette.secondary.strong.color); - let short_hand = - Path::line(Point::ORIGIN, Point::new(0.0, -0.5 * radius)); + let short_hand = Path::line(Point::ORIGIN, Point::new(0.0, -0.5 * radius)); - let long_hand = - Path::line(Point::ORIGIN, Point::new(0.0, -0.8 * radius)); + let long_hand = Path::line(Point::ORIGIN, Point::new(0.0, -0.8 * radius)); let width = radius / 100.0; @@ -114,11 +110,9 @@ impl canvas::Program for Clock { }; frame.translate(Vector::new(center.x, center.y)); - let minutes_portion = - Radians::from(hand_rotation(self.now.minute(), 60)) / 12.0; + let minutes_portion = Radians::from(hand_rotation(self.now.minute(), 60)) / 12.0; let hour_hand_angle = - Radians::from(hand_rotation(self.now.hour(), 12)) - + minutes_portion; + Radians::from(hand_rotation(self.now.hour(), 12)) + minutes_portion; frame.with_save(|frame| { frame.rotate(hour_hand_angle); @@ -142,10 +136,7 @@ impl canvas::Program for Clock { 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, - ), + position: Point::new((0.78 * radius) * rotate_factor, -width * 2.0), color: palette.secondary.strong.text, align_x: if rotate_factor > 0.0 { text::Alignment::Right @@ -160,8 +151,7 @@ impl canvas::Program for Clock { // Draw clock numbers for hour in 1..=12 { - let angle = Radians::from(hand_rotation(hour, 12)) - - Radians::from(Degrees(90.0)); + let angle = Radians::from(hand_rotation(hour, 12)) - Radians::from(Degrees(90.0)); let x = radius * angle.0.cos(); let y = radius * angle.0.sin(); @@ -185,10 +175,7 @@ impl canvas::Program for Clock { frame.with_save(|frame| { frame.rotate(angle); frame.fill( - &Path::rectangle( - Point::new(0.0, radius - 15.0), - Size::new(width, 7.0), - ), + &Path::rectangle(Point::new(0.0, radius - 15.0), Size::new(width, 7.0)), palette.secondary.strong.text, ); }); diff --git a/examples/color_palette/src/main.rs b/examples/color_palette/src/main.rs index e5554dee27..671f8cea06 100644 --- a/examples/color_palette/src/main.rs +++ b/examples/color_palette/src/main.rs @@ -2,10 +2,7 @@ use iced::alignment; use iced::mouse; use iced::widget::canvas::{self, Canvas, Frame, Geometry, Path}; use iced::widget::{Slider, column, row, text}; -use iced::{ - Center, Color, Element, Fill, Font, Pixels, Point, Rectangle, Renderer, - Size, Vector, -}; +use iced::{Center, Color, Element, Fill, Font, Pixels, Point, Rectangle, Renderer, Size, Vector}; use palette::{Darken, Hsl, Lighten, ShiftHue, convert::FromColor, rgb::Rgb}; use std::marker::PhantomData; use std::ops::RangeInclusive; @@ -305,8 +302,7 @@ impl ColorPicker { component: f32, update: impl Fn(f32) -> C + 'a, ) -> Slider<'a, f64, C> { - Slider::new(range, f64::from(component), move |v| update(v as f32)) - .step(0.01) + Slider::new(range, f64::from(component), move |v| update(v as f32)).step(0.01) } row![ @@ -324,8 +320,7 @@ impl ColorPicker { impl ColorSpace for Color { const LABEL: &'static str = "RGB"; - const COMPONENT_RANGES: [RangeInclusive; 3] = - [0.0..=1.0, 0.0..=1.0, 0.0..=1.0]; + const COMPONENT_RANGES: [RangeInclusive; 3] = [0.0..=1.0, 0.0..=1.0, 0.0..=1.0]; fn new(r: f32, g: f32, b: f32) -> Self { Color::from_rgb(r, g, b) @@ -347,15 +342,10 @@ impl ColorSpace for Color { impl ColorSpace for palette::Hsl { const LABEL: &'static str = "HSL"; - const COMPONENT_RANGES: [RangeInclusive; 3] = - [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; + const COMPONENT_RANGES: [RangeInclusive; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, saturation: f32, lightness: f32) -> Self { - palette::Hsl::new( - palette::RgbHue::from_degrees(hue), - saturation, - lightness, - ) + palette::Hsl::new(palette::RgbHue::from_degrees(hue), saturation, lightness) } fn components(&self) -> [f32; 3] { @@ -378,8 +368,7 @@ impl ColorSpace for palette::Hsl { impl ColorSpace for palette::Hsv { const LABEL: &'static str = "HSV"; - const COMPONENT_RANGES: [RangeInclusive; 3] = - [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; + const COMPONENT_RANGES: [RangeInclusive; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, saturation: f32, value: f32) -> Self { palette::Hsv::new(palette::RgbHue::from_degrees(hue), saturation, value) @@ -405,15 +394,10 @@ impl ColorSpace for palette::Hsv { impl ColorSpace for palette::Hwb { const LABEL: &'static str = "HWB"; - const COMPONENT_RANGES: [RangeInclusive; 3] = - [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; + const COMPONENT_RANGES: [RangeInclusive; 3] = [0.0..=360.0, 0.0..=1.0, 0.0..=1.0]; fn new(hue: f32, whiteness: f32, blackness: f32) -> Self { - palette::Hwb::new( - palette::RgbHue::from_degrees(hue), - whiteness, - blackness, - ) + palette::Hwb::new(palette::RgbHue::from_degrees(hue), whiteness, blackness) } fn components(&self) -> [f32; 3] { @@ -454,8 +438,7 @@ impl ColorSpace for palette::Lab { impl ColorSpace for palette::Lch { const LABEL: &'static str = "Lch"; - const COMPONENT_RANGES: [RangeInclusive; 3] = - [0.0..=100.0, 0.0..=128.0, 0.0..=360.0]; + const COMPONENT_RANGES: [RangeInclusive; 3] = [0.0..=100.0, 0.0..=128.0, 0.0..=360.0]; fn new(l: f32, chroma: f32, hue: f32) -> Self { palette::Lch::new(l, chroma, palette::LabHue::from_degrees(hue)) diff --git a/examples/counter/src/main.rs b/examples/counter/src/main.rs index 5027afd7e5..cfae782a5a 100644 --- a/examples/counter/src/main.rs +++ b/examples/counter/src/main.rs @@ -1,5 +1,5 @@ +use iced::widget::{button, column, text, Column}; use iced::Center; -use iced::widget::{Column, button, column, text}; pub fn main() -> iced::Result { iced::run(Counter::update, Counter::view) @@ -42,7 +42,7 @@ impl Counter { #[cfg(test)] mod tests { use super::*; - use iced_test::{Error, simulator}; + use iced_test::{simulator, Error}; #[test] fn it_counts() -> Result<(), Error> { diff --git a/examples/custom_quad/src/main.rs b/examples/custom_quad/src/main.rs index 1d02b64f81..3c9318f1f0 100644 --- a/examples/custom_quad/src/main.rs +++ b/examples/custom_quad/src/main.rs @@ -99,20 +99,16 @@ impl Example { text!("Radius: {top_left:.2}/{top_right:.2}/{bottom_right:.2}/{bottom_left:.2}"), slider(1.0..=200.0, top_left, Message::RadiusTopLeftChanged).step(0.01), slider(1.0..=200.0, top_right, Message::RadiusTopRightChanged).step(0.01), - slider(1.0..=200.0, bottom_right, Message::RadiusBottomRightChanged) - .step(0.01), - slider(1.0..=200.0, bottom_left, Message::RadiusBottomLeftChanged) - .step(0.01), - slider(0.0..=10.0, self.border_width, Message::BorderWidthChanged) - .step(0.01), + slider(1.0..=200.0, bottom_right, Message::RadiusBottomRightChanged).step(0.01), + slider(1.0..=200.0, bottom_left, Message::RadiusBottomLeftChanged).step(0.01), + slider(0.0..=10.0, self.border_width, Message::BorderWidthChanged).step(0.01), text!("Shadow: {sx:.2}x{sy:.2}, {sr:.2}"), - slider(-100.0..=100.0, sx, Message::ShadowXOffsetChanged) - .step(0.01), - slider(-100.0..=100.0, sy, Message::ShadowYOffsetChanged) - .step(0.01), - slider(0.0..=100.0, sr, Message::ShadowBlurRadiusChanged) - .step(0.01), - toggler(self.snap).label("Snap to pixel grid").on_toggle(Message::SnapToggled), + slider(-100.0..=100.0, sx, Message::ShadowXOffsetChanged).step(0.01), + slider(-100.0..=100.0, sy, Message::ShadowYOffsetChanged).step(0.01), + slider(0.0..=100.0, sr, Message::ShadowBlurRadiusChanged).step(0.01), + toggler(self.snap) + .label("Snap to pixel grid") + .on_toggle(Message::SnapToggled), ] .padding(20) .spacing(20) diff --git a/examples/custom_shader/src/scene.rs b/examples/custom_shader/src/scene.rs index d5515e497a..5b9c6d0184 100644 --- a/examples/custom_shader/src/scene.rs +++ b/examples/custom_shader/src/scene.rs @@ -176,11 +176,7 @@ fn rnd_origin() -> Vec3 { } impl shader::Pipeline for Pipeline { - fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - format: wgpu::TextureFormat, - ) -> Pipeline { + fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Pipeline { Self::new(device, queue, format) } } diff --git a/examples/custom_shader/src/scene/camera.rs b/examples/custom_shader/src/scene/camera.rs index 02192dea66..525bba1e82 100644 --- a/examples/custom_shader/src/scene/camera.rs +++ b/examples/custom_shader/src/scene/camera.rs @@ -35,12 +35,7 @@ impl Camera { pub fn build_view_proj_matrix(&self, bounds: Rectangle) -> glam::Mat4 { let aspect_ratio = bounds.width / bounds.height; let view = glam::Mat4::look_at_rh(self.eye, self.target, self.up); - let proj = glam::Mat4::perspective_rh( - self.fov_y, - aspect_ratio, - self.near, - self.far, - ); + let proj = glam::Mat4::perspective_rh(self.fov_y, aspect_ratio, self.near, self.far); OPENGL_TO_WGPU_MATRIX * proj * view } diff --git a/examples/custom_shader/src/scene/pipeline.rs b/examples/custom_shader/src/scene/pipeline.rs index 30262a5d91..edfab1407b 100644 --- a/examples/custom_shader/src/scene/pipeline.rs +++ b/examples/custom_shader/src/scene/pipeline.rs @@ -28,18 +28,13 @@ pub struct Pipeline { } impl Pipeline { - pub fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - format: wgpu::TextureFormat, - ) -> Self { + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { //vertices of one cube - let vertices = - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("cubes vertex buffer"), - contents: bytemuck::cast_slice(&cube::Raw::vertices()), - usage: wgpu::BufferUsages::VERTEX, - }); + let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("cubes vertex buffer"), + contents: bytemuck::cast_slice(&cube::Raw::vertices()), + usage: wgpu::BufferUsages::VERTEX, + }); //cube instance data let cubes_buffer = Buffer::new( @@ -69,13 +64,11 @@ impl Pipeline { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::TEXTURE_BINDING, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); - let depth_view = - depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); let normal_map_data = load_normal_map_data(); @@ -100,8 +93,7 @@ impl Pipeline { &normal_map_data, ); - let normal_view = - normal_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let normal_view = normal_texture.create_view(&wgpu::TextureViewDescriptor::default()); //skybox texture for reflection/refraction let skybox_data = load_skybox_data(); @@ -126,12 +118,11 @@ impl Pipeline { &skybox_data, ); - let sky_view = - skybox_texture.create_view(&wgpu::TextureViewDescriptor { - label: Some("cubes skybox texture view"), - dimension: Some(wgpu::TextureViewDimension::Cube), - ..Default::default() - }); + let sky_view = skybox_texture.create_view(&wgpu::TextureViewDescriptor { + label: Some("cubes skybox texture view"), + dimension: Some(wgpu::TextureViewDimension::Cube), + ..Default::default() + }); let sky_sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("cubes skybox sampler"), @@ -162,9 +153,7 @@ impl Pipeline { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: true, - }, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::Cube, multisampled: false, }, @@ -173,18 +162,14 @@ impl Pipeline { wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler( - wgpu::SamplerBindingType::Filtering, - ), + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: true, - }, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, @@ -193,96 +178,88 @@ impl Pipeline { ], }); - let uniform_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("cubes uniform bind group"), - layout: &uniform_bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: uniforms.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::TextureView(&sky_view), - }, - wgpu::BindGroupEntry { - binding: 2, - resource: wgpu::BindingResource::Sampler(&sky_sampler), - }, - wgpu::BindGroupEntry { - binding: 3, - resource: wgpu::BindingResource::TextureView( - &normal_view, - ), - }, - ], - }); + let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("cubes uniform bind group"), + layout: &uniform_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniforms.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&sky_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sky_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&normal_view), + }, + ], + }); - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("cubes pipeline layout"), - bind_group_layouts: &[&uniform_bind_group_layout], - immediate_size: 0, - }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("cubes pipeline layout"), + bind_group_layouts: &[&uniform_bind_group_layout], + immediate_size: 0, + }); - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("cubes shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - include_str!("../shaders/cubes.wgsl"), - )), - }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("cubes shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( + "../shaders/cubes.wgsl" + ))), + }); - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("cubes pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: &[Vertex::desc(), cube::Raw::desc()], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: true, - depth_compare: wgpu::CompareFunction::Less, - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState { - color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - alpha: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::One, - dst_factor: wgpu::BlendFactor::One, - operation: wgpu::BlendOperation::Max, - }, - }), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - multiview_mask: None, - cache: None, - }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("cubes pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[Vertex::desc(), cube::Raw::desc()], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: true, + depth_compare: wgpu::CompareFunction::Less, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Max, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + multiview_mask: None, + cache: None, + }); let depth_pipeline = DepthPipeline::new( device, @@ -322,8 +299,7 @@ impl Pipeline { view_formats: &[], }); - self.depth_view = - text.create_view(&wgpu::TextureViewDescriptor::default()); + self.depth_view = text.create_view(&wgpu::TextureViewDescriptor::default()); self.depth_texture_size = size; self.depth_pipeline.update(device, &text); @@ -362,34 +338,29 @@ impl Pipeline { show_depth: bool, ) { { - let mut pass = - encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("cubes.pipeline.pass"), - color_attachments: &[Some( - wgpu::RenderPassColorAttachment { - view: target, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, - }, - )], - depth_stencil_attachment: Some( - wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Clear(1.0), - store: wgpu::StoreOp::Store, - }), - stencil_ops: None, - }, - ), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("cubes.pipeline.pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); pass.set_viewport( clip_bounds.x as f32, @@ -431,32 +402,27 @@ impl DepthPipeline { ..Default::default() }); - let bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("cubes.depth_pipeline.bind_group_layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler( - wgpu::SamplerBindingType::NonFiltering, - ), - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: false, - }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("cubes.depth_pipeline.bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, }, - ], - }); + count: None, + }, + ], + }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("cubes.depth_pipeline.bind_group"), @@ -468,62 +434,55 @@ impl DepthPipeline { }, wgpu::BindGroupEntry { binding: 1, - resource: wgpu::BindingResource::TextureView( - &depth_texture, - ), + resource: wgpu::BindingResource::TextureView(&depth_texture), }, ], }); - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("cubes.depth_pipeline.layout"), - bind_group_layouts: &[&bind_group_layout], - immediate_size: 0, - }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("cubes.depth_pipeline.layout"), + bind_group_layouts: &[&bind_group_layout], + immediate_size: 0, + }); - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("cubes.depth_pipeline.shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - include_str!("../shaders/depth.wgsl"), - )), - }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("cubes.depth_pipeline.shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( + "../shaders/depth.wgsl" + ))), + }); - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("cubes.depth_pipeline.pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: &[], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: false, - depth_compare: wgpu::CompareFunction::Less, - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState::REPLACE), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - multiview_mask: None, - cache: None, - }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("cubes.depth_pipeline.pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: false, + depth_compare: wgpu::CompareFunction::Less, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::REPLACE), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + multiview_mask: None, + cache: None, + }); Self { pipeline, @@ -534,31 +493,23 @@ impl DepthPipeline { } } - pub fn update( - &mut self, - device: &wgpu::Device, - depth_texture: &wgpu::Texture, - ) { - self.depth_view = - depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); + pub fn update(&mut self, device: &wgpu::Device, depth_texture: &wgpu::Texture) { + self.depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); - self.bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("cubes.depth_pipeline.bind_group"), - layout: &self.bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Sampler(&self.sampler), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::TextureView( - &self.depth_view, - ), - }, - ], - }); + self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("cubes.depth_pipeline.bind_group"), + layout: &self.bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&self.depth_view), + }, + ], + }); } pub fn render( @@ -578,13 +529,11 @@ impl DepthPipeline { store: wgpu::StoreOp::Store, }, })], - depth_stencil_attachment: Some( - wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, - depth_ops: None, - stencil_ops: None, - }, - ), + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth_view, + depth_ops: None, + stencil_ops: None, + }), timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, @@ -615,13 +564,10 @@ fn load_skybox_data() -> Vec { let data: [&[u8]; 6] = [pos_x, neg_x, pos_y, neg_y, pos_z, neg_z]; data.iter().fold(vec![], |mut acc, bytes| { - let i = image::load_from_memory_with_format( - bytes, - image::ImageFormat::Jpeg, - ) - .unwrap() - .to_rgba8() - .into_raw(); + let i = image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg) + .unwrap() + .to_rgba8() + .into_raw(); acc.extend(i); acc diff --git a/examples/custom_shader/src/scene/pipeline/cube.rs b/examples/custom_shader/src/scene/pipeline/cube.rs index 5f6eb9c5ce..1e3ed15e8a 100644 --- a/examples/custom_shader/src/scene/pipeline/cube.rs +++ b/examples/custom_shader/src/scene/pipeline/cube.rs @@ -46,10 +46,8 @@ impl Cube { } pub fn update(&mut self, size: f32, time: f32) { - self.rotation = glam::Quat::from_axis_angle( - self.rotation_axis, - time / 2.0 * self.rotation_dir, - ); + self.rotation = + glam::Quat::from_axis_angle(self.rotation_axis, time / 2.0 * self.rotation_dir); self.size = size; } } diff --git a/examples/custom_widget/src/main.rs b/examples/custom_widget/src/main.rs index 8fe571fb4f..db2ceb74b4 100644 --- a/examples/custom_widget/src/main.rs +++ b/examples/custom_widget/src/main.rs @@ -62,8 +62,7 @@ mod circle { } } - impl From - for Element<'_, Message, Theme, Renderer> + impl From for Element<'_, Message, Theme, Renderer> where Renderer: renderer::Renderer, { diff --git a/examples/delineate/src/main.rs b/examples/delineate/src/main.rs index d4bc8a9a6f..f42b9b093e 100644 --- a/examples/delineate/src/main.rs +++ b/examples/delineate/src/main.rs @@ -1,13 +1,8 @@ use iced::event::{self, Event}; use iced::mouse; -use iced::widget::{ - self, column, container, row, scrollable, selector, space, text, -}; +use iced::widget::{self, column, container, row, scrollable, selector, space, text}; use iced::window; -use iced::{ - Center, Color, Element, Fill, Font, Point, Rectangle, Subscription, Task, - Theme, -}; +use iced::{Center, Color, Element, Fill, Font, Point, Rectangle, Subscription, Task, Theme}; pub fn main() -> iced::Result { iced::application(Example::default, Example::update, Example::view) @@ -45,14 +40,12 @@ impl Example { selector::find(INNER_CONTAINER).map(Message::InnerFound), ]), Message::OuterFound(outer) => { - self.outer_bounds = - outer.as_ref().and_then(selector::Target::visible_bounds); + self.outer_bounds = outer.as_ref().and_then(selector::Target::visible_bounds); Task::none() } Message::InnerFound(inner) => { - self.inner_bounds = - inner.as_ref().and_then(selector::Target::visible_bounds); + self.inner_bounds = inner.as_ref().and_then(selector::Target::visible_bounds); Task::none() } @@ -82,9 +75,7 @@ impl Example { }, if bounds .zip(self.mouse_position) - .map(|(bounds, mouse_position)| { - bounds.contains(mouse_position) - }) + .map(|(bounds, mouse_position)| bounds.contains(mouse_position)) .unwrap_or_default() { Some(Color { @@ -149,9 +140,7 @@ impl Example { Event::Mouse(mouse::Event::CursorMoved { position }) => { Some(Message::MouseMoved(position)) } - Event::Window(window::Event::Resized { .. }) => { - Some(Message::WindowResized) - } + Event::Window(window::Event::Resized { .. }) => Some(Message::WindowResized), _ => None, }) } diff --git a/examples/download_progress/src/main.rs b/examples/download_progress/src/main.rs index 53ee282324..f9ffcb5da3 100644 --- a/examples/download_progress/src/main.rs +++ b/examples/download_progress/src/main.rs @@ -50,8 +50,7 @@ impl Example { task.map(Message::DownloadUpdated.with(index)) } Message::DownloadUpdated(id, update) => { - if let Some(download) = - self.downloads.iter_mut().find(|download| download.id == id) + if let Some(download) = self.downloads.iter_mut().find(|download| download.id == id) { download.update(update); } @@ -62,15 +61,14 @@ impl Example { } fn view(&self) -> Element<'_, Message> { - let downloads = - Column::with_children(self.downloads.iter().map(Download::view)) - .push( - button("Add another download") - .on_press(Message::Add) - .padding(10), - ) - .spacing(20) - .align_x(Right); + let downloads = Column::with_children(self.downloads.iter().map(Download::view)) + .push( + button("Add another download") + .on_press(Message::Add) + .padding(10), + ) + .spacing(20) + .align_x(Right); center(downloads).padding(20).into() } @@ -166,15 +164,11 @@ impl Download { State::Idle => button("Start the download!") .on_press(Message::Download(self.id)) .into(), - State::Finished => { - column!["Download finished!", button("Start again")] - .spacing(10) - .align_x(Center) - .into() - } - State::Downloading { .. } => { - text!("Downloading... {current_progress:.2}%").into() - } + State::Finished => column!["Download finished!", button("Start again")] + .spacing(10) + .align_x(Center) + .into(), + State::Downloading { .. } => text!("Downloading... {current_progress:.2}%").into(), State::Errored => column![ "Something went wrong :(", button("Try again").on_press(Message::Download(self.id)), diff --git a/examples/editor/src/main.rs b/examples/editor/src/main.rs index 3bb657f531..38aa305a14 100644 --- a/examples/editor/src/main.rs +++ b/examples/editor/src/main.rs @@ -1,8 +1,8 @@ use iced::highlighter; use iced::keyboard; use iced::widget::{ - button, center_x, column, container, operation, pick_list, row, space, - text, text_editor, toggler, tooltip, + button, center_x, column, container, operation, pick_list, row, space, text, text_editor, + toggler, tooltip, }; use iced::window; use iced::{Center, Element, Fill, Font, Task, Theme, Window}; @@ -54,10 +54,7 @@ impl Editor { }, Task::batch([ Task::perform( - load_file(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/main.rs", - )), + load_file(concat!(env!("CARGO_MANIFEST_DIR"), "/src/main.rs",)), Message::FileOpened, ), operation::focus(EDITOR), @@ -129,10 +126,7 @@ impl Editor { text.push_str(ending.as_str()); } - Task::perform( - save_file(self.file.clone(), text), - Message::FileSaved, - ) + Task::perform(save_file(self.file.clone(), text), Message::FileSaved) } } Message::FileSaved(result) => { @@ -222,12 +216,8 @@ impl Editor { ) .key_binding(|key_press| { match key_press.key.as_ref() { - keyboard::Key::Character("s") - if key_press.modifiers.command() => - { - Some(text_editor::Binding::Custom( - Message::SaveFile, - )) + keyboard::Key::Character("s") if key_press.modifiers.command() => { + Some(text_editor::Binding::Custom(Message::SaveFile)) } _ => text_editor::Binding::from_key_press(key_press), } @@ -262,16 +252,13 @@ fn open_file( .set_parent(&window); async move { - let picked_file = - dialog.pick_file().await.ok_or(Error::DialogClosed)?; + let picked_file = dialog.pick_file().await.ok_or(Error::DialogClosed)?; load_file(picked_file).await } } -async fn load_file( - path: impl Into, -) -> Result<(PathBuf, Arc), Error> { +async fn load_file(path: impl Into) -> Result<(PathBuf, Arc), Error> { let path = path.into(); let contents = tokio::fs::read_to_string(&path) @@ -282,10 +269,7 @@ async fn load_file( Ok((path, contents)) } -async fn save_file( - path: Option, - contents: String, -) -> Result { +async fn save_file(path: Option, contents: String) -> Result { let path = if let Some(path) = path { path } else { diff --git a/examples/ferris/src/main.rs b/examples/ferris/src/main.rs index f706ce01b8..769b9c3d7c 100644 --- a/examples/ferris/src/main.rs +++ b/examples/ferris/src/main.rs @@ -1,11 +1,9 @@ use iced::time::Instant; -use iced::widget::{ - center, checkbox, column, container, image, pick_list, row, slider, text, -}; +use iced::widget::{center, checkbox, column, container, image, pick_list, row, slider, text}; use iced::window; use iced::{ - Bottom, Center, Color, ContentFit, Degrees, Element, Fill, Radians, - Rotation, Subscription, Theme, + Bottom, Center, Color, ContentFit, Degrees, Element, Fill, Radians, Rotation, Subscription, + Theme, }; pub fn main() -> iced::Result { @@ -46,19 +44,13 @@ impl Image { } Message::RotationStrategyChanged(strategy) => { self.rotation = match strategy { - RotationStrategy::Floating => { - Rotation::Floating(self.rotation.radians()) - } - RotationStrategy::Solid => { - Rotation::Solid(self.rotation.radians()) - } + 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::Floating(_) => Rotation::Floating(rotation.into()), Rotation::Solid(_) => Rotation::Solid(rotation.into()), }; } @@ -74,9 +66,8 @@ impl Image { 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.rotation.radians_mut() = + (self.rotation.radians() + ROTATION_SPEED * delta) % (2.0 * Radians::PI); self.last_tick = now; } @@ -142,8 +133,7 @@ impl Image { format!("Width: {}px", self.width) ), with_value( - slider(0.0..=1.0, self.opacity, Message::OpacityChanged) - .step(0.01), + slider(0.0..=1.0, self.opacity, Message::OpacityChanged).step(0.01), format!("Opacity: {:.2}", self.opacity) ), with_value( @@ -201,10 +191,7 @@ impl std::fmt::Display for RotationStrategy { } } -fn with_value<'a>( - control: impl Into>, - value: String, -) -> Element<'a, Message> { +fn with_value<'a>(control: impl Into>, value: String) -> Element<'a, Message> { column![control.into(), text(value).size(12).line_height(1.0)] .spacing(2) .align_x(Center) diff --git a/examples/gallery/src/civitai.rs b/examples/gallery/src/civitai.rs index f7475525c9..dc041e5799 100644 --- a/examples/gallery/src/civitai.rs +++ b/examples/gallery/src/civitai.rs @@ -45,11 +45,7 @@ impl Image { .collect()) } - pub async fn blurhash( - self, - width: u32, - height: u32, - ) -> Result { + pub async fn blurhash(self, width: u32, height: u32) -> Result { task::spawn_blocking(move || { let pixels = blurhash::decode(&self.hash, width, height, 1.0)?; @@ -83,9 +79,7 @@ impl Image { .url .split("/") .map(|part| { - if part.starts_with("width=") - || part.starts_with("original=") - { + if part.starts_with("width=") || part.starts_with("original=") { format!("width={}", width * 2) // High DPI } else { part.to_owned() @@ -105,9 +99,7 @@ impl Image { } } -#[derive( - Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, -)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] pub struct Id(u32); #[derive(Debug, Clone)] diff --git a/examples/gallery/src/main.rs b/examples/gallery/src/main.rs index 198cdc27ab..d03ad66fb2 100644 --- a/examples/gallery/src/main.rs +++ b/examples/gallery/src/main.rs @@ -10,13 +10,11 @@ use iced::animation; use iced::border; use iced::time::{Instant, milliseconds}; use iced::widget::{ - button, container, float, grid, image, mouse_area, opaque, scrollable, - sensor, space, stack, + button, container, float, grid, image, mouse_area, opaque, scrollable, sensor, space, stack, }; use iced::window; use iced::{ - Animation, Color, ContentFit, Element, Fill, Function, Shadow, - Subscription, Task, Theme, color, + Animation, Color, ContentFit, Element, Fill, Function, Shadow, Subscription, Task, Theme, color, }; use std::collections::{HashMap, HashSet}; @@ -180,9 +178,7 @@ impl Gallery { return Task::none(); } - let Some(Preview::Ready { thumbnail, .. }) = - self.previews.get_mut(&id) - else { + let Some(Preview::Ready { thumbnail, .. }) = self.previews.get_mut(&id) else { return Task::none(); }; @@ -275,9 +271,7 @@ impl Gallery { .height(grid::aspect_ratio(Preview::WIDTH, Preview::HEIGHT)) .spacing(10); - let content = - container(scrollable(gallery).spacing(10).auto_scroll(true)) - .padding(10); + let content = container(scrollable(gallery).spacing(10).auto_scroll(true)).padding(10); let viewer = self.viewer.view(self.now); stack![content, viewer].into() @@ -290,36 +284,33 @@ fn card<'a>( now: Instant, ) -> Element<'a, Message> { let image = if let Some(preview) = preview { - let thumbnail: Element<'_, _> = - if let Preview::Ready { thumbnail, .. } = &preview - && let Some(allocation) = &thumbnail.allocation - { - float( - image(allocation.handle()) - .width(Fill) - .content_fit(ContentFit::Cover) - .opacity(thumbnail.fade_in.interpolate(0.0, 1.0, now)) - .border_radius(BORDER_RADIUS), - ) - .scale(thumbnail.zoom.interpolate(1.0, 1.1, now)) - .translate(move |bounds, viewport| { - bounds.zoom(1.1).offset(&viewport.shrink(10)) - * thumbnail.zoom.interpolate(0.0, 1.0, now) - }) - .style(move |_theme| float::Style { - shadow: Shadow { - color: Color::BLACK.scale_alpha( - thumbnail.zoom.interpolate(0.0, 1.0, now), - ), - blur_radius: thumbnail.zoom.interpolate(0.0, 20.0, now), - ..Shadow::default() - }, - shadow_border_radius: border::radius(BORDER_RADIUS), - }) - .into() - } else { - space::horizontal().into() - }; + let thumbnail: Element<'_, _> = if let Preview::Ready { thumbnail, .. } = &preview + && let Some(allocation) = &thumbnail.allocation + { + float( + image(allocation.handle()) + .width(Fill) + .content_fit(ContentFit::Cover) + .opacity(thumbnail.fade_in.interpolate(0.0, 1.0, now)) + .border_radius(BORDER_RADIUS), + ) + .scale(thumbnail.zoom.interpolate(1.0, 1.1, now)) + .translate(move |bounds, viewport| { + bounds.zoom(1.1).offset(&viewport.shrink(10)) + * thumbnail.zoom.interpolate(0.0, 1.0, now) + }) + .style(move |_theme| float::Style { + shadow: Shadow { + color: Color::BLACK.scale_alpha(thumbnail.zoom.interpolate(0.0, 1.0, now)), + blur_radius: thumbnail.zoom.interpolate(0.0, 20.0, now), + ..Shadow::default() + }, + shadow_border_radius: border::radius(BORDER_RADIUS), + }) + .into() + } else { + space::horizontal().into() + }; if let Some(blurhash) = preview.blurhash(now) { let blurhash = image(&blurhash.handle) @@ -407,11 +398,7 @@ impl Preview { .duration(milliseconds(700)) .easing(animation::Easing::EaseIn) .go(true, now), - handle: image::Handle::from_rgba( - rgba.width, - rgba.height, - rgba.pixels, - ), + handle: image::Handle::from_rgba(rgba.width, rgba.height, rgba.pixels), }, } } @@ -449,9 +436,9 @@ impl Preview { } => { thumbnail.fade_in.is_animating(now) || thumbnail.zoom.is_animating(now) - || blurhash.as_ref().is_some_and(|blurhash| { - blurhash.fade_in.is_animating(now) - }) + || blurhash + .as_ref() + .is_some_and(|blurhash| blurhash.fade_in.is_animating(now)) } } } @@ -463,9 +450,7 @@ impl Preview { blurhash: Some(blurhash), thumbnail, .. - } if !thumbnail.fade_in.value() - || thumbnail.fade_in.is_animating(now) => - { + } if !thumbnail.fade_in.value() || thumbnail.fade_in.is_animating(now) => { Some(blurhash) } Self::Ready { .. } => None, @@ -536,8 +521,7 @@ impl Viewer { } fn is_animating(&self, now: Instant) -> bool { - self.background_fade_in.is_animating(now) - || self.image_fade_in.is_animating(now) + self.background_fade_in.is_animating(now) || self.image_fade_in.is_animating(now) } fn view(&self, now: Instant) -> Option> { @@ -560,8 +544,7 @@ impl Viewer { container(image) .center(Fill) .style(move |_theme| { - container::Style::default() - .background(color!(0x000000, opacity)) + container::Style::default().background(color!(0x000000, opacity)) }) .padding(20), ) @@ -572,19 +555,13 @@ impl Viewer { fn to_rgba(bytes: Bytes) -> Task { Task::future(async move { - tokio::task::spawn_blocking(move || { - match ::image::load_from_memory(bytes.as_slice()) { - Ok(image) => { - let rgba = image.to_rgba8(); - - image::Handle::from_rgba( - rgba.width(), - rgba.height(), - rgba.into_raw(), - ) - } - _ => image::Handle::from_bytes(bytes), + tokio::task::spawn_blocking(move || match ::image::load_from_memory(bytes.as_slice()) { + Ok(image) => { + let rgba = image.to_rgba8(); + + image::Handle::from_rgba(rgba.width(), rgba.height(), rgba.into_raw()) } + _ => image::Handle::from_bytes(bytes), }) .await .unwrap() diff --git a/examples/game_of_life/src/main.rs b/examples/game_of_life/src/main.rs index 2cec8fe0fa..a835cef0ba 100644 --- a/examples/game_of_life/src/main.rs +++ b/examples/game_of_life/src/main.rs @@ -6,9 +6,7 @@ use grid::Grid; use preset::Preset; use iced::time::{self, milliseconds}; -use iced::widget::{ - button, checkbox, column, container, pick_list, row, slider, text, -}; +use iced::widget::{button, checkbox, column, container, pick_list, row, slider, text}; use iced::{Center, Element, Fill, Function, Subscription, Task, Theme}; pub fn main() -> iced::Result { @@ -104,8 +102,7 @@ impl GameOfLife { fn subscription(&self) -> Subscription { if self.is_playing { - time::every(milliseconds(1000 / self.speed as u64)) - .map(|_| Message::Tick) + time::every(milliseconds(1000 / self.speed as u64)).map(|_| Message::Tick) } else { Subscription::none() } @@ -121,11 +118,8 @@ impl GameOfLife { self.grid.preset(), ); - let content = column![ - self.grid.view().map(Message::Grid.with(version)), - controls, - ] - .height(Fill); + let content = + column![self.grid.view().map(Message::Grid.with(version)), controls,].height(Fill); container(content).width(Fill).height(Fill).into() } @@ -144,8 +138,7 @@ fn view_controls<'a>( preset: Preset, ) -> Element<'a, Message> { let playback_controls = row![ - button(if is_playing { "Pause" } else { "Play" }) - .on_press(Message::TogglePlayback), + button(if is_playing { "Pause" } else { "Play" }).on_press(Message::TogglePlayback), button("Next") .on_press(Message::Next) .style(button::secondary), @@ -186,13 +179,9 @@ mod grid { use iced::time::{Duration, Instant}; use iced::touch; use iced::widget::canvas; - use iced::widget::canvas::{ - Cache, Canvas, Event, Frame, Geometry, Path, Text, - }; + use iced::widget::canvas::{Cache, Canvas, Event, Frame, Geometry, Path, Text}; use iced::widget::text; - use iced::{ - Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme, Vector, - }; + use iced::{Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme, Vector}; use rustc_hash::{FxHashMap, FxHashSet}; use std::ops::RangeInclusive; @@ -255,10 +244,7 @@ mod grid { } } - pub fn tick( - &mut self, - amount: usize, - ) -> Option + use<>> { + pub fn tick(&mut self, amount: usize) -> Option + use<>> { let tick = self.state.tick(amount)?; self.last_queued_ticks = amount; @@ -447,9 +433,7 @@ mod grid { Interaction::Erasing => unpopulate, Interaction::Panning { translation, start } => { Some(Message::Translated( - translation - + (cursor_position - start) - * (1.0 / self.scaling), + translation + (cursor_position - start) * (1.0 / self.scaling), )) } Interaction::None => None, @@ -473,38 +457,29 @@ mod grid { let old_scaling = self.scaling; let scaling = (self.scaling * (1.0 + y / 30.0)) - .clamp( - Self::MIN_SCALING, - Self::MAX_SCALING, - ); - - let translation = - if let Some(cursor_to_center) = - cursor.position_from(bounds.center()) - { - let factor = scaling - old_scaling; - - Some( - self.translation - - Vector::new( - cursor_to_center.x * factor - / (old_scaling - * old_scaling), - cursor_to_center.y * factor - / (old_scaling - * old_scaling), - ), - ) - } else { - None - }; + .clamp(Self::MIN_SCALING, Self::MAX_SCALING); + + let translation = if let Some(cursor_to_center) = + cursor.position_from(bounds.center()) + { + let factor = scaling - old_scaling; + + Some( + self.translation + - Vector::new( + cursor_to_center.x * factor + / (old_scaling * old_scaling), + cursor_to_center.y * factor + / (old_scaling * old_scaling), + ), + ) + } else { + None + }; Some( - canvas::Action::publish(Message::Scaled( - scaling, - translation, - )) - .and_capture(), + canvas::Action::publish(Message::Scaled(scaling, translation)) + .and_capture(), ) } else { Some(canvas::Action::capture()) @@ -552,9 +527,9 @@ mod grid { let overlay = { let mut frame = Frame::new(renderer, bounds.size()); - let hovered_cell = cursor.position_in(bounds).map(|position| { - Cell::at(self.project(position, frame.size())) - }); + let hovered_cell = cursor + .position_in(bounds) + .map(|position| Cell::at(self.project(position, frame.size()))); if let Some(cell) = hovered_cell { frame.with_save(|frame| { @@ -607,40 +582,38 @@ mod grid { }; if self.scaling >= 0.2 && self.show_lines { - let grid = - self.grid_cache.draw(renderer, bounds.size(), |frame| { - frame.translate(center); - frame.scale(self.scaling); - frame.translate(self.translation); - frame.scale(Cell::SIZE); + let grid = self.grid_cache.draw(renderer, bounds.size(), |frame| { + frame.translate(center); + frame.scale(self.scaling); + frame.translate(self.translation); + frame.scale(Cell::SIZE); - let region = self.visible_region(frame.size()); - let rows = region.rows(); - let columns = region.columns(); - let (total_rows, total_columns) = - (rows.clone().count(), columns.clone().count()); - let width = 2.0 / Cell::SIZE as f32; - let color = Color::from_rgb8(70, 74, 83); - - frame - .translate(Vector::new(-width / 2.0, -width / 2.0)); - - for row in region.rows() { - frame.fill_rectangle( - Point::new(*columns.start() as f32, row as f32), - Size::new(total_columns as f32, width), - color, - ); - } + let region = self.visible_region(frame.size()); + let rows = region.rows(); + let columns = region.columns(); + let (total_rows, total_columns) = + (rows.clone().count(), columns.clone().count()); + let width = 2.0 / Cell::SIZE as f32; + let color = Color::from_rgb8(70, 74, 83); - for column in region.columns() { - frame.fill_rectangle( - Point::new(column as f32, *rows.start() as f32), - Size::new(width, total_rows as f32), - color, - ); - } - }); + frame.translate(Vector::new(-width / 2.0, -width / 2.0)); + + for row in region.rows() { + frame.fill_rectangle( + Point::new(*columns.start() as f32, row as f32), + Size::new(total_columns as f32, width), + color, + ); + } + + for column in region.columns() { + frame.fill_rectangle( + Point::new(column as f32, *rows.start() as f32), + Size::new(width, total_rows as f32), + color, + ); + } + }); vec![life, grid, overlay] } else { @@ -658,9 +631,7 @@ mod grid { Interaction::Drawing => mouse::Interaction::Crosshair, Interaction::Erasing => mouse::Interaction::Crosshair, Interaction::Panning { .. } => mouse::Interaction::Grabbing, - Interaction::None if cursor.is_over(bounds) => { - mouse::Interaction::Crosshair - } + Interaction::None if cursor.is_over(bounds) => mouse::Interaction::Crosshair, Interaction::None => mouse::Interaction::default(), } } @@ -719,8 +690,7 @@ mod grid { fn tick( &mut self, amount: usize, - ) -> Option> + use<>> - { + ) -> Option> + use<>> { if self.is_ticking { return None; } @@ -856,8 +826,7 @@ mod grid { fn rows(&self) -> RangeInclusive { let first_row = (self.y / Cell::SIZE as f32).floor() as isize; - let visible_rows = - (self.height / Cell::SIZE as f32).ceil() as isize; + let visible_rows = (self.height / Cell::SIZE as f32).ceil() as isize; first_row..=first_row + visible_rows } @@ -865,8 +834,7 @@ mod grid { fn columns(&self) -> RangeInclusive { let first_column = (self.x / Cell::SIZE as f32).floor() as isize; - let visible_columns = - (self.width / Cell::SIZE as f32).ceil() as isize; + let visible_columns = (self.width / Cell::SIZE as f32).ceil() as isize; first_column..=first_column + visible_columns } @@ -878,9 +846,7 @@ mod grid { let rows = self.rows(); let columns = self.columns(); - cells.filter(move |cell| { - rows.contains(&cell.i) && columns.contains(&cell.j) - }) + cells.filter(move |cell| rows.contains(&cell.i) && columns.contains(&cell.j)) } } diff --git a/examples/game_of_life/src/preset.rs b/examples/game_of_life/src/preset.rs index 552527b193..3655d14bd3 100644 --- a/examples/game_of_life/src/preset.rs +++ b/examples/game_of_life/src/preset.rs @@ -107,9 +107,7 @@ impl Preset { .chars() .enumerate() .filter(|(_, c)| !c.is_whitespace()) - .map(move |(j, _)| { - (start_row + i as isize, start_column + j as isize) - }) + .map(move |(j, _)| (start_row + i as isize, start_column + j as isize)) }) .collect() } diff --git a/examples/geometry/src/main.rs b/examples/geometry/src/main.rs index 8c2351ac77..d283c2be19 100644 --- a/examples/geometry/src/main.rs +++ b/examples/geometry/src/main.rs @@ -7,10 +7,7 @@ mod rainbow { use iced::advanced::widget::{self, Widget}; use iced::advanced::{Clipboard, Shell}; use iced::mouse; - use iced::{ - Element, Event, Length, Rectangle, Renderer, Size, Theme, - Transformation, Vector, - }; + use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Transformation, Vector}; #[derive(Debug, Clone, Copy, Default)] pub struct Rainbow; @@ -65,9 +62,7 @@ mod rainbow { _viewport: &Rectangle, ) { use iced::advanced::Renderer as _; - use iced::advanced::graphics::mesh::{ - self, Mesh, Renderer as _, SolidVertex2D, - }; + use iced::advanced::graphics::mesh::{self, Mesh, Renderer as _, SolidVertex2D}; let bounds = layout.bounds(); @@ -153,12 +148,9 @@ mod rainbow { clip_bounds: Rectangle::INFINITE, }; - renderer.with_translation( - Vector::new(bounds.x, bounds.y), - |renderer| { - renderer.draw_mesh(mesh); - }, - ); + renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { + renderer.draw_mesh(mesh); + }); } } diff --git a/examples/gradient/src/main.rs b/examples/gradient/src/main.rs index 187e1204d5..23dba3b386 100644 --- a/examples/gradient/src/main.rs +++ b/examples/gradient/src/main.rs @@ -70,8 +70,7 @@ impl Gradient { let angle_picker = row![ text("Angle").width(64), - slider(Radians::RANGE, self.angle, Message::AngleChanged) - .step(0.01) + slider(Radians::RANGE, self.angle, Message::AngleChanged).step(0.01) ] .spacing(8) .padding(8) @@ -115,14 +114,10 @@ impl Default for Gradient { fn color_picker(label: &str, color: Color) -> Element<'_, Color> { row![ text(label).width(64), - slider(0.0..=1.0, color.r, move |r| { Color { r, ..color } }) - .step(0.01), - slider(0.0..=1.0, color.g, move |g| { Color { g, ..color } }) - .step(0.01), - slider(0.0..=1.0, color.b, move |b| { Color { b, ..color } }) - .step(0.01), - slider(0.0..=1.0, color.a, move |a| { Color { a, ..color } }) - .step(0.01), + slider(0.0..=1.0, color.r, move |r| { Color { r, ..color } }).step(0.01), + slider(0.0..=1.0, color.g, move |g| { Color { g, ..color } }).step(0.01), + slider(0.0..=1.0, color.b, move |b| { Color { b, ..color } }).step(0.01), + slider(0.0..=1.0, color.a, move |a| { Color { a, ..color } }).step(0.01), ] .spacing(8) .padding(8) diff --git a/examples/layout/src/main.rs b/examples/layout/src/main.rs index 07791796cc..c670e10397 100644 --- a/examples/layout/src/main.rs +++ b/examples/layout/src/main.rs @@ -2,12 +2,12 @@ use iced::border; use iced::keyboard; use iced::mouse; use iced::widget::{ - button, canvas, center, center_y, checkbox, column, container, pick_list, - pin, responsive, row, rule, scrollable, space, stack, text, + button, canvas, center, center_y, checkbox, column, container, pick_list, pin, responsive, row, + rule, scrollable, space, stack, text, }; use iced::{ - Center, Element, Fill, Font, Length, Point, Rectangle, Renderer, Shrink, - Subscription, Theme, color, + Center, Element, Fill, Font, Length, Point, Rectangle, Renderer, Shrink, Subscription, Theme, + color, }; pub fn main() -> iced::Result { @@ -69,12 +69,8 @@ impl Layout { }; match modified_key { - keyboard::Key::Named(key::Named::ArrowLeft) => { - Some(Message::Previous) - } - keyboard::Key::Named(key::Named::ArrowRight) => { - Some(Message::Next) - } + keyboard::Key::Named(key::Named::ArrowLeft) => Some(Message::Previous), + keyboard::Key::Named(key::Named::ArrowRight) => Some(Message::Next), _ => None, } }) @@ -87,8 +83,7 @@ impl Layout { checkbox(self.explain) .label("Explain") .on_toggle(Message::ExplainToggled), - pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeSelected) - .placeholder("Theme"), + pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeSelected).placeholder("Theme"), ] .spacing(20) .align_y(Center); @@ -182,9 +177,7 @@ impl Example { } fn previous(self) -> Self { - let Some(index) = - Self::LIST.iter().position(|&example| example == self) - else { + let Some(index) = Self::LIST.iter().position(|&example| example == self) else { return self; }; @@ -195,9 +188,7 @@ impl Example { } fn next(self) -> Self { - let Some(index) = - Self::LIST.iter().position(|&example| example == self) - else { + let Some(index) = Self::LIST.iter().position(|&example| example == self) else { return self; }; @@ -270,8 +261,7 @@ fn application<'a>() -> Element<'a, Message> { .style(|theme| { let palette = theme.extended_palette(); - container::Style::default() - .border(border::color(palette.background.strong.color).width(1)) + container::Style::default().border(border::color(palette.background.strong.color).width(1)) }); let sidebar = center_y( @@ -305,9 +295,7 @@ fn application<'a>() -> Element<'a, Message> { } fn quotes<'a>() -> Element<'a, Message> { - fn quote<'a>( - content: impl Into>, - ) -> Element<'a, Message> { + fn quote<'a>(content: impl Into>) -> Element<'a, Message> { row![rule::vertical(1), content.into()] .spacing(10) .height(Shrink) @@ -369,8 +357,7 @@ fn responsive_<'a>() -> Element<'a, Message> { let size = size.ratio(16.0 / 9.0); container(center( - text!("{:.0}x{:.0}px (16:9)", size.width, size.height) - .font(Font::MONOSPACE), + text!("{:.0}x{:.0}px (16:9)", size.width, size.height).font(Font::MONOSPACE), )) .clip(true) .width(size.width) diff --git a/examples/lazy/src/main.rs b/examples/lazy/src/main.rs index 6a48b655ea..bc933b3f4f 100644 --- a/examples/lazy/src/main.rs +++ b/examples/lazy/src/main.rs @@ -1,6 +1,4 @@ -use iced::widget::{ - button, column, lazy, pick_list, row, scrollable, space, text, text_input, -}; +use iced::widget::{button, column, lazy, pick_list, row, scrollable, space, text, text_input}; use iced::{Element, Fill}; use std::collections::HashSet; @@ -158,12 +156,8 @@ impl App { let mut items: Vec<_> = self.items.iter().cloned().collect(); items.sort_by(|a, b| match self.order { - Order::Ascending => { - a.name.to_lowercase().cmp(&b.name.to_lowercase()) - } - Order::Descending => { - b.name.to_lowercase().cmp(&a.name.to_lowercase()) - } + Order::Ascending => a.name.to_lowercase().cmp(&b.name.to_lowercase()), + Order::Descending => b.name.to_lowercase().cmp(&a.name.to_lowercase()), }); column(items.into_iter().map(|item| { @@ -191,8 +185,7 @@ impl App { text_input("Add a new option", &self.input) .on_input(Message::InputChanged) .on_submit(Message::AddItem(self.input.clone())), - button(text!("Toggle Order ({})", self.order)) - .on_press(Message::ToggleOrder) + button(text!("Toggle Order ({})", self.order)).on_press(Message::ToggleOrder) ] .spacing(10) ] diff --git a/examples/list/src/main.rs b/examples/list/src/main.rs index 5f60f5c54f..da4f29b86d 100644 --- a/examples/list/src/main.rs +++ b/examples/list/src/main.rs @@ -1,6 +1,5 @@ use iced::widget::{ - button, center, column, container, list, row, scrollable, - space::horizontal, text, + button, center, column, container, list, row, scrollable, space::horizontal, text, }; use iced::{Alignment, Element, Length, Task, Theme}; @@ -55,8 +54,7 @@ impl List { container(list(&self.content, |index, (id, state)| { row![ match state { - State::Idle => - Element::from(text(format!("I am item {id}!"))), + State::Idle => Element::from(text(format!("I am item {id}!"))), State::Updated => center( column![ text(format!("I am item {id}!")), @@ -69,8 +67,7 @@ impl List { }, horizontal(), button("Update").on_press_maybe( - matches!(state, State::Idle) - .then_some(Message::Update(index)) + matches!(state, State::Idle).then_some(Message::Update(index)) ), button("Remove") .on_press(Message::Remove(index)) @@ -93,9 +90,7 @@ impl List { impl Default for List { fn default() -> Self { Self { - content: list::Content::from_iter( - (0..1_000).map(|id| (id, State::Idle)), - ), + content: list::Content::from_iter((0..1_000).map(|id| (id, State::Idle))), } } } diff --git a/examples/loading_spinners/src/circular.rs b/examples/loading_spinners/src/circular.rs index a05d4e0abb..db5367ab7a 100644 --- a/examples/loading_spinners/src/circular.rs +++ b/examples/loading_spinners/src/circular.rs @@ -7,10 +7,7 @@ use iced::mouse; use iced::time::Instant; use iced::widget::canvas; use iced::window; -use iced::{ - Background, Color, Element, Event, Length, Radians, Rectangle, Renderer, - Size, Vector, -}; +use iced::{Background, Color, Element, Event, Length, Radians, Rectangle, Renderer, Size, Vector}; use super::easing::{self, Easing}; @@ -135,12 +132,9 @@ impl Animation { Self::Contracting { rotation, .. } => Self::Expanding { start: now, progress: 0.0, - rotation: rotation.wrapping_add( - BASE_ROTATION_SPEED.wrapping_add( - (f64::from(WRAP_ANGLE / (2.0 * Radians::PI)) - * u32::MAX as f64) as u32, - ), - ), + rotation: rotation.wrapping_add(BASE_ROTATION_SPEED.wrapping_add( + (f64::from(WRAP_ANGLE / (2.0 * Radians::PI)) * u32::MAX as f64) as u32, + )), last: now, }, } @@ -148,17 +142,13 @@ impl Animation { fn start(&self) -> Instant { match self { - Self::Expanding { start, .. } | Self::Contracting { start, .. } => { - *start - } + Self::Expanding { start, .. } | Self::Contracting { start, .. } => *start, } } fn last(&self) -> Instant { match self { - Self::Expanding { last, .. } | Self::Contracting { last, .. } => { - *last - } + Self::Expanding { last, .. } | Self::Contracting { last, .. } => *last, } } @@ -174,15 +164,8 @@ impl Animation { * (u32::MAX) as f32) as u32; match elapsed { - elapsed if elapsed > cycle_duration => { - self.next(additional_rotation, now) - } - _ => self.with_elapsed( - cycle_duration, - additional_rotation, - elapsed, - now, - ), + elapsed if elapsed > cycle_duration => self.next(additional_rotation, now), + _ => self.with_elapsed(cycle_duration, additional_rotation, elapsed, now), } } @@ -216,8 +199,7 @@ impl Animation { fn rotation(&self) -> f32 { match self { - Self::Expanding { rotation, .. } - | Self::Contracting { rotation, .. } => { + Self::Expanding { rotation, .. } | Self::Contracting { rotation, .. } => { *rotation as f32 / u32::MAX as f32 } } @@ -230,8 +212,7 @@ struct State { cache: canvas::Cache, } -impl<'a, Message, Theme> Widget - for Circular<'a, Theme> +impl<'a, Message, Theme> Widget for Circular<'a, Theme> where Message: 'a + Clone, Theme: StyleSheet, @@ -274,11 +255,10 @@ where let state = tree.state.downcast_mut::(); if let Event::Window(window::Event::RedrawRequested(now)) = event { - state.animation = state.animation.timed_transition( - self.cycle_duration, - self.rotation_duration, - *now, - ); + state.animation = + state + .animation + .timed_transition(self.cycle_duration, self.rotation_duration, *now); state.cache.clear(); shell.request_redraw(); @@ -299,8 +279,7 @@ where let state = tree.state.downcast_ref::(); let bounds = layout.bounds(); - let custom_style = - ::appearance(theme, &self.style); + let custom_style = ::appearance(theme, &self.style); let geometry = state.cache.draw(renderer, bounds.size(), |frame| { let track_radius = frame.width() / 2.0 - self.bar_height; @@ -323,17 +302,14 @@ where center: frame.center(), radius: track_radius, start_angle: start, - end_angle: start - + MIN_ANGLE - + WRAP_ANGLE * (self.easing.y_at_x(progress)), + end_angle: start + MIN_ANGLE + WRAP_ANGLE * (self.easing.y_at_x(progress)), }); } Animation::Contracting { progress, .. } => { builder.arc(canvas::path::Arc { center: frame.center(), radius: track_radius, - start_angle: start - + WRAP_ANGLE * (self.easing.y_at_x(progress)), + start_angle: start + WRAP_ANGLE * (self.easing.y_at_x(progress)), end_angle: start + MIN_ANGLE + WRAP_ANGLE, }); } @@ -349,19 +325,15 @@ where ); }); - renderer.with_translation( - Vector::new(bounds.x, bounds.y), - |renderer| { - use iced::advanced::graphics::geometry::Renderer as _; + renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { + use iced::advanced::graphics::geometry::Renderer as _; - renderer.draw_geometry(geometry); - }, - ); + renderer.draw_geometry(geometry); + }); } } -impl<'a, Message, Theme> From> - for Element<'a, Message, Theme, Renderer> +impl<'a, Message, Theme> From> for Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Theme: StyleSheet + 'a, diff --git a/examples/loading_spinners/src/easing.rs b/examples/loading_spinners/src/easing.rs index 374695a2d8..c408049eb6 100644 --- a/examples/loading_spinners/src/easing.rs +++ b/examples/loading_spinners/src/easing.rs @@ -53,10 +53,9 @@ impl Easing { } pub fn y_at_x(&self, x: f32) -> f32 { - let mut sampler = self.measurements.create_sampler( - &self.path, - lyon_algorithms::measure::SampleType::Normalized, - ); + let mut sampler = self + .measurements + .create_sampler(&self.path, lyon_algorithms::measure::SampleType::Normalized); let sample = sampler.sample(x); sample.position().y @@ -81,11 +80,7 @@ impl Builder { } /// Adds a quadratic bézier curve. Points must be between 0,0 and 1,1 - pub fn quadratic_bezier_to( - mut self, - ctrl: impl Into, - to: impl Into, - ) -> Self { + pub fn quadratic_bezier_to(mut self, ctrl: impl Into, to: impl Into) -> Self { self.0 .quadratic_bezier_to(Self::point(ctrl), Self::point(to)); @@ -99,11 +94,8 @@ impl Builder { ctrl2: impl Into, to: impl Into, ) -> Self { - self.0.cubic_bezier_to( - Self::point(ctrl1), - Self::point(ctrl2), - Self::point(to), - ); + self.0 + .cubic_bezier_to(Self::point(ctrl1), Self::point(ctrl2), Self::point(to)); self } diff --git a/examples/loading_spinners/src/linear.rs b/examples/loading_spinners/src/linear.rs index 551d0111b6..441bf55845 100644 --- a/examples/loading_spinners/src/linear.rs +++ b/examples/loading_spinners/src/linear.rs @@ -109,9 +109,7 @@ impl State { fn start(&self) -> Instant { match self { - Self::Expanding { start, .. } | Self::Contracting { start, .. } => { - *start - } + Self::Expanding { start, .. } | Self::Contracting { start, .. } => *start, } } @@ -124,11 +122,7 @@ impl State { } } - fn with_elapsed( - &self, - cycle_duration: Duration, - elapsed: Duration, - ) -> Self { + fn with_elapsed(&self, cycle_duration: Duration, elapsed: Duration) -> Self { let progress = elapsed.as_secs_f32() / cycle_duration.as_secs_f32(); match self { Self::Expanding { start, .. } => Self::Expanding { @@ -143,8 +137,7 @@ impl State { } } -impl<'a, Message, Theme, Renderer> Widget - for Linear<'a, Theme> +impl<'a, Message, Theme, Renderer> Widget for Linear<'a, Theme> where Message: Clone + 'a, Theme: StyleSheet + 'a, @@ -238,11 +231,9 @@ where State::Contracting { progress, .. } => renderer.fill_quad( Quad { bounds: Rectangle { - x: bounds.x - + self.easing.y_at_x(*progress) * bounds.width, + x: bounds.x + self.easing.y_at_x(*progress) * bounds.width, y: bounds.y, - width: (1.0 - self.easing.y_at_x(*progress)) - * bounds.width, + width: (1.0 - self.easing.y_at_x(*progress)) * bounds.width, height: bounds.height, }, ..renderer::Quad::default() @@ -253,8 +244,7 @@ where } } -impl<'a, Message, Theme, Renderer> From> - for Element<'a, Message, Theme, Renderer> +impl<'a, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where Message: Clone + 'a, Theme: StyleSheet + 'a, diff --git a/examples/loading_spinners/src/main.rs b/examples/loading_spinners/src/main.rs index 122b30fdad..19884fddc5 100644 --- a/examples/loading_spinners/src/main.rs +++ b/examples/loading_spinners/src/main.rs @@ -59,12 +59,12 @@ impl LoadingSpinners { column.push( row![ text(label).width(250), - Linear::new().easing(easing).cycle_duration( - Duration::from_secs_f32(self.cycle_duration) - ), - Circular::new().easing(easing).cycle_duration( - Duration::from_secs_f32(self.cycle_duration) - ) + Linear::new() + .easing(easing) + .cycle_duration(Duration::from_secs_f32(self.cycle_duration)), + Circular::new() + .easing(easing) + .cycle_duration(Duration::from_secs_f32(self.cycle_duration)) ] .align_y(Center) .spacing(20.0), diff --git a/examples/loupe/src/main.rs b/examples/loupe/src/main.rs index 6d32a62a6a..1995944e79 100644 --- a/examples/loupe/src/main.rs +++ b/examples/loupe/src/main.rs @@ -51,10 +51,7 @@ mod loupe { use iced::advanced::renderer; use iced::advanced::widget::{self, Widget}; use iced::mouse; - use iced::{ - Color, Element, Length, Rectangle, Renderer, Size, Theme, - Transformation, - }; + use iced::{Color, Element, Length, Rectangle, Renderer, Size, Theme, Transformation}; pub fn loupe<'a, Message>( zoom: f32, @@ -138,9 +135,9 @@ mod loupe { ); }); } else { - self.content.as_widget().draw( - tree, renderer, theme, style, layout, cursor, viewport, - ); + self.content + .as_widget() + .draw(tree, renderer, theme, style, layout, cursor, viewport); } } @@ -160,8 +157,7 @@ mod loupe { } } - impl<'a, Message> From> - for Element<'a, Message, Theme, Renderer> + impl<'a, Message> From> for Element<'a, Message, Theme, Renderer> where Message: 'a, { diff --git a/examples/markdown/src/main.rs b/examples/markdown/src/main.rs index 87d36dc43f..afdc5faa17 100644 --- a/examples/markdown/src/main.rs +++ b/examples/markdown/src/main.rs @@ -5,13 +5,11 @@ use iced::clipboard; use iced::highlighter; use iced::time::{self, Instant, milliseconds}; use iced::widget::{ - button, center_x, container, hover, image, markdown, operation, right, row, - scrollable, sensor, space, text_editor, toggler, + button, center_x, container, hover, image, markdown, operation, right, row, scrollable, sensor, + space, text_editor, toggler, }; use iced::window; -use iced::{ - Animation, Element, Fill, Font, Function, Subscription, Task, Theme, -}; +use iced::{Animation, Element, Fill, Font, Function, Subscription, Task, Theme}; use std::collections::HashMap; use std::io; @@ -216,9 +214,7 @@ impl Markdown { fn subscription(&self) -> Subscription { let listen_stream = match self.mode { Mode::Preview => Subscription::none(), - Mode::Stream { .. } => { - time::every(milliseconds(10)).map(|_| Message::NextToken) - } + Mode::Stream { .. } => time::every(milliseconds(10)).map(|_| Message::NextToken), }; let animate = { @@ -278,8 +274,7 @@ impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> { code: &'a str, lines: &'a [markdown::Text], ) -> Element<'a, Message> { - let code_block = - markdown::code_block(settings, lines, Message::LinkClicked); + let code_block = markdown::code_block(settings, lines, Message::LinkClicked); let copy = button(icon::copy().size(12)) .padding(2) @@ -288,8 +283,7 @@ impl<'a> markdown::Viewer<'a, Message> for CustomViewer<'a> { hover( code_block, - right(container(copy).style(container::dark)) - .padding(settings.spacing / 2), + right(container(copy).style(container::dark)).padding(settings.spacing / 2), ) } } diff --git a/examples/modal/src/main.rs b/examples/modal/src/main.rs index daf288e0a1..23cb62eec4 100644 --- a/examples/modal/src/main.rs +++ b/examples/modal/src/main.rs @@ -2,8 +2,8 @@ use iced::event::{self, Event}; use iced::keyboard; use iced::keyboard::key; use iced::widget::{ - button, center, column, container, mouse_area, opaque, operation, - pick_list, row, space, stack, text, text_input, + button, center, column, container, mouse_area, opaque, operation, pick_list, row, space, stack, + text, text_input, }; use iced::{Bottom, Color, Element, Fill, Subscription, Task}; @@ -95,8 +95,7 @@ impl App { fn view(&self) -> Element<'_, Message> { let content = container( column![ - row![text("Top Left"), space::horizontal(), text("Top Right")] - .height(Fill), + row![text("Top Left"), space::horizontal(), text("Top Right")].height(Fill), center(button(text("Show Modal")).on_press(Message::ShowModal)), row![ text("Bottom Left"), @@ -134,12 +133,7 @@ impl App { .spacing(5), column![ text("Plan").size(12), - pick_list( - Plan::ALL, - Some(self.plan), - Message::Plan - ) - .padding(5), + pick_list(Plan::ALL, Some(self.plan), Message::Plan).padding(5), ] .spacing(5), button(text("Submit")).on_press(Message::HideModal), @@ -176,8 +170,7 @@ enum Plan { } impl Plan { - pub const ALL: &'static [Self] = - &[Self::Basic, Self::Pro, Self::Enterprise]; + pub const ALL: &'static [Self] = &[Self::Basic, Self::Pro, Self::Enterprise]; } impl fmt::Display for Plan { diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 937bcc9208..66fcaf62e3 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,11 +1,8 @@ use iced::widget::{ - button, center, center_x, column, container, operation, scrollable, space, - text, text_input, + button, center, center_x, column, container, operation, scrollable, space, text, text_input, }; use iced::window; -use iced::{ - Center, Element, Fill, Function, Subscription, Task, Theme, Vector, -}; +use iced::{Center, Element, Fill, Function, Subscription, Task, Theme, Vector}; use std::collections::BTreeMap; @@ -69,14 +66,10 @@ impl Example { window::position(*last_window) .then(|last_position| { - let position = last_position.map_or( - window::Position::Default, - |last_position| { - window::Position::Specific( - last_position + Vector::new(20.0, 20.0), - ) - }, - ); + let position = + last_position.map_or(window::Position::Default, |last_position| { + window::Position::Specific(last_position + Vector::new(20.0, 20.0)) + }); let (_, open) = window::open(window::Settings { position, @@ -171,10 +164,7 @@ impl Window { text("Window scale factor:"), text_input("Window Scale", &self.scale_input) .on_input(Message::ScaleInputChanged.with(id)) - .on_submit(Message::ScaleChanged( - id, - self.scale_input.to_string() - )) + .on_submit(Message::ScaleChanged(id, self.scale_input.to_string())) ]; let title_input = column![ @@ -184,8 +174,7 @@ impl Window { .id(format!("input-{id}")) ]; - let new_window_button = - button(text("New Window")).on_press(Message::OpenWindow); + let new_window_button = button(text("New Window")).on_press(Message::OpenWindow); let content = column![scale_input, title_input, new_window_button] .spacing(50) diff --git a/examples/multitouch/src/main.rs b/examples/multitouch/src/main.rs index 6ea20511af..532a06b8f1 100644 --- a/examples/multitouch/src/main.rs +++ b/examples/multitouch/src/main.rs @@ -64,8 +64,7 @@ impl canvas::Program for Multitouch { | touch::Event::FingerMoved { id, position }, ) => Some(Message::FingerPressed { id, position }), Event::Touch( - touch::Event::FingerLifted { id, .. } - | touch::Event::FingerLost { id, .. }, + touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. }, ) => Some(Message::FingerLifted { id }), _ => None, }; @@ -101,14 +100,9 @@ impl canvas::Program for Multitouch { .map(|(_, p)| (f64::from(p.x), f64::from(p.y))) .collect(); - let diagram: voronator::VoronoiDiagram< - voronator::delaunator::Point, - > = voronator::VoronoiDiagram::from_tuple( - &(0.0, 0.0), - &(700.0, 700.0), - &vpoints, - ) - .expect("Generate Voronoi diagram"); + let diagram: voronator::VoronoiDiagram = + voronator::VoronoiDiagram::from_tuple(&(0.0, 0.0), &(700.0, 700.0), &vpoints) + .expect("Generate Voronoi diagram"); for (cell, zone) in diagram.cells().iter().zip(zones) { let mut builder = canvas::path::Builder::new(); diff --git a/examples/pane_grid/src/main.rs b/examples/pane_grid/src/main.rs index 0c0f7d7cb9..5bd7ecc46b 100644 --- a/examples/pane_grid/src/main.rs +++ b/examples/pane_grid/src/main.rs @@ -1,8 +1,6 @@ use iced::keyboard; use iced::widget::pane_grid::{self, PaneGrid}; -use iced::widget::{ - button, center_y, column, container, responsive, row, scrollable, text, -}; +use iced::widget::{button, center_y, column, container, responsive, row, scrollable, text}; use iced::{Center, Color, Element, Fill, Size, Subscription}; pub fn main() -> iced::Result { @@ -46,8 +44,7 @@ impl Example { fn update(&mut self, message: Message) { match message { Message::Split(axis, pane) => { - let result = - self.panes.split(axis, pane, Pane::new(self.panes_created)); + let result = self.panes.split(axis, pane, Pane::new(self.panes_created)); if let Some((pane, _)) = result { self.focus = Some(pane); @@ -57,11 +54,7 @@ impl Example { } Message::SplitFocused(axis) => { if let Some(pane) = self.focus { - let result = self.panes.split( - axis, - pane, - Pane::new(self.panes_created), - ); + let result = self.panes.split(axis, pane, Pane::new(self.panes_created)); if let Some((pane, _)) = result { self.focus = Some(pane); @@ -83,10 +76,7 @@ impl Example { Message::Resized(pane_grid::ResizeEvent { split, ratio }) => { self.panes.resize(split, ratio); } - Message::Dragged(pane_grid::DragEvent::Dropped { - pane, - target, - }) => { + Message::Dragged(pane_grid::DragEvent::Dropped { pane, target }) => { self.panes.drop(pane, target); } Message::Dragged(_) => {} @@ -118,8 +108,7 @@ impl Example { fn subscription(&self) -> Subscription { keyboard::listen().filter_map(|event| { - let keyboard::Event::KeyPressed { key, modifiers, .. } = event - else { + let keyboard::Event::KeyPressed { key, modifiers, .. } = event else { return None; }; @@ -138,11 +127,9 @@ impl Example { let pane_grid = PaneGrid::new(&self.panes, |id, pane, is_maximized| { let is_focused = focus == Some(id); - let pin_button = button( - text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), - ) - .on_press(Message::TogglePin(id)) - .padding(3); + let pin_button = button(text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14)) + .on_press(Message::TogglePin(id)) + .padding(3); let title = row![ pin_button, @@ -157,22 +144,15 @@ impl Example { let title_bar = pane_grid::TitleBar::new(title) .controls(pane_grid::Controls::dynamic( - view_controls( - id, - total_panes, - pane.is_pinned, - is_maximized, - ), + view_controls(id, total_panes, pane.is_pinned, is_maximized), button(text("X").size(14)) .style(button::danger) .padding(3) - .on_press_maybe( - if total_panes > 1 && !pane.is_pinned { - Some(Message::Close(id)) - } else { - None - }, - ), + .on_press_maybe(if total_panes > 1 && !pane.is_pinned { + Some(Message::Close(id)) + } else { + None + }), )) .padding(10) .style(if is_focused { @@ -288,10 +268,9 @@ fn view_content<'a>( .spacing(5) .max_width(160); - let content = - column![text!("{}x{}", size.width, size.height).size(24), controls,] - .spacing(10) - .align_x(Center); + let content = column![text!("{}x{}", size.width, size.height).size(24), controls,] + .spacing(10) + .align_x(Center); center_y(scrollable(content)).padding(5).into() } diff --git a/examples/pokedex/src/main.rs b/examples/pokedex/src/main.rs index d56c0878d3..b4aaee048e 100644 --- a/examples/pokedex/src/main.rs +++ b/examples/pokedex/src/main.rs @@ -65,9 +65,7 @@ impl Pokedex { fn view(&self) -> Element<'_, Message> { let content: Element<_> = match self { - Pokedex::Loading => { - text("Searching for Pokémon...").size(40).into() - } + Pokedex::Loading => text("Searching for Pokémon...").size(40).into(), Pokedex::Loaded { pokemon } => column![ pokemon.view(), button("Keep searching!").on_press(Message::Search) @@ -153,8 +151,7 @@ impl Pokemon { }; let (entry, image): (Entry, _) = - futures::future::try_join(fetch_entry, Self::fetch_image(id)) - .await?; + futures::future::try_join(fetch_entry, Self::fetch_image(id)).await?; let description = entry .flavor_text_entries diff --git a/examples/progress_bar/src/main.rs b/examples/progress_bar/src/main.rs index 89a941076d..128a3b3e6a 100644 --- a/examples/progress_bar/src/main.rs +++ b/examples/progress_bar/src/main.rs @@ -1,7 +1,6 @@ use iced::Element; use iced::widget::{ - center, center_x, checkbox, column, progress_bar, row, slider, - vertical_slider, + center, center_x, checkbox, column, progress_bar, row, slider, vertical_slider, }; pub fn main() -> iced::Result { @@ -24,9 +23,7 @@ impl Progress { fn update(&mut self, message: Message) { match message { Message::SliderChanged(x) => self.value = x, - Message::ToggleVertical(is_vertical) => { - self.is_vertical = is_vertical - } + Message::ToggleVertical(is_vertical) => self.is_vertical = is_vertical, } } @@ -38,12 +35,7 @@ impl Progress { center( row![ bar.vertical(), - vertical_slider( - 0.0..=100.0, - self.value, - Message::SliderChanged - ) - .step(0.01) + vertical_slider(0.0..=100.0, self.value, Message::SliderChanged).step(0.01) ] .spacing(20), ) @@ -51,8 +43,7 @@ impl Progress { center( column![ bar, - slider(0.0..=100.0, self.value, Message::SliderChanged) - .step(0.01) + slider(0.0..=100.0, self.value, Message::SliderChanged).step(0.01) ] .spacing(20), ) diff --git a/examples/qr_code/src/main.rs b/examples/qr_code/src/main.rs index fecc4abfb2..b34f5198fa 100644 --- a/examples/qr_code/src/main.rs +++ b/examples/qr_code/src/main.rs @@ -1,18 +1,12 @@ -use iced::widget::{ - center, column, pick_list, qr_code, row, slider, text, text_input, toggler, -}; +use iced::widget::{center, column, pick_list, qr_code, row, slider, text, text_input, toggler}; use iced::{Center, Element, Theme}; use std::ops::RangeInclusive; pub fn main() -> iced::Result { - iced::application( - QRGenerator::default, - QRGenerator::update, - QRGenerator::view, - ) - .theme(QRGenerator::theme) - .run() + iced::application(QRGenerator::default, QRGenerator::update, QRGenerator::view) + .theme(QRGenerator::theme) + .run() } #[derive(Default)] @@ -50,8 +44,7 @@ impl QRGenerator { Message::ToggleTotalSize(enabled) => { self.total_size = enabled.then_some( Self::SIZE_RANGE.start() - + (Self::SIZE_RANGE.end() - Self::SIZE_RANGE.start()) - / 2.0, + + (Self::SIZE_RANGE.end() - Self::SIZE_RANGE.start()) / 2.0, ); } Message::TotalSizeChanged(total_size) => { @@ -66,11 +59,10 @@ impl QRGenerator { fn view(&self) -> Element<'_, Message> { let title = text("QR Code Generator").size(70); - let input = - text_input("Type the data of your QR code here...", &self.data) - .on_input(Message::DataChanged) - .size(30) - .padding(15); + let input = text_input("Type the data of your QR code here...", &self.data) + .on_input(Message::DataChanged) + .size(30) + .padding(15); let toggle_total_size = toggler(self.total_size.is_some()) .on_toggle(Message::ToggleTotalSize) @@ -78,8 +70,7 @@ impl QRGenerator { let choose_theme = row![ text("Theme:"), - pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeChanged) - .placeholder("Theme") + pick_list(Theme::ALL, self.theme.as_ref(), Message::ThemeChanged).placeholder("Theme") ] .spacing(10) .align_y(Center); diff --git a/examples/screenshot/src/main.rs b/examples/screenshot/src/main.rs index b99157eaac..7ada45df0d 100644 --- a/examples/screenshot/src/main.rs +++ b/examples/screenshot/src/main.rs @@ -1,13 +1,8 @@ use iced::keyboard; -use iced::widget::{ - button, center_y, column, container, image, row, text, text_input, -}; +use iced::widget::{button, center_y, column, container, image, row, text, text_input}; use iced::window; use iced::window::screenshot::{self, Screenshot}; -use iced::{ - Center, ContentFit, Element, Fill, FillPortion, Rectangle, Subscription, - Task, -}; +use iced::{Center, ContentFit, Element, Fill, FillPortion, Rectangle, Subscription, Task}; use ::image as img; use ::image::ColorType; @@ -67,10 +62,7 @@ impl Example { if let Some((screenshot, _handle)) = &self.screenshot { self.png_saving = true; - return Task::perform( - save_to_png(screenshot.clone()), - Message::PngSaved, - ); + return Task::perform(save_to_png(screenshot.clone()), Message::PngSaved); } } Message::PngSaved(res) => { @@ -122,16 +114,15 @@ impl Example { } fn view(&self) -> Element<'_, Message> { - let image: Element = - if let Some((_screenshot, handle)) = &self.screenshot { - image(handle) - .content_fit(ContentFit::Contain) - .width(Fill) - .height(Fill) - .into() - } else { - text("Press the button to take a screenshot!").into() - }; + let image: Element = if let Some((_screenshot, handle)) = &self.screenshot { + image(handle) + .content_fit(ContentFit::Contain) + .width(Fill) + .height(Fill) + .into() + } else { + text("Press the button to take a screenshot!").into() + }; let image = center_y(image) .height(FillPortion(2)) @@ -149,11 +140,9 @@ impl Example { let crop_dimension_controls = row![ text("W:").width(30), - numeric_input("0", self.width_input_value) - .map(Message::WidthInputChanged), + numeric_input("0", self.width_input_value).map(Message::WidthInputChanged), text("H:").width(30), - numeric_input("0", self.height_input_value) - .map(Message::HeightInputChanged) + numeric_input("0", self.height_input_value).map(Message::HeightInputChanged) ] .spacing(10) .align_y(Center); @@ -169,15 +158,15 @@ impl Example { .align_x(Center); let controls = { - let save_result = - self.saved_png_path.as_ref().map( - |png_result| match png_result { - Ok(path) => format!("Png saved as: {path:?}!"), - Err(PngError(error)) => { - format!("Png could not be saved due to:\n{error}") - } - }, - ); + let save_result = self + .saved_png_path + .as_ref() + .map(|png_result| match png_result { + Ok(path) => format!("Png saved as: {path:?}!"), + Err(PngError(error)) => { + format!("Png could not be saved due to:\n{error}") + } + }); column![ column![ @@ -186,12 +175,10 @@ impl Example { .width(Fill) .on_press(Message::Screenshot), if !self.png_saving { - button(centered_text("Save as png")).on_press_maybe( - self.screenshot.is_some().then(|| Message::Png), - ) + button(centered_text("Save as png")) + .on_press_maybe(self.screenshot.is_some().then(|| Message::Png)) } else { - button(centered_text("Saving...")) - .style(button::secondary) + button(centered_text("Saving...")).style(button::secondary) } .style(button::secondary) .padding([10, 20]) @@ -262,10 +249,7 @@ async fn save_to_png(screenshot: Screenshot) -> Result { #[derive(Clone, Debug)] struct PngError(String); -fn numeric_input( - placeholder: &str, - value: Option, -) -> Element<'_, Option> { +fn numeric_input(placeholder: &str, value: Option) -> Element<'_, Option> { text_input( placeholder, &value.as_ref().map(ToString::to_string).unwrap_or_default(), diff --git a/examples/scrollable/src/main.rs b/examples/scrollable/src/main.rs index a67489ed53..c25932c763 100644 --- a/examples/scrollable/src/main.rs +++ b/examples/scrollable/src/main.rs @@ -1,7 +1,6 @@ use iced::widget::scrollable::{self, Properties, Scrollbar, Scroller}; use iced::widget::{ - button, column, container, operation, progress_bar, radio, row, scrollable, - slider, space, text, + button, column, container, operation, progress_bar, radio, row, scrollable, slider, space, text, }; use iced::{Border, Center, Color, Element, Fill, Task, Theme}; use iced_core::id::Id; @@ -104,11 +103,8 @@ impl ScrollableDemo { } fn view(&self) -> Element<'_, Message> { - let scrollbar_width_slider = slider( - 0..=15, - self.scrollbar_width, - Message::ScrollbarWidthChanged, - ); + let scrollbar_width_slider = + slider(0..=15, self.scrollbar_width, Message::ScrollbarWidthChanged); let scrollbar_margin_slider = slider( 0..=15, self.scrollbar_margin, @@ -186,120 +182,112 @@ impl ScrollableDemo { .on_press(Message::ScrollToBeginning) }; - let scrollable_content: Element = - Element::from(match self.scrollable_direction { - Direction::Vertical => scrollable( + let scrollable_content: Element = Element::from(match self.scrollable_direction { + Direction::Vertical => scrollable( + column![ + scroll_to_end_button(), + text("Beginning!"), + space().height(1200), + text("Middle!"), + space().height(1200), + text("End!"), + scroll_to_beginning_button(), + ] + .align_x(Center) + .padding([40, 0]) + .spacing(40), + ) + .direction(scrollable::Direction::Vertical( + scrollable::Scrollbar::new() + .width(self.scrollbar_width) + .margin(self.scrollbar_margin) + .scroller_width(self.scroller_width) + .anchor(self.anchor), + )) + .width(Fill) + .height(Fill) + .id(SCROLLABLE) + .on_scroll(Message::Scrolled) + .auto_scroll(true), + Direction::Horizontal => scrollable( + row![ + scroll_to_end_button(), + text("Beginning!"), + space().width(1200), + text("Middle!"), + space().width(1200), + text("End!"), + scroll_to_beginning_button(), + ] + .height(450) + .align_y(Center) + .padding([0, 40]) + .spacing(40), + ) + .direction(scrollable::Direction::Horizontal( + scrollable::Scrollbar::new() + .width(self.scrollbar_width) + .margin(self.scrollbar_margin) + .scroller_width(self.scroller_width) + .anchor(self.anchor), + )) + .width(Fill) + .height(Fill) + .id(SCROLLABLE) + .on_scroll(Message::Scrolled) + .auto_scroll(true), + Direction::Multi => scrollable( + //horizontal content + row![ + column![text("Let's do some scrolling!"), space().height(2400)], + scroll_to_end_button(), + text("Horizontal - Beginning!"), + space().width(1200), + //vertical content column![ + text("Horizontal - Middle!"), scroll_to_end_button(), - text("Beginning!"), + text("Vertical - Beginning!"), space().height(1200), - text("Middle!"), + text("Vertical - Middle!"), space().height(1200), - text("End!"), - scroll_to_beginning_button(), - ] - .align_x(Center) - .padding([40, 0]) - .spacing(40), - ) - .direction(scrollable::Direction::Vertical( - scrollable::Scrollbar::new() - .width(self.scrollbar_width) - .margin(self.scrollbar_margin) - .scroller_width(self.scroller_width) - .anchor(self.anchor), - )) - .width(Fill) - .height(Fill) - .id(SCROLLABLE) - .on_scroll(Message::Scrolled) - .auto_scroll(true), - Direction::Horizontal => scrollable( - row![ - scroll_to_end_button(), - text("Beginning!"), - space().width(1200), - text("Middle!"), - space().width(1200), - text("End!"), - scroll_to_beginning_button(), - ] - .height(450) - .align_y(Center) - .padding([0, 40]) - .spacing(40), - ) - .direction(scrollable::Direction::Horizontal( - scrollable::Scrollbar::new() - .width(self.scrollbar_width) - .margin(self.scrollbar_margin) - .scroller_width(self.scroller_width) - .anchor(self.anchor), - )) - .width(Fill) - .height(Fill) - .id(SCROLLABLE) - .on_scroll(Message::Scrolled) - .auto_scroll(true), - Direction::Multi => scrollable( - //horizontal content - row![ - column![ - text("Let's do some scrolling!"), - space().height(2400) - ], - scroll_to_end_button(), - text("Horizontal - Beginning!"), - space().width(1200), - //vertical content - column![ - text("Horizontal - Middle!"), - scroll_to_end_button(), - text("Vertical - Beginning!"), - space().height(1200), - text("Vertical - Middle!"), - space().height(1200), - text("Vertical - End!"), - scroll_to_beginning_button(), - space().height(40), - ] - .spacing(40), - space().width(1200), - text("Horizontal - End!"), + text("Vertical - End!"), scroll_to_beginning_button(), + space().height(40), ] - .align_y(Center) - .padding([0, 40]) .spacing(40), - ) - .direction({ - let scrollbar = scrollable::Scrollbar::new() - .width(self.scrollbar_width) - .margin(self.scrollbar_margin) - .scroller_width(self.scroller_width) - .anchor(self.anchor); + space().width(1200), + text("Horizontal - End!"), + scroll_to_beginning_button(), + ] + .align_y(Center) + .padding([0, 40]) + .spacing(40), + ) + .direction({ + let scrollbar = scrollable::Scrollbar::new() + .width(self.scrollbar_width) + .margin(self.scrollbar_margin) + .scroller_width(self.scroller_width) + .anchor(self.anchor); - scrollable::Direction::Both { - horizontal: scrollbar, - vertical: scrollbar, - } - }) - .width(Fill) - .height(Fill) - .id(SCROLLABLE) - .on_scroll(Message::Scrolled) - .auto_scroll(true), - }); + scrollable::Direction::Both { + horizontal: scrollbar, + vertical: scrollbar, + } + }) + .width(Fill) + .height(Fill) + .id(SCROLLABLE) + .on_scroll(Message::Scrolled) + .auto_scroll(true), + }); let progress_bars: Element = match self.scrollable_direction { - Direction::Vertical => { - progress_bar(0.0..=1.0, self.current_scroll_offset.y).into() - } - Direction::Horizontal => { - progress_bar(0.0..=1.0, self.current_scroll_offset.x) - .style(progress_bar_custom_style) - .into() - } + Direction::Vertical => progress_bar(0.0..=1.0, self.current_scroll_offset.y).into(), + Direction::Horizontal => progress_bar(0.0..=1.0, self.current_scroll_offset.x) + .style(progress_bar_custom_style) + .into(), Direction::Multi => column![ progress_bar(0.0..=1.0, self.current_scroll_offset.y), progress_bar(0.0..=1.0, self.current_scroll_offset.x) @@ -309,11 +297,10 @@ impl ScrollableDemo { .into(), }; - let content: Element = - column![scroll_controls, scrollable_content, progress_bars] - .align_x(Center) - .spacing(10) - .into(); + let content: Element = column![scroll_controls, scrollable_content, progress_bars] + .align_x(Center) + .spacing(10) + .into(); container(content).padding(20).into() } diff --git a/examples/sctk_drag/src/dnd_destination.rs b/examples/sctk_drag/src/dnd_destination.rs index 1081d8bb0b..14618124b3 100644 --- a/examples/sctk_drag/src/dnd_destination.rs +++ b/examples/sctk_drag/src/dnd_destination.rs @@ -3,20 +3,20 @@ use std::{ sync::atomic::{AtomicU64, Ordering}, }; -use iced::{Element, id::Id}; use iced::{ - Event, Length, Rectangle, clipboard::{ dnd::{self, DndAction, DndDestinationRectangle, DndEvent, OfferEvent}, mime::AllowedMimeTypes, }, event, id::Internal, - mouse, overlay, + mouse, overlay, Event, Length, Rectangle, }; +use iced::{id::Id, Element}; use iced_core::{ - self, Clipboard, Layout, Shell, Widget, layout, - widget::{Tree, tree}, + self, layout, + widget::{tree, Tree}, + Clipboard, Layout, Shell, Widget, }; pub fn dnd_destination<'a, Message: 'static>( @@ -40,10 +40,7 @@ pub struct DragId(pub u128); impl DragId { pub fn new() -> Self { - DragId( - u128::from(u64::MAX) - + u128::from(DRAG_ID_COUNTER.fetch_add(1, Ordering::Relaxed)), - ) + DragId(u128::from(u64::MAX) + u128::from(DRAG_ID_COUNTER.fetch_add(1, Ordering::Relaxed))) } } @@ -69,15 +66,11 @@ pub struct DndDestination<'a, Message> { on_motion: Option Message>>, on_action_selected: Option Message>>, on_data_received: Option) -> Message>>, - on_finish: - Option, DndAction, f64, f64) -> Message>>, + on_finish: Option, DndAction, f64, f64) -> Message>>, } impl<'a, Message: 'static> DndDestination<'a, Message> { - pub fn new( - child: impl Into>, - mimes: Vec>, - ) -> Self { + pub fn new(child: impl Into>, mimes: Vec>) -> Self { Self { id: Id::unique(), drag_id: None, @@ -127,10 +120,9 @@ impl<'a, Message: 'static> DndDestination<'a, Message> { mut self, f: impl Fn(Option) -> Message + 'static, ) -> Self { - self.on_data_received = - Some(Box::new( - move |mime, data| f(T::try_from((data, mime)).ok()), - )); + self.on_data_received = Some(Box::new( + move |mime, data| f(T::try_from((data, mime)).ok()), + )); self } @@ -183,28 +175,19 @@ impl<'a, Message: 'static> DndDestination<'a, Message> { } #[must_use] - pub fn on_hold( - mut self, - f: impl Fn(f64, f64) -> Message + 'static, - ) -> Self { + pub fn on_hold(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self { self.on_hold = Some(Box::new(f)); self } #[must_use] - pub fn on_drop( - mut self, - f: impl Fn(f64, f64) -> Message + 'static, - ) -> Self { + pub fn on_drop(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self { self.on_drop = Some(Box::new(f)); self } #[must_use] - pub fn on_enter( - mut self, - f: impl Fn(f64, f64, Vec) -> Message + 'static, - ) -> Self { + pub fn on_enter(mut self, f: impl Fn(f64, f64, Vec) -> Message + 'static) -> Self { self.on_enter = Some(Box::new(f)); self } @@ -225,28 +208,19 @@ impl<'a, Message: 'static> DndDestination<'a, Message> { } #[must_use] - pub fn on_motion( - mut self, - f: impl Fn(f64, f64) -> Message + 'static, - ) -> Self { + pub fn on_motion(mut self, f: impl Fn(f64, f64) -> Message + 'static) -> Self { self.on_motion = Some(Box::new(f)); self } #[must_use] - pub fn on_action_selected( - mut self, - f: impl Fn(DndAction) -> Message + 'static, - ) -> Self { + pub fn on_action_selected(mut self, f: impl Fn(DndAction) -> Message + 'static) -> Self { self.on_action_selected = Some(Box::new(f)); self } #[must_use] - pub fn on_data_received( - mut self, - f: impl Fn(String, Vec) -> Message + 'static, - ) -> Self { + pub fn on_data_received(mut self, f: impl Fn(String, Vec) -> Message + 'static) -> Self { self.on_data_received = Some(Box::new(f)); self } @@ -295,11 +269,9 @@ impl<'a, Message: 'static> Widget renderer: &iced::Renderer, limits: &layout::Limits, ) -> layout::Node { - self.container.as_widget().layout( - &mut tree.children[0], - renderer, - limits, - ) + self.container + .as_widget() + .layout(&mut tree.children[0], renderer, limits) } fn operate( @@ -309,12 +281,9 @@ impl<'a, Message: 'static> Widget renderer: &iced::Renderer, operation: &mut dyn iced_core::widget::Operation<()>, ) { - self.container.as_widget().operate( - &mut tree.children[0], - layout, - renderer, - operation, - ); + self.container + .as_widget() + .operate(&mut tree.children[0], layout, renderer, operation); } #[allow(clippy::too_many_lines)] @@ -366,8 +335,7 @@ impl<'a, Message: 'static> Widget } if self.forward_drag_as_cursor { #[allow(clippy::cast_possible_truncation)] - let drag_cursor = - mouse::Cursor::Available((x as f32, y as f32).into()); + let drag_cursor = mouse::Cursor::Available((x as f32, y as f32).into()); let event = Event::Mouse(mouse::Event::CursorMoved { position: drag_cursor.position().unwrap(), }); @@ -385,12 +353,8 @@ impl<'a, Message: 'static> Widget shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer(id, OfferEvent::Leave)) - if id == Some(my_id) => - { - state.on_leave( - self.on_leave.as_ref().map(std::convert::AsRef::as_ref), - ); + Event::Dnd(DndEvent::Offer(id, OfferEvent::Leave)) if id == Some(my_id) => { + state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref)); if self.forward_drag_as_cursor { let drag_cursor = mouse::Cursor::Unavailable; @@ -409,9 +373,7 @@ impl<'a, Message: 'static> Widget shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer(id, OfferEvent::Motion { x, y })) - if id == Some(my_id) => - { + Event::Dnd(DndEvent::Offer(id, OfferEvent::Motion { x, y })) if id == Some(my_id) => { if let Some(msg) = state.on_motion( x, y, @@ -424,8 +386,7 @@ impl<'a, Message: 'static> Widget if self.forward_drag_as_cursor { #[allow(clippy::cast_possible_truncation)] - let drag_cursor = - mouse::Cursor::Available((x as f32, y as f32).into()); + let drag_cursor = mouse::Cursor::Available((x as f32, y as f32).into()); let event = Event::Mouse(mouse::Event::CursorMoved { position: drag_cursor.position().unwrap(), }); @@ -443,32 +404,27 @@ impl<'a, Message: 'static> Widget shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer(id, OfferEvent::LeaveDestination)) - if id == Some(my_id) => - { - if let Some(msg) = state.on_leave( - self.on_leave.as_ref().map(std::convert::AsRef::as_ref), - ) { + Event::Dnd(DndEvent::Offer(id, OfferEvent::LeaveDestination)) if id == Some(my_id) => { + if let Some(msg) = + state.on_leave(self.on_leave.as_ref().map(std::convert::AsRef::as_ref)) + { shell.publish(msg); } shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer(id, OfferEvent::Drop)) - if id == Some(my_id) => - { - if let Some(msg) = state.on_drop( - self.on_drop.as_ref().map(std::convert::AsRef::as_ref), - ) { + Event::Dnd(DndEvent::Offer(id, OfferEvent::Drop)) if id == Some(my_id) => { + if let Some(msg) = + state.on_drop(self.on_drop.as_ref().map(std::convert::AsRef::as_ref)) + { shell.publish(msg); } shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer( - id, - OfferEvent::SelectedAction(action), - )) if id == Some(my_id) => { + Event::Dnd(DndEvent::Offer(id, OfferEvent::SelectedAction(action))) + if id == Some(my_id) => + { if let Some(msg) = state.on_action_selected( action, self.on_action_selected @@ -480,10 +436,9 @@ impl<'a, Message: 'static> Widget shell.capture_event(); return; } - Event::Dnd(DndEvent::Offer( - id, - OfferEvent::Data { data, mime_type }, - )) if id == Some(my_id) => { + Event::Dnd(DndEvent::Offer(id, OfferEvent::Data { data, mime_type })) + if id == Some(my_id) => + { if let (Some(msg), ret) = state.on_data_received( mime_type, data, @@ -547,8 +502,7 @@ impl<'a, Message: 'static> Widget layout: Layout<'_>, renderer: &iced::Renderer, translation: iced::Vector, - ) -> Option> - { + ) -> Option> { None } @@ -629,10 +583,7 @@ impl State { on_enter.map(|f| f(x, y, mime_types)) } - pub fn on_leave( - &mut self, - on_leave: Option<&dyn Fn() -> Message>, - ) -> Option { + pub fn on_leave(&mut self, on_leave: Option<&dyn Fn() -> Message>) -> Option { if self.drag_offer.as_ref().is_some_and(|d| !d.dropped) { self.drag_offer = None; on_leave.map(|f| f()) @@ -700,9 +651,7 @@ impl State { mime: String, data: Vec, on_data_received: Option) -> Message>, - on_finish: Option< - impl Fn(String, Vec, DndAction, f64, f64) -> Message, - >, + on_finish: Option, DndAction, f64, f64) -> Message>, ) -> (Option, event::Status) { let Some(dnd) = self.drag_offer.as_ref() else { self.drag_offer = None; @@ -711,8 +660,7 @@ impl State { if dnd.dropped { let ret = ( - on_finish - .map(|f| f(mime, data, dnd.selected_action, dnd.x, dnd.y)), + on_finish.map(|f| f(mime, data, dnd.selected_action, dnd.x, dnd.y)), event::Status::Captured, ); self.drag_offer = None; @@ -725,9 +673,7 @@ impl State { } } -impl<'a, Message: 'static> From> - for Element<'a, Message> -{ +impl<'a, Message: 'static> From> for Element<'a, Message> { fn from(wrapper: DndDestination<'a, Message>) -> Self { Element::new(wrapper) } diff --git a/examples/sctk_drag/src/dnd_source.rs b/examples/sctk_drag/src/dnd_source.rs index 1d8b85c426..00f9c46019 100644 --- a/examples/sctk_drag/src/dnd_source.rs +++ b/examples/sctk_drag/src/dnd_source.rs @@ -1,16 +1,16 @@ use std::any::Any; -use iced::Element; use iced::id::Id; use iced::widget::container; +use iced::Element; use iced::{ - Event, Length, Point, Rectangle, clipboard::dnd::{DndAction, DndEvent, SourceEvent}, - event, mouse, overlay, + event, mouse, overlay, Event, Length, Point, Rectangle, }; use iced_core::{ - Clipboard, Shell, layout, renderer, - widget::{Tree, tree}, + layout, renderer, + widget::{tree, Tree}, + Clipboard, Shell, }; use iced_core::{Layout, Widget}; @@ -30,18 +30,17 @@ pub struct DndSource<'a, Message, AppMessage, D> { action: DndAction, container: Element<'a, Message>, drag_content: Option D>>, - drag_icon: - Option (Element<'static, AppMessage>, tree::State)>>, + drag_icon: Option (Element<'static, AppMessage>, tree::State)>>, drag_threshold: f32, _phantom: std::marker::PhantomData, } impl< - 'a, - Message: 'static, - AppMessage: 'static, - D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, -> DndSource<'a, Message, AppMessage, D> + 'a, + Message: 'static, + AppMessage: 'static, + D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, + > DndSource<'a, Message, AppMessage, D> { pub fn new(child: impl Into>) -> Self { Self { @@ -119,12 +118,11 @@ impl< } impl< - 'a, - Message: 'static, - AppMessage: 'static, - D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, -> Widget - for DndSource<'a, Message, AppMessage, D> + 'a, + Message: 'static, + AppMessage: 'static, + D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, + > Widget for DndSource<'a, Message, AppMessage, D> { fn children(&self) -> Vec { vec![Tree::new(&self.container)] @@ -153,11 +151,10 @@ impl< limits: &layout::Limits, ) -> layout::Node { let state = tree.state.downcast_mut::(); - let node = self.container.as_widget().layout( - &mut tree.children[0], - renderer, - limits, - ); + let node = self + .container + .as_widget() + .layout(&mut tree.children[0], renderer, limits); state.cached_bounds = node.bounds(); node } @@ -170,18 +167,11 @@ impl< operation: &mut dyn iced_core::widget::Operation<()>, ) { operation.custom((&mut tree.state) as &mut dyn Any, Some(&self.id)); - operation.container( - Some(&self.id), - layout.bounds(), - &mut |operation| { - self.container.as_widget().operate( - &mut tree.children[0], - layout, - renderer, - operation, - ) - }, - ); + operation.container(Some(&self.id), layout.bounds(), &mut |operation| { + self.container + .as_widget() + .operate(&mut tree.children[0], layout, renderer, operation) + }); } fn update( @@ -236,16 +226,9 @@ impl< state.left_pressed_position = None; return ret; } - if let Some(left_pressed_position) = - state.left_pressed_position - { - if position.distance(left_pressed_position) - > self.drag_threshold - { - self.start_dnd( - clipboard, - state.cached_bounds, - ); + if let Some(left_pressed_position) = state.left_pressed_position { + if position.distance(left_pressed_position) > self.drag_threshold { + self.start_dnd(clipboard, state.cached_bounds); state.is_dragging = true; state.left_pressed_position = None; } @@ -264,9 +247,7 @@ impl< } _ => return ret, }, - Event::Dnd(DndEvent::Source( - SourceEvent::Cancelled | SourceEvent::Finished, - )) => { + Event::Dnd(DndEvent::Source(SourceEvent::Cancelled | SourceEvent::Finished)) => { if state.is_dragging { state.is_dragging = false; shell.capture_event(); @@ -327,8 +308,7 @@ impl< layout: Layout<'_>, renderer: &iced::Renderer, translation: iced::Vector, - ) -> Option> - { + ) -> Option> { None } @@ -357,11 +337,11 @@ impl< } impl< - 'a, - Message: 'static, - AppMessage: 'static, - D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, -> From> for Element<'a, Message> + 'a, + Message: 'static, + AppMessage: 'static, + D: iced::clipboard::mime::AsMimeTypes + std::marker::Send + 'static, + > From> for Element<'a, Message> { fn from(e: DndSource<'a, Message, AppMessage, D>) -> Element<'a, Message> { Element::new(e) diff --git a/examples/sctk_drag/src/main.rs b/examples/sctk_drag/src/main.rs index f2d1a5e527..9cdeda5810 100644 --- a/examples/sctk_drag/src/main.rs +++ b/examples/sctk_drag/src/main.rs @@ -19,8 +19,7 @@ use iced_core::{ }; fn main() -> iced::Result { - iced::daemon(DndTest::title, DndTest::update, DndTest::view) - .run_with(DndTest::new) + iced::daemon(DndTest::title, DndTest::update, DndTest::view).run_with(DndTest::new) // iced::application(Todos::title, Todos::update, Todos::view) // .subscription(Todos::subscription) // .font(include_bytes!("../fonts/icons.ttf").as_slice()) @@ -75,10 +74,7 @@ impl AsMimeTypes for MyDndString { ]) } - fn as_bytes( - &self, - _mime_type: &str, - ) -> Option> { + fn as_bytes(&self, _mime_type: &str) -> Option> { Some(Cow::Owned(self.0.clone().into_bytes())) } } @@ -136,13 +132,10 @@ impl DndTest { let s2 = s.clone(); column![ dnd_destination::dnd_destination_for_data::( - container(text(format!( - "Drag text here: {}", - &self.current_text - ))) - .width(Length::Fill) - .height(Length::FillPortion(1)) - .padding(20), + container(text(format!("Drag text here: {}", &self.current_text))) + .width(Length::Fill) + .height(Length::FillPortion(1)) + .padding(20), |data, _| { dbg!("got data"); Message::DndData(data.unwrap_or_default()) @@ -176,8 +169,7 @@ impl DndTest { ) .drag_threshold(5.0) .drag_icon(move || { - let t: Text<'static, iced::Theme, iced::Renderer> = - text(s.clone()); + let t: Text<'static, iced::Theme, iced::Renderer> = text(s.clone()); let state = ::from( - t, - ), + Element::<'static, (), iced::Theme, iced::Renderer>::from(t), state, ) }) diff --git a/examples/sctk_lazy/src/main.rs b/examples/sctk_lazy/src/main.rs index 47560ee39d..448260b1f2 100644 --- a/examples/sctk_lazy/src/main.rs +++ b/examples/sctk_lazy/src/main.rs @@ -5,8 +5,7 @@ use iced::platform_specific::shell::commands::layer_surface::{ }; use iced::widget::{ - button, column, horizontal_space, lazy, pick_list, row, scrollable, text, - text_input, + button, column, horizontal_space, lazy, pick_list, row, scrollable, text, text_input, }; use iced::window::Id; use iced::Task; @@ -131,8 +130,7 @@ enum Message { impl App { fn new() -> (App, Task) { let mut initial_surface = SctkLayerSurfaceSettings::default(); - initial_surface.keyboard_interactivity = - KeyboardInteractivity::OnDemand; + initial_surface.keyboard_interactivity = KeyboardInteractivity::OnDemand; initial_surface.size_limits = Limits::NONE .min_width(1.0) .min_height(1.0) @@ -184,17 +182,12 @@ impl App { let mut items: Vec<_> = self.items.iter().cloned().collect(); items.sort_by(|a, b| match self.order { - Order::Ascending => { - a.name.to_lowercase().cmp(&b.name.to_lowercase()) - } - Order::Descending => { - b.name.to_lowercase().cmp(&a.name.to_lowercase()) - } + Order::Ascending => a.name.to_lowercase().cmp(&b.name.to_lowercase()), + Order::Descending => b.name.to_lowercase().cmp(&a.name.to_lowercase()), }); column(items.into_iter().map(|item| { - let button = button("Delete") - .on_press(Message::DeleteItem(item.clone())); + let button = button("Delete").on_press(Message::DeleteItem(item.clone())); row![ text(item.name.clone()), diff --git a/examples/sctk_session_lock/src/main.rs b/examples/sctk_session_lock/src/main.rs index 8d42973f0e..911f5b907e 100644 --- a/examples/sctk_session_lock/src/main.rs +++ b/examples/sctk_session_lock/src/main.rs @@ -44,10 +44,7 @@ impl Locker { Message::WaylandEvent(evt) => match evt { WaylandEvent::Output(evt, output) => match evt { OutputEvent::Created(_) => { - return session_lock::get_lock_surface( - window::Id::unique(), - output, - ); + return session_lock::get_lock_surface(window::Id::unique(), output); } OutputEvent::Removed => {} _ => {} @@ -55,9 +52,7 @@ impl Locker { WaylandEvent::SessionLock(evt) => match evt { SessionLockEvent::Locked => { return iced::Task::perform( - async_std::task::sleep( - std::time::Duration::from_secs(5), - ), + async_std::task::sleep(std::time::Duration::from_secs(5)), |_| Message::TimeUp, ); } @@ -83,9 +78,7 @@ impl Locker { fn subscription(&self) -> Subscription { listen_raw(|evt, _, _| { - if let iced::Event::PlatformSpecific( - iced::event::PlatformSpecific::Wayland(evt), - ) = evt + if let iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(evt)) = evt { Some(Message::WaylandEvent(evt)) } else { diff --git a/examples/sctk_subsurface/src/main.rs b/examples/sctk_subsurface/src/main.rs index c00f722544..c9f88c3f62 100644 --- a/examples/sctk_subsurface/src/main.rs +++ b/examples/sctk_subsurface/src/main.rs @@ -7,7 +7,6 @@ use cctk::sctk::reexports::{ use iced::platform_specific::shell::commands::subsurface::get_subsurface; use iced::{ - Element, Length, Subscription, Task, event::wayland::Event as WaylandEvent, platform_specific::{ runtime::wayland::subsurface::SctkSubsurfaceSettings, @@ -15,6 +14,7 @@ use iced::{ }, widget::{button, column, text, text_input}, window::{self, Id, Settings}, + Element, Length, Subscription, Task, }; use std::sync::{Arc, Mutex}; @@ -74,8 +74,7 @@ impl SubsurfaceApp { WaylandEvent::Output(_evt, output) => { if self.connection.is_none() { if let Some(backend) = output.backend().upgrade() { - self.connection = - Some(Connection::from_backend(backend)); + self.connection = Some(Connection::from_backend(backend)); } } } @@ -130,28 +129,22 @@ impl SubsurfaceApp { .width(Length::Fill) .height(Length::Fill) .push( - subsurface_widget::Subsurface::new( - red_buffer.clone() - ) - .width(Length::Fill) - .height(Length::Fill) - .z(0) + subsurface_widget::Subsurface::new(red_buffer.clone()) + .width(Length::Fill) + .height(Length::Fill) + .z(0) ) .push( - subsurface_widget::Subsurface::new( - green_buffer.clone() - ) - .width(Length::Fixed(1920.)) - .height(Length::Fixed(200.)) - .z(1) + subsurface_widget::Subsurface::new(green_buffer.clone()) + .width(Length::Fixed(1920.)) + .height(Length::Fixed(200.)) + .z(1) ) .push( - subsurface_widget::Subsurface::new( - red_buffer.clone() - ) - .width(Length::Fill) - .height(Length::Fixed(100.)) - .z(2) + subsurface_widget::Subsurface::new(red_buffer.clone()) + .width(Length::Fill) + .height(Length::Fixed(100.)) + .z(2) ) ) .width(Length::Fill) @@ -176,12 +169,9 @@ impl SubsurfaceApp { fn subscription(&self) -> Subscription { let mut subscriptions = vec![iced::event::listen_with(|evt, _, _| { - if let iced::Event::PlatformSpecific( - iced::event::PlatformSpecific::Wayland(WaylandEvent::Output( - evt, - output, - )), - ) = evt + if let iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland( + WaylandEvent::Output(evt, output), + )) = evt { Some(Message::WaylandEvent(WaylandEvent::Output(evt, output))) } else { @@ -189,8 +179,7 @@ impl SubsurfaceApp { } })]; if let Some(connection) = &self.connection { - subscriptions - .push(wayland::subscription(connection).map(Message::Wayland)); + subscriptions.push(wayland::subscription(connection).map(Message::Wayland)); } Subscription::batch(subscriptions) } diff --git a/examples/sctk_subsurface/src/subsurface_container.rs b/examples/sctk_subsurface/src/subsurface_container.rs index ed0e88941e..9dba959e07 100644 --- a/examples/sctk_subsurface/src/subsurface_container.rs +++ b/examples/sctk_subsurface/src/subsurface_container.rs @@ -7,8 +7,7 @@ use iced::core::overlay; use iced::core::renderer; use iced::core::widget::{Operation, Tree}; use iced::core::{ - Clipboard, Element, Layout, Length, Padding, Pixels, Rectangle, Shell, - Size, Vector, Widget, + Clipboard, Element, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents vertically. @@ -34,12 +33,7 @@ use iced::core::{ /// } /// ``` #[allow(missing_debug_implementations)] -pub struct SubsurfaceContainer< - 'a, - Message, - Theme = iced::Theme, - Renderer = iced::Renderer, -> { +pub struct SubsurfaceContainer<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> { spacing: f32, padding: Padding, width: Length, @@ -50,8 +44,7 @@ pub struct SubsurfaceContainer< children: Vec>, } -impl<'a, Message, Theme, Renderer> - SubsurfaceContainer<'a, Message, Theme, Renderer> +impl<'a, Message, Theme, Renderer> SubsurfaceContainer<'a, Message, Theme, Renderer> where Renderer: iced::core::Renderer, { @@ -81,9 +74,7 @@ where /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`SubsurfaceContainer::width`] or [`SubsurfaceContainer::height`] accordingly. - pub fn from_vec( - children: Vec>, - ) -> Self { + pub fn from_vec(children: Vec>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, @@ -144,10 +135,7 @@ where } /// Adds an element to the [`SubsurfaceContainer`]. - pub fn push( - mut self, - child: impl Into>, - ) -> Self { + pub fn push(mut self, child: impl Into>) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); @@ -179,8 +167,7 @@ where } } -impl<'a, Message, Renderer> Default - for SubsurfaceContainer<'a, Message, Renderer> +impl<'a, Message, Renderer> Default for SubsurfaceContainer<'a, Message, Renderer> where Renderer: iced::core::Renderer, { @@ -193,11 +180,7 @@ impl<'a, Message, Theme, Renderer: iced::core::Renderer> FromIterator> for SubsurfaceContainer<'a, Message, Theme, Renderer> { - fn from_iter< - T: IntoIterator>, - >( - iter: T, - ) -> Self { + fn from_iter>>(iter: T) -> Self { Self::with_children(iter) } } @@ -241,9 +224,7 @@ where size.height, self.padding, |limits| c.0.as_widget().layout(c.1, renderer, limits), - |content, size| { - content.align(self.align, Alignment::Start, size) - }, + |content, size| content.align(self.align, Alignment::Start, size), ) }) .collect(); @@ -316,9 +297,9 @@ where .zip(&tree.children) .zip(layout.children()) .map(|((child, state), layout)| { - child.as_widget().mouse_interaction( - state, layout, cursor, viewport, renderer, - ) + child + .as_widget() + .mouse_interaction(state, layout, cursor, viewport, renderer) }) .max() .unwrap_or_default() @@ -348,9 +329,9 @@ where .zip(layout.children()) .filter(|(_, layout)| layout.bounds().intersects(viewport)) { - child.as_widget().draw( - state, renderer, theme, style, layout, cursor, viewport, - ); + child + .as_widget() + .draw(state, renderer, theme, style, layout, cursor, viewport); } } } @@ -362,13 +343,7 @@ where renderer: &Renderer, translation: Vector, ) -> Option> { - overlay::from_children( - &mut self.children, - tree, - layout, - renderer, - translation, - ) + overlay::from_children(&mut self.children, tree, layout, renderer, translation) } #[cfg(feature = "a11y")] @@ -385,9 +360,7 @@ where .iter() .zip(layout.children()) .zip(state.children.iter()) - .map(|((c, c_layout), state)| { - c.as_widget().a11y_nodes(c_layout, state, cursor) - }), + .map(|((c, c_layout), state)| c.as_widget().a11y_nodes(c_layout, state, cursor)), ) } @@ -404,27 +377,20 @@ where .zip(layout.children()) .zip(state.children.iter()) { - e.as_widget().drag_destinations( - state, - layout, - renderer, - dnd_rectangles, - ); + e.as_widget() + .drag_destinations(state, layout, renderer, dnd_rectangles); } } } -impl<'a, Message, Theme, Renderer> - From> +impl<'a, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where Message: 'a, Theme: 'a, Renderer: iced::core::Renderer + 'a, { - fn from( - SubsurfaceContainer: SubsurfaceContainer<'a, Message, Theme, Renderer>, - ) -> Self { + fn from(SubsurfaceContainer: SubsurfaceContainer<'a, Message, Theme, Renderer>) -> Self { Self::new(SubsurfaceContainer) } } diff --git a/examples/sctk_subsurface/src/wayland.rs b/examples/sctk_subsurface/src/wayland.rs index f43a77a32f..8bd863c443 100644 --- a/examples/sctk_subsurface/src/wayland.rs +++ b/examples/sctk_subsurface/src/wayland.rs @@ -123,9 +123,7 @@ fn create_memfile() -> rustix::io::Result { time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos() ); - match rustix::io::retry_on_intr(|| { - rustix::shm::shm_open(&name, flags, 0600.into()) - }) { + match rustix::io::retry_on_intr(|| rustix::shm::shm_open(&name, flags, 0600.into())) { Ok(fd) => match rustix::shm::shm_unlink(&name) { Ok(_) => return Ok(fd), Err(errno) => { diff --git a/examples/sctk_subsurface_gst/src/pipewire.rs b/examples/sctk_subsurface_gst/src/pipewire.rs index a179bf1ff5..42908db9b8 100644 --- a/examples/sctk_subsurface_gst/src/pipewire.rs +++ b/examples/sctk_subsurface_gst/src/pipewire.rs @@ -62,10 +62,7 @@ pub fn subscription(path: &str) -> iced::Subscription { ) } -fn pipewire_thread( - path: &str, - mut sender: futures_channel::mpsc::Sender, -) { +fn pipewire_thread(path: &str, mut sender: futures_channel::mpsc::Sender) { gst::init().unwrap(); let pipeline = gst::parse::launch(&format!( @@ -114,8 +111,7 @@ fn pipewire_thread( appsink.set_callbacks( gst_app::AppSinkCallbacks::builder() .new_sample(move |appsink| { - let sample = - appsink.pull_sample().map_err(|_| gst::FlowError::Eos)?; + let sample = appsink.pull_sample().map_err(|_| gst::FlowError::Eos)?; let buffer = sample.buffer().unwrap(); let meta = buffer.meta::().unwrap(); @@ -166,8 +162,7 @@ fn pipewire_thread( buffer_source }; - let (buffer, new_subsurface_release) = - SubsurfaceBuffer::new(buffer_source); + let (buffer, new_subsurface_release) = SubsurfaceBuffer::new(buffer_source); block_on(sender.send(Event::Frame(buffer))).unwrap(); // Wait for server to release other buffer diff --git a/examples/sctk_subsurface_img/Cargo.toml b/examples/sctk_subsurface_img/Cargo.toml index 6ac531c17b..d600e80ac6 100644 --- a/examples/sctk_subsurface_img/Cargo.toml +++ b/examples/sctk_subsurface_img/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] iced = { path = "../..", default-features = false, features = [ "tokio", - "wayland", + "cctk", "winit", "debug", "tiny-skia", diff --git a/examples/sctk_subsurface_img/src/main.rs b/examples/sctk_subsurface_img/src/main.rs index 114e8407ae..996ca6a7cf 100644 --- a/examples/sctk_subsurface_img/src/main.rs +++ b/examples/sctk_subsurface_img/src/main.rs @@ -1,8 +1,6 @@ use cctk::sctk::reexports::client::protocol::wl_shm; use iced::{ - platform_specific::shell::subsurface_widget::{ - self, Shmbuf, SubsurfaceBuffer, - }, + platform_specific::shell::subsurface_widget::{self, Shmbuf, SubsurfaceBuffer}, window::{self, Id, Settings}, Element, Subscription, Task, }; @@ -29,12 +27,13 @@ fn main() -> iced::Result { } iced::daemon( - SubsurfaceApp::title, + move || SubsurfaceApp::new(path.clone()), SubsurfaceApp::update, SubsurfaceApp::view, ) + .title(SubsurfaceApp::title) .subscription(SubsurfaceApp::subscription) - .run_with(|| SubsurfaceApp::new(path)) + .run() } #[derive(Debug, Clone)] @@ -105,7 +104,7 @@ impl SubsurfaceApp { Task::none() } - fn view(&self, _id: window::Id) -> Element { + fn view(&self, _id: window::Id) -> Element<'_, Message> { let image: Element<_> = if self.use_subsurface { subsurface_widget::Subsurface::new(self.buffer.clone()) .content_fit(iced::ContentFit::None) @@ -120,15 +119,12 @@ impl SubsurfaceApp { fn subscription(&self) -> Subscription { iced::event::listen_with(|evt, _status, _id| match evt { - iced::Event::Keyboard(iced::keyboard::Event::KeyReleased { - key, - .. - }) => match key { - iced::keyboard::Key::Character( - " ".into() - ) => Some(Message::Toggle), - _ => None, - }, + iced::Event::Keyboard(iced::keyboard::Event::KeyReleased { key, .. }) => { + match key.as_ref() { + iced::keyboard::Key::Character(" ") => Some(Message::Toggle), + _ => None, + } + } _ => None, }) } @@ -144,9 +140,7 @@ fn create_memfile() -> rustix::io::Result { time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos() ); - match rustix::io::retry_on_intr(|| { - rustix::shm::shm_open(&name, flags, 0600.into()) - }) { + match rustix::io::retry_on_intr(|| rustix::shm::shm_open(&name, flags, 0600.into())) { Ok(fd) => match rustix::shm::shm_unlink(&name) { Ok(_) => return Ok(fd), Err(errno) => { diff --git a/examples/sctk_todos/src/main.rs b/examples/sctk_todos/src/main.rs index cf27529a97..9ad1ea04ec 100644 --- a/examples/sctk_todos/src/main.rs +++ b/examples/sctk_todos/src/main.rs @@ -7,8 +7,7 @@ use iced::platform_specific::shell::commands::{ }; use iced::theme::{self, Theme}; use iced::widget::{ - self, button, checkbox, column, container, row, scrollable, text, - text_input, Text, + self, button, checkbox, column, container, row, scrollable, text, text_input, Text, }; use iced::window::Settings; use iced::{window, Application, Element, Program, Task}; @@ -149,9 +148,7 @@ impl Todos { } Message::CreateTask => { if !state.input_value.is_empty() { - state - .tasks - .push(MyTask::new(state.input_value.clone())); + state.tasks.push(MyTask::new(state.input_value.clone())); state.input_value.clear(); } Task::none() @@ -168,8 +165,7 @@ impl Todos { } Message::TaskMessage(i, task_message) => { if let Some(task) = state.tasks.get_mut(i) { - let should_focus = - matches!(task_message, TaskMessage::Edit); + let should_focus = matches!(task_message, TaskMessage::Edit); task.update(task_message); @@ -255,8 +251,7 @@ impl Todos { .on_paste(Message::InputChanged); let controls = view_controls(tasks, *filter); - let filtered_tasks = - tasks.iter().filter(|task| filter.matches(task)); + let filtered_tasks = tasks.iter().filter(|task| filter.matches(task)); let tasks: Element<_> = if filtered_tasks.count() > 0 { column( @@ -265,9 +260,8 @@ impl Todos { .enumerate() .filter(|(_, task)| filter.matches(task)) .map(|(i, task)| { - task.view(i).map(move |message| { - Message::TaskMessage(i, message) - }) + task.view(i) + .map(move |message| Message::TaskMessage(i, message)) }) .collect::>(), ) @@ -277,9 +271,7 @@ impl Todos { empty_message(match filter { Filter::All => "You have not created a task yet...", Filter::Active => "All your tasks are done! :D", - Filter::Completed => { - "You have not completed a task yet..." - } + Filter::Completed => "You have not completed a task yet...", }) }; @@ -421,13 +413,12 @@ impl MyTask { .into() } TaskState::Editing => { - let text_input = - text_input("Describe your task...", &self.description) - .id(Self::text_input_id(i)) - .on_submit(TaskMessage::FinishEdition) - .on_input(TaskMessage::DescriptionEdited) - .on_paste(TaskMessage::DescriptionEdited) - .padding(10); + let text_input = text_input("Describe your task...", &self.description) + .id(Self::text_input_id(i)) + .on_submit(TaskMessage::FinishEdition) + .on_input(TaskMessage::DescriptionEdited) + .on_paste(TaskMessage::DescriptionEdited) + .padding(10); row![ text_input, @@ -598,8 +589,7 @@ impl SavedState { async fn save(self) -> Result<(), SaveError> { use async_std::prelude::*; - let json = serde_json::to_string_pretty(&self) - .map_err(|_| SaveError::Format)?; + let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; let path = Self::path(); @@ -648,8 +638,7 @@ impl SavedState { async fn save(self) -> Result<(), SaveError> { let storage = Self::storage().ok_or(SaveError::File)?; - let json = serde_json::to_string_pretty(&self) - .map_err(|_| SaveError::Format)?; + let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; storage .set_item("state", &json) diff --git a/examples/sierpinski_triangle/src/main.rs b/examples/sierpinski_triangle/src/main.rs index f6911c2939..8cd8192a8e 100644 --- a/examples/sierpinski_triangle/src/main.rs +++ b/examples/sierpinski_triangle/src/main.rs @@ -1,9 +1,7 @@ use iced::mouse; use iced::widget::canvas::{self, Canvas, Event, Geometry}; use iced::widget::{column, row, slider, text}; -use iced::{ - Center, Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme, -}; +use iced::{Center, Color, Element, Fill, Point, Rectangle, Renderer, Size, Theme}; use rand::Rng; use std::fmt::Debug; @@ -85,12 +83,10 @@ impl canvas::Program for SierpinskiGraph { match event { Event::Mouse(mouse::Event::ButtonPressed(button)) => match button { - mouse::Button::Left => Some(canvas::Action::publish( - Message::PointAdded(cursor_position), - )), - mouse::Button::Right => { - Some(canvas::Action::publish(Message::PointRemoved)) - } + mouse::Button::Left => Some(canvas::Action::publish(Message::PointAdded( + cursor_position, + ))), + mouse::Button::Right => Some(canvas::Action::publish(Message::PointRemoved)), _ => None, }, _ => None, @@ -143,8 +139,7 @@ impl SierpinskiGraph { } fn gen_rand_point(&self, last: Option) -> Point { - let dest_point_idx = - rand::thread_rng().gen_range(0..self.fix_points.len()); + let dest_point_idx = rand::thread_rng().gen_range(0..self.fix_points.len()); let dest_point = self.fix_points[dest_point_idx]; let cur_point = last.or_else(|| Some(self.fix_points[0])).unwrap(); diff --git a/examples/solar_system/src/main.rs b/examples/solar_system/src/main.rs index 958fc672ec..0c172f4f18 100644 --- a/examples/solar_system/src/main.rs +++ b/examples/solar_system/src/main.rs @@ -11,10 +11,7 @@ use iced::widget::canvas::stroke::{self, Stroke}; use iced::widget::canvas::{Geometry, Path}; use iced::widget::{canvas, image}; use iced::window; -use iced::{ - Color, Element, Fill, Point, Rectangle, Renderer, Size, Subscription, - Theme, Vector, -}; +use iced::{Color, Element, Fill, Point, Rectangle, Renderer, Size, Subscription, Theme, Vector}; use std::time::Instant; @@ -92,15 +89,9 @@ impl State { let size = window::Settings::default().size; State { - sun: image::Handle::from_bytes( - include_bytes!("../assets/sun.png").as_slice(), - ), - earth: image::Handle::from_bytes( - include_bytes!("../assets/earth.png").as_slice(), - ), - moon: image::Handle::from_bytes( - include_bytes!("../assets/moon.png").as_slice(), - ), + sun: image::Handle::from_bytes(include_bytes!("../assets/sun.png").as_slice()), + earth: image::Handle::from_bytes(include_bytes!("../assets/earth.png").as_slice()), + moon: image::Handle::from_bytes(include_bytes!("../assets/moon.png").as_slice()), space_cache: canvas::Cache::default(), system_cache: canvas::Cache::default(), start: now, @@ -147,28 +138,24 @@ impl canvas::Program for State { ) -> Vec { use std::f32::consts::PI; - let background = - self.space_cache.draw(renderer, bounds.size(), |frame| { - frame.fill_rectangle(Point::ORIGIN, frame.size(), Color::BLACK); + let background = self.space_cache.draw(renderer, bounds.size(), |frame| { + frame.fill_rectangle(Point::ORIGIN, frame.size(), Color::BLACK); - let stars = Path::new(|path| { - for (p, size) in &self.stars { - path.rectangle(*p, Size::new(*size, *size)); - } - }); - - frame.translate(frame.center() - Point::ORIGIN); - frame.fill(&stars, Color::WHITE); + let stars = Path::new(|path| { + for (p, size) in &self.stars { + path.rectangle(*p, Size::new(*size, *size)); + } }); + frame.translate(frame.center() - Point::ORIGIN); + frame.fill(&stars, Color::WHITE); + }); + let system = self.system_cache.draw(renderer, bounds.size(), |frame| { let center = frame.center(); frame.translate(Vector::new(center.x, center.y)); - frame.draw_image( - Rectangle::with_radius(Self::SUN_RADIUS), - &self.sun, - ); + frame.draw_image(Rectangle::with_radius(Self::SUN_RADIUS), &self.sun); let orbit = Path::circle(Point::ORIGIN, Self::ORBIT_RADIUS); frame.stroke( @@ -199,10 +186,7 @@ impl canvas::Program for State { frame.rotate(rotation * 10.0); frame.translate(Vector::new(0.0, Self::MOON_DISTANCE)); - frame.draw_image( - Rectangle::with_radius(Self::MOON_RADIUS), - &self.moon, - ); + frame.draw_image(Rectangle::with_radius(Self::MOON_RADIUS), &self.moon); }); vec![background, system] diff --git a/examples/stopwatch/src/main.rs b/examples/stopwatch/src/main.rs index 1fbec9a044..7f8060c96d 100644 --- a/examples/stopwatch/src/main.rs +++ b/examples/stopwatch/src/main.rs @@ -59,9 +59,7 @@ impl Stopwatch { fn subscription(&self) -> Subscription { let tick = match self.state { State::Idle => Subscription::none(), - State::Ticking { .. } => { - time::every(milliseconds(10)).map(Message::Tick) - } + State::Ticking { .. } => time::every(milliseconds(10)).map(Message::Tick), }; fn handle_hotkey(event: keyboard::Event) -> Option { @@ -72,18 +70,13 @@ impl Stopwatch { }; match modified_key.as_ref() { - keyboard::Key::Named(key::Named::Space) => { - Some(Message::Toggle) - } + keyboard::Key::Named(key::Named::Space) => Some(Message::Toggle), keyboard::Key::Character("r") => Some(Message::Reset), _ => None, } } - Subscription::batch(vec![ - tick, - keyboard::listen().filter_map(handle_hotkey), - ]) + Subscription::batch(vec![tick, keyboard::listen().filter_map(handle_hotkey)]) } fn view(&self) -> Element<'_, Message> { @@ -101,8 +94,7 @@ impl Stopwatch { ) .size(40); - let button = - |label| button(text(label).align_x(Center)).padding(10).width(80); + let button = |label| button(text(label).align_x(Center)).padding(10).width(80); let toggle_button = { let label = match self.state { diff --git a/examples/styling/src/main.rs b/examples/styling/src/main.rs index fe10e4b7a0..cfcd113eac 100644 --- a/examples/styling/src/main.rs +++ b/examples/styling/src/main.rs @@ -1,8 +1,7 @@ use iced::keyboard; use iced::widget::{ - button, center_x, center_y, checkbox, column, container, pick_list, - progress_bar, row, rule, scrollable, slider, space, text, text_input, - toggler, + button, center_x, center_y, checkbox, column, container, pick_list, progress_bar, row, rule, + scrollable, slider, space, text, text_input, toggler, }; use iced::{Center, Element, Fill, Shrink, Subscription, Theme}; @@ -47,14 +46,13 @@ impl Styling { Message::CheckboxToggled(value) => self.checkbox_value = value, Message::TogglerToggled(value) => self.toggler_value = value, Message::PreviousTheme | Message::NextTheme => { - let current = Theme::ALL.iter().position(|candidate| { - self.theme.as_ref() == Some(candidate) - }); + let current = Theme::ALL + .iter() + .position(|candidate| self.theme.as_ref() == Some(candidate)); self.theme = Some(if matches!(message, Message::NextTheme) { - Theme::ALL[current.map(|current| current + 1).unwrap_or(0) - % Theme::ALL.len()] - .clone() + Theme::ALL[current.map(|current| current + 1).unwrap_or(0) % Theme::ALL.len()] + .clone() } else { let current = current.unwrap_or(0); @@ -97,42 +95,32 @@ impl Styling { ("Danger", button::danger), ]; - let styled_button = - |label| button(text(label).width(Fill).center()).padding(10); + let styled_button = |label| button(text(label).width(Fill).center()).padding(10); column![ - row(styles.into_iter().map(|(name, style)| styled_button( - name - ) - .on_press(Message::ButtonPressed) - .style(style) - .into())) + row(styles.into_iter().map(|(name, style)| styled_button(name) + .on_press(Message::ButtonPressed) + .style(style) + .into())) .spacing(10) .align_y(Center), - row(styles.into_iter().map(|(name, style)| styled_button( - name - ) - .style(style) - .into())) + row(styles + .into_iter() + .map(|(name, style)| styled_button(name).style(style).into())) .spacing(10) .align_y(Center), ] .spacing(10) }; - let slider = - || slider(0.0..=100.0, self.slider_value, Message::SliderChanged); + let slider = || slider(0.0..=100.0, self.slider_value, Message::SliderChanged); let progress_bar = || progress_bar(0.0..=100.0, self.slider_value); - let scroll_me = scrollable(column![ - "Scroll me!", - space().height(800), - "You did it!" - ]) - .width(Fill) - .height(Fill) - .auto_scroll(true); + let scroll_me = scrollable(column!["Scroll me!", space().height(800), "You did it!"]) + .width(Fill) + .height(Fill) + .auto_scroll(true); let check = checkbox(self.checkbox_value) .label("Check me!") @@ -145,21 +133,13 @@ impl Styling { .on_toggle(Message::TogglerToggled) .spacing(10); - let disabled_toggle = - toggler(self.toggler_value).label("Disabled").spacing(10); + let disabled_toggle = toggler(self.toggler_value).label("Disabled").spacing(10); let card = { - container( - column![ - text("Card Example").size(24), - slider(), - progress_bar(), - ] - .spacing(20), - ) - .width(Fill) - .padding(20) - .style(container::bordered_box) + container(column![text("Card Example").size(24), slider(), progress_bar(),].spacing(20)) + .width(Fill) + .padding(20) + .style(container::bordered_box) }; let content = column![ @@ -172,8 +152,7 @@ impl Styling { row![ scroll_me, rule::vertical(1), - column![check, check_disabled, toggle, disabled_toggle] - .spacing(10) + column![check, check_disabled, toggle, disabled_toggle].spacing(10) ] .spacing(10) .height(Shrink) @@ -201,12 +180,12 @@ impl Styling { }; match modified_key { - keyboard::key::Named::ArrowUp - | keyboard::key::Named::ArrowLeft => { + keyboard::key::Named::ArrowUp | keyboard::key::Named::ArrowLeft => { Some(Message::PreviousTheme) } - keyboard::key::Named::ArrowDown - | keyboard::key::Named::ArrowRight => Some(Message::NextTheme), + keyboard::key::Named::ArrowDown | keyboard::key::Named::ArrowRight => { + Some(Message::NextTheme) + } keyboard::key::Named::Space => Some(Message::ClearTheme), _ => None, } @@ -241,10 +220,7 @@ mod tests { assert!( snapshot.matches_hash(format!( "snapshots/{theme}", - theme = theme - .to_string() - .to_ascii_lowercase() - .replace(" ", "_") + theme = theme.to_string().to_ascii_lowercase().replace(" ", "_") ))?, "snapshots for {theme} should match!" ); diff --git a/examples/svg/src/main.rs b/examples/svg/src/main.rs index 06c1314faf..9c853f058d 100644 --- a/examples/svg/src/main.rs +++ b/examples/svg/src/main.rs @@ -25,17 +25,16 @@ impl Tiger { } fn view(&self) -> Element<'_, Message> { - let svg = - svg(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/tiger.svg")) - .width(Fill) - .height(Fill) - .style(|_theme, _status| svg::Style { - color: if self.apply_color_filter { - Some(color!(0x0000ff)) - } else { - None - }, - }); + let svg = svg(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/tiger.svg")) + .width(Fill) + .height(Fill) + .style(|_theme, _status| svg::Style { + color: if self.apply_color_filter { + Some(color!(0x0000ff)) + } else { + None + }, + }); let apply_color_filter = checkbox(self.apply_color_filter) .label("Apply a color filter") diff --git a/examples/table/src/main.rs b/examples/table/src/main.rs index 7a1d6be25d..ccfc2a396c 100644 --- a/examples/table/src/main.rs +++ b/examples/table/src/main.rs @@ -1,8 +1,7 @@ use iced::font; use iced::time::{Duration, hours, minutes}; use iced::widget::{ - center_x, center_y, column, container, row, scrollable, slider, table, - text, tooltip, + center_x, center_y, column, container, row, scrollable, slider, table, text, tooltip, }; use iced::{Center, Element, Fill, Font, Right, Theme}; @@ -64,13 +63,11 @@ impl Table { .align_y(Center), table::column(bold("Price"), |event: &Event| { if event.price > 0.0 { - text!("${:.2}", event.price).style( - if event.price > 100.0 { - text::warning - } else { - text::default - }, - ) + text!("${:.2}", event.price).style(if event.price > 100.0 { + text::warning + } else { + text::default + }) } else { text("Free").style(text::success).width(Fill).center() } @@ -121,12 +118,7 @@ impl Table { }; column![ - labeled_slider( - "Padding", - 0.0..=30.0, - self.padding, - Message::PaddingChanged - ), + labeled_slider("Padding", 0.0..=30.0, self.padding, Message::PaddingChanged), labeled_slider( "Separator", 0.0..=5.0, @@ -205,8 +197,7 @@ impl Event { rating: 4.7, }, Event { - name: "Try to order at a secret ramen place with no sign" - .to_owned(), + name: "Try to order at a secret ramen place with no sign".to_owned(), duration: minutes(50), price: 14.0, rating: 4.6, diff --git a/examples/the_matrix/src/main.rs b/examples/the_matrix/src/main.rs index 6bf3447d5f..31fe31d14c 100644 --- a/examples/the_matrix/src/main.rs +++ b/examples/the_matrix/src/main.rs @@ -1,9 +1,7 @@ use iced::mouse; use iced::time::{self, milliseconds}; use iced::widget::canvas; -use iced::{ - Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme, -}; +use iced::{Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme}; use std::cell::RefCell; @@ -67,10 +65,8 @@ impl canvas::Program for TheMatrix { caches.resize_with(30, || canvas::Cache::with_group(group)); } - vec![caches[self.tick % caches.len()].draw( - renderer, - bounds.size(), - |frame| { + 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(); @@ -79,16 +75,13 @@ impl canvas::Program for TheMatrix { 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 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"); + let distribution = rand::distributions::WeightedIndex::new(weights) + .expect("Create distribution"); frame.fill_text(canvas::Text { content: rng.gen_range('!'..'z').to_string(), @@ -104,7 +97,7 @@ impl canvas::Program for TheMatrix { }); } } - }, - )] + }), + ] } } diff --git a/examples/toast/src/main.rs b/examples/toast/src/main.rs index 3b06346b0e..2013249ae5 100644 --- a/examples/toast/src/main.rs +++ b/examples/toast/src/main.rs @@ -1,9 +1,7 @@ use iced::event::{self, Event}; use iced::keyboard; use iced::keyboard::key; -use iced::widget::{ - button, center, column, operation, pick_list, row, slider, text, text_input, -}; +use iced::widget::{button, center, column, operation, pick_list, row, slider, text, text_input}; use iced::{Center, Element, Fill, Subscription, Task}; use toast::{Status, Toast}; @@ -52,9 +50,7 @@ impl App { fn update(&mut self, message: Message) -> Task { match message { Message::Add => { - if !self.editing.title.is_empty() - && !self.editing.body.is_empty() - { + if !self.editing.title.is_empty() && !self.editing.body.is_empty() { self.toasts.push(std::mem::take(&mut self.editing)); } Task::none() @@ -132,12 +128,7 @@ impl App { "Timeout", row![ text!("{:0>2} sec", self.timeout_secs), - slider( - 1.0..=30.0, - self.timeout_secs as f64, - Message::Timeout - ) - .step(1.0) + slider(1.0..=30.0, self.timeout_secs as f64, Message::Timeout).step(1.0) ] .spacing(5) .into() @@ -166,17 +157,15 @@ mod toast { use iced::advanced::layout::{self, Layout}; use iced::advanced::overlay; use iced::advanced::renderer; - use iced::advanced::widget::{ - self, Operation, OperationOutputWrapper, Tree, - }; + use iced::advanced::widget::{self, Operation, OperationOutputWrapper, Tree}; use iced::advanced::{Clipboard, Shell, Widget}; use iced::mouse; use iced::time::{self, Duration, Instant}; use iced::widget::{button, column, container, row, rule, space, text}; use iced::window; use iced::{ - Alignment, Center, Element, Event, Fill, Length, Point, Rectangle, - Renderer, Size, Theme, Vector, + Alignment, Center, Element, Event, Fill, Length, Point, Rectangle, Renderer, Size, Theme, + Vector, }; pub const DEFAULT_TIMEOUT: u64 = 5; @@ -246,9 +235,7 @@ mod toast { row![ text(toast.title.as_str()), space::horizontal(), - button("X") - .on_press((on_close)(index)) - .padding(3), + button("X").on_press((on_close)(index)).padding(3), ] .align_y(Center) ) @@ -299,11 +286,9 @@ mod toast { renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { - self.content.as_widget_mut().layout( - &mut tree.children[0], - renderer, - limits, - ) + self.content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) } fn tag(&self) -> widget::tree::Tag { @@ -334,10 +319,7 @@ mod toast { instants.truncate(new); } (old, new) if old < new => { - instants.extend(std::iter::repeat_n( - Some(Instant::now()), - new - old, - )); + instants.extend(std::iter::repeat_n(Some(Instant::now()), new - old)); } _ => {} } @@ -459,11 +441,9 @@ mod toast { timeout_secs: self.timeout_secs, })) }); - let overlays = - content.into_iter().chain(toasts).collect::>(); + let overlays = content.into_iter().chain(toasts).collect::>(); - (!overlays.is_empty()) - .then(|| overlay::Group::with_children(overlays).overlay()) + (!overlays.is_empty()).then(|| overlay::Group::with_children(overlays).overlay()) } } @@ -477,14 +457,8 @@ mod toast { timeout_secs: u64, } - impl overlay::Overlay - for Overlay<'_, '_, Message> - { - fn layout( - &mut self, - renderer: &Renderer, - bounds: Size, - ) -> layout::Node { + impl overlay::Overlay for Overlay<'_, '_, Message> { + fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { let limits = layout::Limits::new(Size::ZERO, bounds); layout::flex::resolve( @@ -512,11 +486,13 @@ mod toast { shell: &mut Shell<'_, Message>, ) { if let Event::Window(window::Event::RedrawRequested(now)) = &event { - self.instants.iter_mut().enumerate().for_each( - |(index, maybe_instant)| { + self.instants + .iter_mut() + .enumerate() + .for_each(|(index, maybe_instant)| { if let Some(instant) = maybe_instant.as_mut() { - let remaining = time::seconds(self.timeout_secs) - .saturating_sub(instant.elapsed()); + let remaining = + time::seconds(self.timeout_secs).saturating_sub(instant.elapsed()); if remaining == Duration::ZERO { maybe_instant.take(); @@ -525,8 +501,7 @@ mod toast { shell.request_redraw_at(*now + remaining); } } - }, - ); + }); } let viewport = layout.bounds(); @@ -576,9 +551,9 @@ mod toast { .zip(self.trees.iter()) .zip(layout.children()) { - child.as_widget().draw( - tree, renderer, theme, style, layout, cursor, &viewport, - ); + child + .as_widget() + .draw(tree, renderer, theme, style, layout, cursor, &viewport); } } @@ -615,13 +590,7 @@ mod toast { .map(|((child, state), layout)| { child .as_widget() - .mouse_interaction( - state, - layout, - cursor, - &self.viewport, - renderer, - ) + .mouse_interaction(state, layout, cursor, &self.viewport, renderer) .max(if cursor.is_over(layout.bounds()) { mouse::Interaction::Idle } else { diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 2e3722b190..309dd9472c 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -1,12 +1,12 @@ use iced::keyboard; use iced::widget::{ - self, Text, button, center, center_x, checkbox, column, keyed_column, - operation, row, scrollable, text, text_input, + self, Text, button, center, center_x, checkbox, column, keyed_column, operation, row, + scrollable, text, text_input, }; use iced::window; use iced::{ - Center, Element, Fill, Font, Function, Preset, Program, Subscription, - Task as Command, Theme, application::Application, + Center, Element, Fill, Font, Function, Preset, Program, Subscription, Task as Command, Theme, + application::Application, }; use serde::{Deserialize, Serialize}; @@ -19,8 +19,7 @@ pub fn main() -> iced::Result { application().run() } -fn application() -> Application> -{ +fn application() -> Application> { iced::application(Todos::new, Todos::update, Todos::view) .subscription(Todos::subscription) .title(Todos::title) @@ -106,9 +105,7 @@ impl Todos { } Message::CreateTask => { if !state.input_value.is_empty() { - state - .tasks - .push(Task::new(state.input_value.clone())); + state.tasks.push(Task::new(state.input_value.clone())); state.input_value.clear(); } @@ -126,8 +123,7 @@ impl Todos { } Message::TaskMessage(i, task_message) => { if let Some(task) = state.tasks.get_mut(i) { - let should_focus = - matches!(task_message, TaskMessage::Edit); + let should_focus = matches!(task_message, TaskMessage::Edit); task.update(task_message); @@ -157,8 +153,9 @@ impl Todos { operation::focus_next() } } - Message::ToggleFullscreen(mode) => window::latest() - .and_then(move |window| window::set_mode(window, mode)), + Message::ToggleFullscreen(mode) => { + window::latest().and_then(move |window| window::set_mode(window, mode)) + } Message::Loaded(_) => Command::none(), }; @@ -212,8 +209,7 @@ impl Todos { .align_x(Center); let controls = view_controls(tasks, *filter); - let filtered_tasks = - tasks.iter().filter(|task| filter.matches(task)); + let filtered_tasks = tasks.iter().filter(|task| filter.matches(task)); let tasks: Element<_> = if filtered_tasks.count() > 0 { keyed_column( @@ -222,11 +218,7 @@ impl Todos { .enumerate() .filter(|(_, task)| filter.matches(task)) .map(|(i, task)| { - ( - task.id, - task.view(i) - .map(Message::TaskMessage.with(i)), - ) + (task.id, task.view(i).map(Message::TaskMessage.with(i))) }), ) .spacing(10) @@ -235,9 +227,7 @@ impl Todos { empty_message(match filter { Filter::All => "You have not created a task yet...", Filter::Active => "All your tasks are done! :D", - Filter::Completed => { - "You have not completed a task yet..." - } + Filter::Completed => "You have not completed a task yet...", }) }; @@ -358,23 +348,18 @@ impl Task { .into() } TaskState::Editing => { - let text_input = - text_input("Describe your task...", &self.description) - .id(Self::text_input_id(i)) - .on_input(TaskMessage::DescriptionEdited) - .on_submit(TaskMessage::FinishEdition) - .padding(10); + let text_input = text_input("Describe your task...", &self.description) + .id(Self::text_input_id(i)) + .on_input(TaskMessage::DescriptionEdited) + .on_submit(TaskMessage::FinishEdition) + .padding(10); row![ text_input, - button( - row![delete_icon(), "Delete"] - .spacing(10) - .align_y(Center) - ) - .on_press(TaskMessage::Delete) - .padding(10) - .style(button::danger) + button(row![delete_icon(), "Delete"].spacing(10).align_y(Center)) + .on_press(TaskMessage::Delete) + .padding(10) + .style(button::danger) ] .spacing(20) .align_y(Center) @@ -384,10 +369,7 @@ impl Task { } } -fn view_controls( - tasks: &[Task], - current_filter: Filter, -) -> Element<'_, Message> { +fn view_controls(tasks: &[Task], current_filter: Filter) -> Element<'_, Message> { let tasks_left = tasks.iter().filter(|task| !task.completed).count(); let filter_button = |label, filter, current_filter| { @@ -420,9 +402,7 @@ fn view_controls( .into() } -#[derive( - Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, -)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum Filter { #[default] All, @@ -503,13 +483,12 @@ enum SaveError { #[cfg(not(target_arch = "wasm32"))] impl SavedState { fn path() -> std::path::PathBuf { - let mut path = if let Some(project_dirs) = - directories::ProjectDirs::from("rs", "Iced", "Todos") - { - project_dirs.data_dir().into() - } else { - std::env::current_dir().unwrap_or_default() - }; + let mut path = + if let Some(project_dirs) = directories::ProjectDirs::from("rs", "Iced", "Todos") { + project_dirs.data_dir().into() + } else { + std::env::current_dir().unwrap_or_default() + }; path.push("todos.json"); @@ -527,8 +506,7 @@ impl SavedState { async fn save(self) -> Result<(), SaveError> { use iced::time::milliseconds; - let json = serde_json::to_string_pretty(&self) - .map_err(|_| SaveError::Format)?; + let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; let path = Self::path(); @@ -573,15 +551,13 @@ impl SavedState { async fn save(self) -> Result<(), SaveError> { let storage = Self::storage().ok_or(SaveError::Write)?; - let json = serde_json::to_string_pretty(&self) - .map_err(|_| SaveError::Format)?; + let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?; storage .set_item("state", &json) .map_err(|_| SaveError::Write)?; - let _ = - wasmtimer::tokio::sleep(std::time::Duration::from_secs(2)).await; + let _ = wasmtimer::tokio::sleep(std::time::Duration::from_secs(2)).await; Ok(()) } diff --git a/examples/tooltip/src/main.rs b/examples/tooltip/src/main.rs index b38e7af1df..5ca24b4a2e 100644 --- a/examples/tooltip/src/main.rs +++ b/examples/tooltip/src/main.rs @@ -42,8 +42,7 @@ impl Tooltip { fn view(&self) -> Element<'_, Message> { let tooltip = tooltip( - button("Press to change position") - .on_press(Message::ChangePosition), + button("Press to change position").on_press(Message::ChangePosition), position_to_text(self.position), self.position, ) diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index f2d7b55cbb..233db9fcee 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -1,7 +1,7 @@ use iced::widget::{Button, Column, Container, Slider}; use iced::widget::{ - button, center_x, center_y, checkbox, column, image, radio, rich_text, row, - scrollable, slider, space, span, text, text_input, toggler, + button, center_x, center_y, checkbox, column, image, radio, rich_text, row, scrollable, slider, + space, span, text, text_input, toggler, }; use iced::{Center, Color, Element, Fill, Font, Pixels, color}; @@ -147,9 +147,8 @@ impl Tour { .style(button::secondary) }), space::horizontal(), - self.can_continue().then(|| { - padded_button("Next").on_press(Message::NextPressed) - }) + self.can_continue() + .then(|| { padded_button("Next").on_press(Message::NextPressed) }) ]; let screen = match self.screen { @@ -166,8 +165,7 @@ impl Tour { Screen::End => self.end(), }; - let content: Element<_> = - column![screen, controls].max_width(540).spacing(20).into(); + let content: Element<_> = column![screen, controls].max_width(540).spacing(20).into(); let scrollable = scrollable(center_x(if self.debug { content.explain(Color::BLACK) @@ -264,9 +262,7 @@ impl Tour { ); let layout_section: Element<_> = match self.layout { - Layout::Row => { - row![row_radio, column_radio].spacing(self.spacing).into() - } + Layout::Row => row![row_radio, column_radio].spacing(self.spacing).into(), Layout::Column => column![row_radio, column_radio] .spacing(self.spacing) .into(), @@ -337,12 +333,7 @@ impl Tour { .iter() .copied() .map(|language| { - radio( - language, - language, - self.language, - Message::LanguageSelected, - ) + radio(language, language, self.language, Message::LanguageSelected) }) .map(Element::from) ) @@ -400,10 +391,7 @@ impl Tour { "Iced supports scrollable content. Try it out! Find the \ button further below.", ) - .push( - text("Tip: You can use the scrollbar to scroll down faster!") - .size(16), - ) + .push(text("Tip: You can use the scrollbar to scroll down faster!").size(16)) .push(space().height(4096)) .push( text("You are halfway there!") @@ -551,10 +539,7 @@ impl Screen { } } -fn ferris<'a>( - width: u32, - filter_method: image::FilterMethod, -) -> Container<'a, Message> { +fn ferris<'a>(width: u32, filter_method: image::FilterMethod) -> Container<'a, Message> { center_x( // This should go away once we unify resource loading on native // platforms diff --git a/examples/websocket/src/echo.rs b/examples/websocket/src/echo.rs index 85b3caf600..04c8513c8e 100644 --- a/examples/websocket/src/echo.rs +++ b/examples/websocket/src/echo.rs @@ -17,8 +17,7 @@ pub fn connect() -> impl Sipper { const ECHO_SERVER: &str = "ws://127.0.0.1:3030"; let (mut websocket, mut input) = - match async_tungstenite::tokio::connect_async(ECHO_SERVER).await - { + match async_tungstenite::tokio::connect_async(ECHO_SERVER).await { Ok((websocket, _)) => { let (sender, receiver) = mpsc::channel(100); @@ -27,8 +26,7 @@ pub fn connect() -> impl Sipper { (websocket.fuse(), receiver) } Err(_) => { - tokio::time::sleep(tokio::time::Duration::from_secs(1)) - .await; + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; continue; } diff --git a/examples/websocket/src/main.rs b/examples/websocket/src/main.rs index 5292d0e881..0bfe402fd1 100644 --- a/examples/websocket/src/main.rs +++ b/examples/websocket/src/main.rs @@ -1,8 +1,6 @@ mod echo; -use iced::widget::{ - button, center, column, operation, row, scrollable, text, text_input, -}; +use iced::widget::{button, center, column, operation, row, scrollable, text, text_input}; use iced::{Center, Element, Fill, Subscription, Task, color}; pub fn main() -> iced::Result { @@ -87,20 +85,13 @@ impl WebSocket { fn view(&self) -> Element<'_, Message> { let message_log: Element<_> = if self.messages.is_empty() { - center( - text("Your messages will appear here...") - .color(color!(0x888888)), - ) - .into() + center(text("Your messages will appear here...").color(color!(0x888888))).into() } else { - scrollable( - column(self.messages.iter().map(text).map(Element::from)) - .spacing(10), - ) - .id(MESSAGE_LOG) - .height(Fill) - .spacing(10) - .into() + scrollable(column(self.messages.iter().map(text).map(Element::from)).spacing(10)) + .id(MESSAGE_LOG) + .height(Fill) + .spacing(10) + .into() }; let new_message_input = { @@ -108,8 +99,7 @@ impl WebSocket { .on_input(Message::NewMessageChanged) .padding(10); - let mut button = button(text("Send").height(40).align_y(Center)) - .padding([0, 20]); + let mut button = button(text("Send").height(40).align_y(Center)).padding([0, 20]); if matches!(self.state, State::Connected(_)) && let Some(message) = echo::Message::new(&self.new_message) diff --git a/futures/src/backend/default.rs b/futures/src/backend/default.rs index 4418834e9c..3f90b52c3a 100644 --- a/futures/src/backend/default.rs +++ b/futures/src/backend/default.rs @@ -15,17 +15,10 @@ mod platform { #[cfg(all(feature = "smol", not(feature = "tokio"),))] pub use crate::backend::native::smol::*; - #[cfg(all( - feature = "thread-pool", - not(any(feature = "tokio", feature = "smol")) - ))] + #[cfg(all(feature = "thread-pool", not(any(feature = "tokio", feature = "smol"))))] pub use crate::backend::native::thread_pool::*; - #[cfg(not(any( - feature = "tokio", - feature = "smol", - feature = "thread-pool" - )))] + #[cfg(not(any(feature = "tokio", feature = "smol", feature = "thread-pool")))] pub use crate::backend::null::*; } diff --git a/futures/src/backend/native/smol.rs b/futures/src/backend/native/smol.rs index 3080d5ff94..85ebbf239d 100644 --- a/futures/src/backend/native/smol.rs +++ b/futures/src/backend/native/smol.rs @@ -26,9 +26,7 @@ pub mod time { /// /// The first message is produced after a `duration`, and then continues to /// produce more messages every `duration` after that. - pub fn every( - duration: std::time::Duration, - ) -> Subscription { + pub fn every(duration: std::time::Duration) -> Subscription { subscription::from_recipe(Every(duration)) } diff --git a/futures/src/backend/native/tokio.rs b/futures/src/backend/native/tokio.rs index 93600635b6..2fd6b1905e 100644 --- a/futures/src/backend/native/tokio.rs +++ b/futures/src/backend/native/tokio.rs @@ -42,9 +42,7 @@ pub mod time { let start = tokio::time::Instant::now() + *duration; let mut interval = tokio::time::interval_at(start, *duration); - interval.set_missed_tick_behavior( - tokio::time::MissedTickBehavior::Skip, - ); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let stream = { futures::stream::unfold(interval, |mut interval| async move { diff --git a/futures/src/backend/wasm/wasm_bindgen.rs b/futures/src/backend/wasm/wasm_bindgen.rs index 4811e7f412..32a98d2529 100644 --- a/futures/src/backend/wasm/wasm_bindgen.rs +++ b/futures/src/backend/wasm/wasm_bindgen.rs @@ -29,9 +29,7 @@ pub mod time { use futures::stream::StreamExt; let mut interval = wasmtimer::tokio::interval(*duration); - interval.set_missed_tick_behavior( - wasmtimer::tokio::MissedTickBehavior::Skip, - ); + interval.set_missed_tick_behavior(wasmtimer::tokio::MissedTickBehavior::Skip); let stream = { futures::stream::unfold(interval, |mut interval| async move { diff --git a/futures/src/runtime.rs b/futures/src/runtime.rs index e5e8ab7740..8e921222f5 100644 --- a/futures/src/runtime.rs +++ b/futures/src/runtime.rs @@ -22,11 +22,7 @@ pub struct Runtime { impl Runtime where Executor: self::Executor, - Sender: Sink - + Unpin - + MaybeSend - + Clone - + 'static, + Sender: Sink + Unpin + MaybeSend + Clone + 'static, Message: MaybeSend + 'static, { /// Creates a new empty [`Runtime`]. @@ -66,15 +62,12 @@ where use futures::{FutureExt, StreamExt}; let sender = self.sender.clone(); - let future = - stream.map(Ok).forward(sender).map(|result| match result { - Ok(()) => {} - Err(error) => { - log::warn!( - "Stream could not run until completion: {error}" - ); - } - }); + let future = stream.map(Ok).forward(sender).map(|result| match result { + Ok(()) => {} + Err(error) => { + log::warn!("Stream could not run until completion: {error}"); + } + }); self.executor.spawn(future); } @@ -97,9 +90,7 @@ where /// [`Subscription`]: crate::Subscription pub fn track( &mut self, - recipes: impl IntoIterator< - Item = Box>, - >, + recipes: impl IntoIterator>>, ) { let Runtime { executor, @@ -108,9 +99,7 @@ where .. } = self; - let futures = executor.enter(|| { - subscriptions.update(recipes.into_iter(), sender.clone()) - }); + let futures = executor.enter(|| subscriptions.update(recipes.into_iter(), sender.clone())); for future in futures { executor.spawn(future); diff --git a/futures/src/stream.rs b/futures/src/stream.rs index ee9c0c14e0..dfa381774c 100644 --- a/futures/src/stream.rs +++ b/futures/src/stream.rs @@ -8,10 +8,7 @@ use futures::stream::{self, Stream, StreamExt}; /// This is a more ergonomic [`stream::unfold`], which allows you to go /// from the "world of futures" to the "world of streams" by simply looping /// and publishing to an async channel from inside a [`Future`]. -pub fn channel( - size: usize, - f: impl AsyncFnOnce(mpsc::Sender), -) -> impl Stream { +pub fn channel(size: usize, f: impl AsyncFnOnce(mpsc::Sender)) -> impl Stream { let (sender, receiver) = mpsc::channel(size); let runner = stream::once(f(sender)).filter_map(|_| async { None }); diff --git a/futures/src/subscription.rs b/futures/src/subscription.rs index 12ac370418..0e76bc0b14 100644 --- a/futures/src/subscription.rs +++ b/futures/src/subscription.rs @@ -209,9 +209,7 @@ impl Subscription { /// Batches all the provided subscriptions and returns the resulting /// [`Subscription`]. - pub fn batch( - subscriptions: impl IntoIterator>, - ) -> Self { + pub fn batch(subscriptions: impl IntoIterator>) -> Self { Self { recipes: subscriptions .into_iter() @@ -246,10 +244,7 @@ impl Subscription { self.recipe.hash(state); } - fn stream( - self: Box, - input: EventStream, - ) -> BoxStream { + fn stream(self: Box, input: EventStream) -> BoxStream { use futures::StreamExt; let value = self.value; @@ -310,10 +305,7 @@ impl Subscription { self.recipe.hash(state); } - fn stream( - self: Box, - input: EventStream, - ) -> BoxStream { + fn stream(self: Box, input: EventStream) -> BoxStream { use futures::StreamExt; Box::pin(self.recipe.stream(input).map(self.mapper)) @@ -369,10 +361,7 @@ impl Subscription { self.recipe.hash(state); } - fn stream( - self: Box, - input: EventStream, - ) -> BoxStream { + fn stream(self: Box, input: EventStream) -> BoxStream { use futures::StreamExt; use futures::future; @@ -407,18 +396,14 @@ impl Subscription { } /// Creates a [`Subscription`] from a [`Recipe`] describing it. -pub fn from_recipe( - recipe: impl Recipe + 'static, -) -> Subscription { +pub fn from_recipe(recipe: impl Recipe + 'static) -> Subscription { Subscription { recipes: vec![Box::new(recipe)], } } /// Returns the different recipes of the [`Subscription`]. -pub fn into_recipes( - subscription: Subscription, -) -> Vec>> { +pub fn into_recipes(subscription: Subscription) -> Vec>> { subscription.recipes } diff --git a/futures/src/subscription/tracker.rs b/futures/src/subscription/tracker.rs index 6daead24eb..fdc29b2ad4 100644 --- a/futures/src/subscription/tracker.rs +++ b/futures/src/subscription/tracker.rs @@ -59,11 +59,7 @@ impl Tracker { ) -> Vec> where Message: 'static + MaybeSend, - Receiver: 'static - + Sink - + Unpin - + MaybeSend - + Clone, + Receiver: 'static + Sink + Unpin + MaybeSend + Clone, { use futures::stream::StreamExt; @@ -87,16 +83,14 @@ impl Tracker { let (cancel, mut canceled) = futures::channel::oneshot::channel(); // TODO: Use bus if/when it supports async - let (event_sender, event_receiver) = - futures::channel::mpsc::channel(100); + let (event_sender, event_receiver) = futures::channel::mpsc::channel(100); let mut receiver = receiver.clone(); let mut stream = recipe.stream(event_receiver.boxed()); let future = async move { loop { - let select = - futures::future::select(&mut canceled, stream.next()); + let select = futures::future::select(&mut canceled, stream.next()); match select.await { futures::future::Either::Left(_) @@ -144,9 +138,7 @@ impl Tracker { .filter_map(|connection| connection.listener.as_mut()) .for_each(|listener| { if let Err(error) = listener.try_send(event.clone()) { - log::warn!( - "Error sending event to subscription: {error:?}" - ); + log::warn!("Error sending event to subscription: {error:?}"); } }); } diff --git a/graphics/src/cache.rs b/graphics/src/cache.rs index 7db80a012f..f06e0cd881 100644 --- a/graphics/src/cache.rs +++ b/graphics/src/cache.rs @@ -62,8 +62,7 @@ impl Cache { pub fn clear(&self) { let mut state = self.state.borrow_mut(); - let previous = - mem::replace(&mut *state, State::Empty { previous: None }); + let previous = mem::replace(&mut *state, State::Empty { previous: None }); let previous = match previous { State::Empty { previous } => previous, @@ -181,10 +180,5 @@ impl Cached for () { fn load(_cache: &Self::Cache) -> Self {} - fn cache( - self, - _group: Group, - _previous: Option, - ) -> Self::Cache { - } + fn cache(self, _group: Group, _previous: Option) -> Self::Cache {} } diff --git a/graphics/src/compositor.rs b/graphics/src/compositor.rs index ba5698a1b0..dc5a5ab4e9 100644 --- a/graphics/src/compositor.rs +++ b/graphics/src/compositor.rs @@ -55,12 +55,7 @@ pub trait Compositor: Sized { /// Configures a new [`Surface`] with the given dimensions. /// /// [`Surface`]: Self::Surface - fn configure_surface( - &mut self, - surface: &mut Self::Surface, - width: u32, - height: u32, - ); + fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32); /// Returns [`Information`] used by this [`Compositor`]. fn information(&self) -> Information; @@ -102,15 +97,9 @@ pub trait Compositor: Sized { /// /// This is just a convenient super trait of the `raw-window-handle` /// traits. -pub trait Window: - HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static -{ -} +pub trait Window: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static {} -impl Window for T where - T: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static -{ -} +impl Window for T where T: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static {} /// An owned display handle that can be used in a [`Compositor`]. /// @@ -133,9 +122,7 @@ pub enum SurfaceError { #[error("A timeout was encountered while trying to acquire the next frame")] Timeout, /// The underlying surface has changed, and therefore the surface must be updated. - #[error( - "The underlying surface has changed, and therefore the surface must be updated." - )] + #[error("The underlying surface has changed, and therefore the surface must be updated.")] Outdated, /// The swap chain has been lost and needs to be recreated. #[error("The surface has been lost and needs to be recreated")] @@ -194,13 +181,7 @@ impl Compositor for () { ) -> Self::Surface { } - fn configure_surface( - &mut self, - _surface: &mut Self::Surface, - _width: u32, - _height: u32, - ) { - } + fn configure_surface(&mut self, _surface: &mut Self::Surface, _width: u32, _height: u32) {} fn load_font(&mut self, _font: Cow<'static, [u8]>) {} diff --git a/graphics/src/geometry/cache.rs b/graphics/src/geometry/cache.rs index e17506a30f..55010bbba8 100644 --- a/graphics/src/geometry/cache.rs +++ b/graphics/src/geometry/cache.rs @@ -84,9 +84,7 @@ where let state = self.raw.state(); let previous = match state.borrow().deref() { - cache::State::Empty { previous } => { - previous.as_ref().map(|data| data.geometry.clone()) - } + cache::State::Empty { previous } => previous.as_ref().map(|data| data.geometry.clone()), cache::State::Filled { current } => { if current.bounds == bounds { return Cached::load(¤t.geometry); diff --git a/graphics/src/geometry/frame.rs b/graphics/src/geometry/frame.rs index fb7aae82ec..b9f15e3b3e 100644 --- a/graphics/src/geometry/frame.rs +++ b/graphics/src/geometry/frame.rs @@ -57,12 +57,7 @@ where /// Draws an axis-aligned rectangle given its top-left corner coordinate and /// its `Size` on the [`Frame`] by filling it with the provided style. - pub fn fill_rectangle( - &mut self, - top_left: Point, - size: Size, - fill: impl Into, - ) { + pub fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into) { self.raw.fill_rectangle(top_left, size, fill); } @@ -138,11 +133,7 @@ where /// This method is useful to perform drawing operations that need to be /// clipped. #[inline] - pub fn with_clip( - &mut self, - region: Rectangle, - f: impl FnOnce(&mut Self) -> R, - ) -> R { + pub fn with_clip(&mut self, region: Rectangle, f: impl FnOnce(&mut Self) -> R) -> R { let mut frame = self.draft(region); let result = f(&mut frame); @@ -218,26 +209,12 @@ pub trait Backend: Sized { fn paste(&mut self, frame: Self); fn stroke<'a>(&mut self, path: &Path, stroke: impl Into>); - fn stroke_rectangle<'a>( - &mut self, - top_left: Point, - size: Size, - stroke: impl Into>, - ); - fn stroke_text<'a>( - &mut self, - text: impl Into, - stroke: impl Into>, - ); + fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into>); + fn stroke_text<'a>(&mut self, text: impl Into, stroke: impl Into>); fn fill(&mut self, path: &Path, fill: impl Into); fn fill_text(&mut self, text: impl Into); - fn fill_rectangle( - &mut self, - top_left: Point, - size: Size, - fill: impl Into, - ); + fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into); fn draw_image(&mut self, bounds: Rectangle, image: impl Into); fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into); @@ -284,22 +261,11 @@ impl Backend for () { _stroke: impl Into>, ) { } - fn stroke_text<'a>( - &mut self, - _text: impl Into, - _stroke: impl Into>, - ) { - } + fn stroke_text<'a>(&mut self, _text: impl Into, _stroke: impl Into>) {} fn fill(&mut self, _path: &Path, _fill: impl Into) {} fn fill_text(&mut self, _text: impl Into) {} - fn fill_rectangle( - &mut self, - _top_left: Point, - _size: Size, - _fill: impl Into, - ) { - } + fn fill_rectangle(&mut self, _top_left: Point, _size: Size, _fill: impl Into) {} fn draw_image(&mut self, _bounds: Rectangle, _image: impl Into) {} fn draw_svg(&mut self, _bounds: Rectangle, _svg: impl Into) {} diff --git a/graphics/src/geometry/path.rs b/graphics/src/geometry/path.rs index e72732ff94..ecb638df5d 100644 --- a/graphics/src/geometry/path.rs +++ b/graphics/src/geometry/path.rs @@ -50,11 +50,7 @@ impl Path { /// Creates a new [`Path`] representing a rounded rectangle given its top-left /// corner coordinate, its [`Size`] and [`border::Radius`]. - pub fn rounded_rectangle( - top_left: Point, - size: Size, - radius: border::Radius, - ) -> Self { + pub fn rounded_rectangle(top_left: Point, size: Size, radius: border::Radius) -> Self { Self::new(|p| p.rounded_rectangle(top_left, size, radius)) } diff --git a/graphics/src/geometry/path/builder.rs b/graphics/src/geometry/path/builder.rs index 1a017acb5a..a687edb574 100644 --- a/graphics/src/geometry/path/builder.rs +++ b/graphics/src/geometry/path/builder.rs @@ -65,9 +65,8 @@ impl Builder { return; } - let double_area = start.x * (mid.y - end.y) - + mid.x * (end.y - start.y) - + end.x * (start.y - mid.y); + let double_area = + start.x * (mid.y - end.y) + mid.x * (end.y - start.y) + end.x * (start.y - mid.y); if double_area == 0.0 { let _ = self.raw.line_to(mid); @@ -108,9 +107,7 @@ impl Builder { radii: math::Vector::new(arc.radii.x, arc.radii.y), x_rotation: math::Angle::radians(arc.rotation.0), start_angle: math::Angle::radians(arc.start_angle.0), - sweep_angle: math::Angle::radians( - (arc.end_angle - arc.start_angle).0, - ), + sweep_angle: math::Angle::radians((arc.end_angle - arc.start_angle).0), }; let _ = self.raw.move_to(arc.sample(0.0)); @@ -124,12 +121,7 @@ impl Builder { /// Adds a cubic Bézier curve to the [`Path`] given its two control points /// and its end point. #[inline] - pub fn bezier_curve_to( - &mut self, - control_a: Point, - control_b: Point, - to: Point, - ) { + pub fn bezier_curve_to(&mut self, control_a: Point, control_b: Point, to: Point) { let _ = self.raw.cubic_bezier_to( math::Point::new(control_a.x, control_a.y), math::Point::new(control_b.x, control_b.y), @@ -164,12 +156,7 @@ impl Builder { /// Adds a rounded rectangle to the [`Path`] given its top-left /// corner coordinate its [`Size`] and [`border::Radius`]. #[inline] - pub fn rounded_rectangle( - &mut self, - top_left: Point, - size: Size, - radius: border::Radius, - ) { + pub fn rounded_rectangle(&mut self, top_left: Point, size: Size, radius: border::Radius) { let min_size = (size.height / 2.0).min(size.width / 2.0); let [ top_left_corner, diff --git a/graphics/src/geometry/text.rs b/graphics/src/geometry/text.rs index effe7a785d..c048bfc5cc 100644 --- a/graphics/src/geometry/text.rs +++ b/graphics/src/geometry/text.rs @@ -79,9 +79,7 @@ impl Text { ); let translation_x = match self.align_x { - Alignment::Left | Alignment::Default | Alignment::Justified => { - self.position.x - } + Alignment::Left | Alignment::Default | Alignment::Justified => self.position.x, Alignment::Center | Alignment::Right => { let mut line_width = 0.0f32; @@ -100,12 +98,8 @@ impl Text { let translation_y = { match self.align_y { alignment::Vertical::Top => self.position.y, - alignment::Vertical::Center => { - self.position.y - paragraph.min_height() / 2.0 - } - alignment::Vertical::Bottom => { - self.position.y - paragraph.min_height() - } + alignment::Vertical::Center => self.position.y - paragraph.min_height() / 2.0, + alignment::Vertical::Bottom => self.position.y - paragraph.min_height(), } }; @@ -120,38 +114,30 @@ impl Text { let start_y = translation_y + glyph.y_offset + run.line_y; let offset = Vector::new(start_x, start_y); - if let Some(commands) = swash_cache.get_outline_commands( - font_system.raw(), - physical_glyph.cache_key, - ) { + if let Some(commands) = + swash_cache.get_outline_commands(font_system.raw(), physical_glyph.cache_key) + { let glyph = Path::new(|path| { use cosmic_text::Command; for command in commands { match command { Command::MoveTo(p) => { - path.move_to( - Point::new(p.x, -p.y) + offset, - ); + path.move_to(Point::new(p.x, -p.y) + offset); } Command::LineTo(p) => { - path.line_to( - Point::new(p.x, -p.y) + offset, - ); + path.line_to(Point::new(p.x, -p.y) + offset); } Command::CurveTo(control_a, control_b, to) => { path.bezier_curve_to( - Point::new(control_a.x, -control_a.y) - + offset, - Point::new(control_b.x, -control_b.y) - + offset, + Point::new(control_a.x, -control_a.y) + offset, + Point::new(control_b.x, -control_b.y) + offset, Point::new(to.x, -to.y) + offset, ); } Command::QuadTo(control, to) => { path.quadratic_curve_to( - Point::new(control.x, -control.y) - + offset, + Point::new(control.x, -control.y) + offset, Point::new(to.x, -to.y) + offset, ); } diff --git a/graphics/src/gradient.rs b/graphics/src/gradient.rs index 95593c59ec..3594c18961 100644 --- a/graphics/src/gradient.rs +++ b/graphics/src/gradient.rs @@ -64,11 +64,10 @@ impl Linear { /// Any stop added after the 8th will be silently ignored. pub fn add_stop(mut self, offset: f32, color: Color) -> Self { if offset.is_finite() && (0.0..=1.0).contains(&offset) { - let (Ok(index) | Err(index)) = - self.stops.binary_search_by(|stop| match stop { - None => Ordering::Greater, - Some(stop) => stop.offset.total_cmp(&offset), - }); + let (Ok(index) | Err(index)) = self.stops.binary_search_by(|stop| match stop { + None => Ordering::Greater, + Some(stop) => stop.offset.total_cmp(&offset), + }); if index < 8 { self.stops[index] = Some(ColorStop { offset, color }); @@ -83,10 +82,7 @@ impl Linear { /// Adds multiple [`ColorStop`]s to the gradient. /// /// Any stop added after the 8th will be silently ignored. - pub fn add_stops( - mut self, - stops: impl IntoIterator, - ) -> Self { + pub fn add_stops(mut self, stops: impl IntoIterator) -> Self { for stop in stops { self = self.add_stop(stop.offset, stop.color); } @@ -100,17 +96,14 @@ impl Linear { let mut offsets = [f16::from(0u8); 8]; for (index, stop) in self.stops.iter().enumerate() { - let [r, g, b, a] = - color::pack(stop.map_or(Color::default(), |s| s.color)) - .components(); + let [r, g, b, a] = color::pack(stop.map_or(Color::default(), |s| s.color)).components(); colors[index] = [ pack_f16s([f16::from_f32(r), f16::from_f32(g)]), pack_f16s([f16::from_f32(b), f16::from_f32(a)]), ]; - offsets[index] = - stop.map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); + offsets[index] = stop.map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); } let offsets = [ @@ -150,16 +143,14 @@ pub fn pack(gradient: &core::Gradient, bounds: Rectangle) -> Packed { for (index, stop) in linear.stops.iter().enumerate() { let [r, g, b, a] = - color::pack(stop.map_or(Color::default(), |s| s.color)) - .components(); + color::pack(stop.map_or(Color::default(), |s| s.color)).components(); colors[index] = [ pack_f16s([f16::from_f32(r), f16::from_f32(g)]), pack_f16s([f16::from_f32(b), f16::from_f32(a)]), ]; - offsets[index] = stop - .map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); + offsets[index] = stop.map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); } let offsets = [ diff --git a/graphics/src/image.rs b/graphics/src/image.rs index e5fe928173..0332adf7b3 100644 --- a/graphics/src/image.rs +++ b/graphics/src/image.rs @@ -31,9 +31,7 @@ impl Image { /// Returns the bounds of the [`Image`]. pub fn bounds(&self) -> Rectangle { match self { - Image::Raster { image, bounds, .. } => { - bounds.rotate(image.rotation) - } + Image::Raster { image, bounds, .. } => bounds.rotate(image.rotation), Image::Vector { svg, bounds, .. } => bounds.rotate(svg.rotation), } } @@ -87,10 +85,7 @@ pub fn load(handle: &image::Handle) -> Result { .unwrap_or_else(Self::empty)) } - fn perform( - self, - mut image: ::image::DynamicImage, - ) -> ::image::DynamicImage { + fn perform(self, mut image: ::image::DynamicImage) -> ::image::DynamicImage { use ::image::imageops; if self.contains(Operation::ROTATE_90) { @@ -141,10 +136,9 @@ pub fn load(handle: &image::Handle) -> Result { image::Handle::Bytes(_, bytes) => { let image = ::image::load_from_memory(bytes).map_err(to_error)?; - let operation = - Operation::from_exif(&mut std::io::Cursor::new(bytes)) - .ok() - .unwrap_or_else(Operation::empty); + let operation = Operation::from_exif(&mut std::io::Cursor::new(bytes)) + .ok() + .unwrap_or_else(Operation::empty); let rgba = operation.perform(image).into_rgba8(); @@ -162,9 +156,7 @@ pub fn load(handle: &image::Handle) -> Result { Ok(image) } else { Err(to_error(::image::error::ImageError::Limits( - ::image::error::LimitError::from_kind( - ::image::error::LimitErrorKind::DimensionError, - ), + ::image::error::LimitError::from_kind(::image::error::LimitErrorKind::DimensionError), ))) } } @@ -174,9 +166,7 @@ fn to_error(error: ::image::ImageError) -> image::Error { use std::sync::Arc; match error { - ::image::ImageError::IoError(error) => { - image::Error::Inaccessible(Arc::new(error)) - } + ::image::ImageError::IoError(error) => image::Error::Inaccessible(Arc::new(error)), error => image::Error::Invalid(Arc::new(error)), } } diff --git a/graphics/src/mesh.rs b/graphics/src/mesh.rs index 9e11635461..51f9aa9521 100644 --- a/graphics/src/mesh.rs +++ b/graphics/src/mesh.rs @@ -47,8 +47,9 @@ impl Mesh { /// Returns the [`Transformation`] of the [`Mesh`]. pub fn transformation(&self) -> Transformation { match self { - Self::Solid { transformation, .. } - | Self::Gradient { transformation, .. } => *transformation, + Self::Solid { transformation, .. } | Self::Gradient { transformation, .. } => { + *transformation + } } } diff --git a/graphics/src/settings.rs b/graphics/src/settings.rs index 121953bb44..09c579be6d 100644 --- a/graphics/src/settings.rs +++ b/graphics/src/settings.rs @@ -37,10 +37,8 @@ impl Default for Settings { impl From for Settings { fn from(settings: core::Settings) -> Self { Self { - default_font: if cfg!(all( - target_arch = "wasm32", - feature = "fira-sans" - )) && settings.default_font == Font::default() + default_font: if cfg!(all(target_arch = "wasm32", feature = "fira-sans")) + && settings.default_font == Font::default() { Font::with_name("Fira Sans") } else { diff --git a/graphics/src/text.rs b/graphics/src/text.rs index 230a362d54..db8866f9f6 100644 --- a/graphics/src/text.rs +++ b/graphics/src/text.rs @@ -124,8 +124,7 @@ impl Text { /// /// [Fira Sans]: https://mozilla.github.io/Fira/ #[cfg(feature = "fira-sans")] -pub const FIRA_SANS_REGULAR: &[u8] = - include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(); +pub const FIRA_SANS_REGULAR: &[u8] = include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(); /// Returns the global [`FontSystem`]. pub fn font_system() -> &'static RwLock { @@ -171,9 +170,12 @@ impl FontSystem { } } - let _ = self.raw.db_mut().load_font_source( - cosmic_text::fontdb::Source::Binary(Arc::new(bytes.into_owned())), - ); + let _ = self + .raw + .db_mut() + .load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new( + bytes.into_owned(), + ))); self.version = Version(self.version.0 + 1); } @@ -215,16 +217,16 @@ impl PartialEq for Raw { /// Measures the dimensions of the given [`cosmic_text::Buffer`]. pub fn measure(buffer: &cosmic_text::Buffer) -> (Size, bool) { - let (width, height, has_rtl) = buffer.layout_runs().fold( - (0.0, 0.0, false), - |(width, height, has_rtl), run| { - ( - run.line_w.max(width), - height + run.line_height, - has_rtl || run.rtl, - ) - }, - ); + let (width, height, has_rtl) = + buffer + .layout_runs() + .fold((0.0, 0.0, false), |(width, height, has_rtl), run| { + ( + run.line_w.max(width), + height + run.line_height, + has_rtl || run.rtl, + ) + }); (Size::new(width, height), has_rtl) } @@ -241,9 +243,10 @@ pub fn align( if let Some(align) = to_align(alignment) { let has_multiple_lines = buffer.lines.len() > 1 - || buffer.lines.first().is_some_and(|line| { - line.layout_opt().is_some_and(|layout| layout.len() > 1) - }); + || buffer + .lines + .first() + .is_some_and(|line| line.layout_opt().is_some_and(|layout| layout.len() > 1)); if has_multiple_lines { for line in &mut buffer.lines { @@ -339,10 +342,7 @@ pub fn to_shaping(shaping: Shaping, text: &str) -> cosmic_text::Shaping { #[inline] /// Converts some [`Shaping`] strategy to a [`cosmic_text::Shaping`] strategy. -pub fn to_shaping_ascii( - shaping: Shaping, - is_ascii: bool, -) -> cosmic_text::Shaping { +pub fn to_shaping_ascii(shaping: Shaping, is_ascii: bool) -> cosmic_text::Shaping { match shaping { Shaping::Auto => { if is_ascii { @@ -367,9 +367,7 @@ pub fn to_wrap(wrapping: Wrapping) -> cosmic_text::Wrap { } /// Converts some [`Ellipsize`] strategy to a [`cosmic_text::Ellipsize`] strategy. -pub fn to_ellipsize( - ellipsize: crate::core::text::Ellipsize, -) -> cosmic_text::Ellipsize { +pub fn to_ellipsize(ellipsize: crate::core::text::Ellipsize) -> cosmic_text::Ellipsize { match ellipsize { crate::core::text::Ellipsize::None => cosmic_text::Ellipsize::None, crate::core::text::Ellipsize::Start(limit) => { diff --git a/graphics/src/text/cache.rs b/graphics/src/text/cache.rs index e197594119..872085c0e5 100644 --- a/graphics/src/text/cache.rs +++ b/graphics/src/text/cache.rs @@ -40,10 +40,8 @@ impl Cache { } if let hash_map::Entry::Vacant(entry) = self.entries.entry(hash) { - let metrics = cosmic_text::Metrics::new( - key.size, - key.line_height.max(f32::MIN_POSITIVE), - ); + let metrics = + cosmic_text::Metrics::new(key.size, key.line_height.max(f32::MIN_POSITIVE)); let mut buffer = cosmic_text::Buffer::new(font_system, metrics); buffer.set_size( @@ -73,10 +71,9 @@ impl Cache { }, ] { if key.bounds != bounds { - let _ = self.aliases.insert( - Key { bounds, ..key }.hash(FxHasher::default()), - hash, - ); + let _ = self + .aliases + .insert(Key { bounds, ..key }.hash(FxHasher::default()), hash); } } } diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index b284c76b71..10bec950db 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -57,16 +57,12 @@ impl Editor { .expect("Editor should always be initialized") } - fn with_internal_mut( - &mut self, - f: impl FnOnce(&mut Internal) -> T, - ) -> T { - let editor = - self.0.take().expect("Editor should always be initialized"); + fn with_internal_mut(&mut self, f: impl FnOnce(&mut Internal) -> T) -> T { + let editor = self.0.take().expect("Editor should always be initialized"); // TODO: Handle multiple strong references somehow - let mut internal = Arc::try_unwrap(editor) - .expect("Editor cannot have multiple strong references"); + let mut internal = + Arc::try_unwrap(editor).expect("Editor cannot have multiple strong references"); // Clear cursor cache let _ = internal @@ -92,8 +88,7 @@ impl editor::Editor for Editor { line_height: 1.0, }); - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); buffer.set_text( text, @@ -113,8 +108,7 @@ impl editor::Editor for Editor { fn is_empty(&self) -> bool { let buffer = self.buffer(); - buffer.lines.is_empty() - || (buffer.lines.len() == 1 && buffer.lines[0].text().is_empty()) + buffer.lines.is_empty() || (buffer.lines.len() == 1 && buffer.lines[0].text().is_empty()) } fn line(&self, index: usize) -> Option> { @@ -154,9 +148,7 @@ impl editor::Editor for Editor { let regions = buffer .layout_runs() - .filter(|run| { - run.line_i >= start.line && run.line_i <= end.line - }) + .filter(|run| run.line_i >= start.line && run.line_i <= end.line) .flat_map(|run| { let line_top = run.line_top; run.highlight(start, end) @@ -188,20 +180,15 @@ impl editor::Editor for Editor { // Fallback: cursor not found in any run (e.g. empty buffer). let line_height = buffer.metrics().line_height; let scroll_y = buffer.scroll().vertical; - let visual_lines_offset = - visual_lines_offset(cursor.line, buffer); - Point::new( - 0.0, - visual_lines_offset as f32 * line_height - scroll_y, - ) + let visual_lines_offset = visual_lines_offset(cursor.line, buffer); + Point::new(0.0, visual_lines_offset as f32 * line_height - scroll_y) }); Selection::Caret(point) } }; - *internal.selection.write().expect("Write to cursor cache") = - Some(cursor.clone()); + *internal.selection.write().expect("Write to cursor cache") = Some(cursor.clone()); cursor } @@ -235,8 +222,7 @@ impl editor::Editor for Editor { } fn perform(&mut self, action: Action) { - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); self.with_internal_mut(|internal| { let editor = &mut internal.editor; @@ -256,9 +242,7 @@ impl editor::Editor for Editor { | Motion::DocumentEnd => { editor.action( font_system.raw(), - cosmic_text::Action::Motion(to_motion( - motion, - )), + cosmic_text::Action::Motion(to_motion(motion)), ); } // Other motions simply move the cursor to one end of the selection @@ -280,9 +264,7 @@ impl editor::Editor for Editor { let cursor = editor.cursor(); if editor.selection_bounds().is_none() { - editor.set_selection(cosmic_text::Selection::Normal( - cursor, - )); + editor.set_selection(cosmic_text::Selection::Normal(cursor)); } editor.action( @@ -319,19 +301,15 @@ impl editor::Editor for Editor { { let cursor = editor.cursor(); - editor.set_selection(cosmic_text::Selection::Normal( - cosmic_text::Cursor { - line: 0, - index: 0, - ..cursor - }, - )); + editor.set_selection(cosmic_text::Selection::Normal(cosmic_text::Cursor { + line: 0, + index: 0, + ..cursor + })); editor.action( font_system.raw(), - cosmic_text::Action::Motion( - cosmic_text::Motion::BufferEnd, - ), + cosmic_text::Action::Motion(cosmic_text::Motion::BufferEnd), ); } } @@ -346,43 +324,25 @@ impl editor::Editor for Editor { match edit { Edit::Insert(c) => { - editor.action( - font_system.raw(), - cosmic_text::Action::Insert(c), - ); + editor.action(font_system.raw(), cosmic_text::Action::Insert(c)); } Edit::Paste(text) => { editor.insert_string(&text, None); } Edit::Indent => { - editor.action( - font_system.raw(), - cosmic_text::Action::Indent, - ); + editor.action(font_system.raw(), cosmic_text::Action::Indent); } Edit::Unindent => { - editor.action( - font_system.raw(), - cosmic_text::Action::Unindent, - ); + editor.action(font_system.raw(), cosmic_text::Action::Unindent); } Edit::Enter => { - editor.action( - font_system.raw(), - cosmic_text::Action::Enter, - ); + editor.action(font_system.raw(), cosmic_text::Action::Enter); } Edit::Backspace => { - editor.action( - font_system.raw(), - cosmic_text::Action::Backspace, - ); + editor.action(font_system.raw(), cosmic_text::Action::Backspace); } Edit::Delete => { - editor.action( - font_system.raw(), - cosmic_text::Action::Delete, - ); + editor.action(font_system.raw(), cosmic_text::Action::Delete); } } @@ -392,9 +352,8 @@ impl editor::Editor for Editor { .map(|(start, _)| start) .unwrap_or(cursor); - internal.topmost_line_changed = Some( - selection_start.line.min(topmost_line_before_edit), - ); + internal.topmost_line_changed = + Some(selection_start.line.min(topmost_line_before_edit)); } // Mouse events @@ -428,10 +387,7 @@ impl editor::Editor for Editor { editor.action( font_system.raw(), cosmic_text::Action::Scroll { - pixels: lines as f32 - * buffer_from_editor(editor) - .metrics() - .line_height, + pixels: lines as f32 * buffer_from_editor(editor).metrics().line_height, }, ); } @@ -451,13 +407,11 @@ impl editor::Editor for Editor { if let Some(selection) = cursor.selection { internal .editor - .set_selection(cosmic_text::Selection::Normal( - cosmic_text::Cursor { - line: selection.line, - index: selection.column, - affinity: cosmic_text::Affinity::Before, - }, - )); + .set_selection(cosmic_text::Selection::Normal(cosmic_text::Cursor { + line: selection.line, + index: selection.column, + affinity: cosmic_text::Affinity::Before, + })); } }); } @@ -469,8 +423,7 @@ impl editor::Editor for Editor { fn min_bounds(&self) -> Size { let internal = self.internal(); - let (bounds, _has_rtl) = - text::measure(buffer_from_editor(&internal.editor)); + let (bounds, _has_rtl) = text::measure(buffer_from_editor(&internal.editor)); bounds } @@ -485,8 +438,7 @@ impl editor::Editor for Editor { new_highlighter: &mut impl Highlighter, ) { self.with_internal_mut(|internal| { - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); let buffer = buffer_mut_from_editor(&mut internal.editor); @@ -505,9 +457,9 @@ impl editor::Editor for Editor { log::trace!("Updating font of `Editor`..."); for line in buffer.lines.iter_mut() { - let _ = line.set_attrs_list(cosmic_text::AttrsList::new( - &text::to_attributes(new_font), - )); + let _ = line.set_attrs_list(cosmic_text::AttrsList::new(&text::to_attributes( + new_font, + ))); } internal.font = new_font; @@ -517,15 +469,10 @@ impl editor::Editor for Editor { let metrics = buffer.metrics(); let new_line_height = new_line_height.to_absolute(new_size); - if new_size.0 != metrics.font_size - || new_line_height.0 != metrics.line_height - { + if new_size.0 != metrics.font_size || new_line_height.0 != metrics.line_height { log::trace!("Updating `Metrics` of `Editor`..."); - buffer.set_metrics(cosmic_text::Metrics::new( - new_size.0, - new_line_height.0, - )); + buffer.set_metrics(cosmic_text::Metrics::new(new_size.0, new_line_height.0)); } let new_wrap = text::to_wrap(new_wrapping); @@ -539,15 +486,12 @@ impl editor::Editor for Editor { if new_bounds != internal.bounds { log::trace!("Updating size of `Editor`..."); - buffer - .set_size(Some(new_bounds.width), Some(new_bounds.height)); + buffer.set_size(Some(new_bounds.width), Some(new_bounds.height)); internal.bounds = new_bounds; } - if let Some(topmost_line_changed) = - internal.topmost_line_changed.take() - { + if let Some(topmost_line_changed) = internal.topmost_line_changed.take() { log::trace!( "Notifying highlighter of line \ change: {topmost_line_changed}" @@ -570,8 +514,7 @@ impl editor::Editor for Editor { let buffer = buffer_from_editor(&internal.editor); let scroll = buffer.scroll(); - let mut window = (internal.bounds.height / buffer.metrics().line_height) - .ceil() as i32; + let mut window = (internal.bounds.height / buffer.metrics().line_height).ceil() as i32; let last_visible_line = buffer.lines[scroll.line..] .iter() @@ -598,14 +541,12 @@ impl editor::Editor for Editor { return; } - let editor = - self.0.take().expect("Editor should always be initialized"); + let editor = self.0.take().expect("Editor should always be initialized"); - let mut internal = Arc::try_unwrap(editor) - .expect("Editor cannot have multiple strong references"); + let mut internal = + Arc::try_unwrap(editor).expect("Editor cannot have multiple strong references"); - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); let attributes = text::to_attributes(font); @@ -739,9 +680,7 @@ fn to_motion(motion: Motion) -> cosmic_text::Motion { } } -fn buffer_from_editor<'a, 'b>( - editor: &'a impl cosmic_text::Edit<'b>, -) -> &'a cosmic_text::Buffer +fn buffer_from_editor<'a, 'b>(editor: &'a impl cosmic_text::Edit<'b>) -> &'a cosmic_text::Buffer where 'b: 'a, { diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index 4159623989..8e18df8e51 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -3,9 +3,7 @@ use iced_core::text::Ellipsize; use crate::core; use crate::core::alignment; -use crate::core::text::{ - Affinity, Alignment, Hit, LineHeight, Shaping, Span, Text, Wrapping, -}; +use crate::core::text::{Affinity, Alignment, Hit, LineHeight, Shaping, Span, Text, Wrapping}; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; @@ -75,8 +73,7 @@ impl core::text::Paragraph for Paragraph { fn with_text(text: Text<&str>) -> Self { log::trace!("Allocating plain paragraph: {}", text.content); - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); let mut buffer = cosmic_text::Buffer::new( font_system.raw(), @@ -99,8 +96,7 @@ impl core::text::Paragraph for Paragraph { ); buffer.shape_until_scroll(font_system.raw(), false); - let min_bounds = - text::align(&mut buffer, font_system.raw(), text.align_x); + let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x); Self(Arc::new(Internal { buffer, @@ -119,8 +115,7 @@ impl core::text::Paragraph for Paragraph { fn with_spans(text: Text<&[Span<'_, Link>]>) -> Self { log::trace!("Allocating rich paragraph: {} spans", text.content.len()); - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); let mut buffer = cosmic_text::Buffer::new( font_system.raw(), @@ -172,8 +167,7 @@ impl core::text::Paragraph for Paragraph { ); buffer.shape_until_scroll(font_system.raw(), false); - let min_bounds = - text::align(&mut buffer, font_system.raw(), text.align_x); + let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x); Self(Arc::new(Internal { buffer, @@ -192,8 +186,7 @@ impl core::text::Paragraph for Paragraph { fn resize(&mut self, new_bounds: Size) { let paragraph = Arc::make_mut(&mut self.0); - let mut font_system = - text::font_system().write().expect("Write font system"); + let mut font_system = text::font_system().write().expect("Write font system"); paragraph .buffer @@ -202,11 +195,7 @@ impl core::text::Paragraph for Paragraph { .buffer .shape_until_scroll(font_system.raw(), false); - let min_bounds = text::align( - &mut paragraph.buffer, - font_system.raw(), - paragraph.align_x, - ); + let min_bounds = text::align(&mut paragraph.buffer, font_system.raw(), paragraph.align_x); paragraph.bounds = new_bounds; paragraph.min_bounds = min_bounds; @@ -338,10 +327,7 @@ impl core::text::Paragraph for Paragraph { let new_bounds = || { Rectangle::new( Point::new(glyph.x, y), - Size::new( - glyph.w, - glyph.line_height_opt.unwrap_or(line_height), - ), + Size::new(glyph.w, glyph.line_height_opt.unwrap_or(line_height)), ) }; @@ -379,9 +365,7 @@ impl core::text::Paragraph for Paragraph { .iter() .find(|glyph| { if Some(glyph.start) != last_start { - last_grapheme_count = run.text[glyph.start..glyph.end] - .graphemes(false) - .count(); + last_grapheme_count = run.text[glyph.start..glyph.end].graphemes(false).count(); last_start = Some(glyph.start); graphemes_seen += last_grapheme_count; } @@ -405,18 +389,10 @@ impl core::text::Paragraph for Paragraph { )) } - fn cursor_position( - &self, - line: usize, - byte_index: usize, - affinity: Affinity, - ) -> Option { + fn cursor_position(&self, line: usize, byte_index: usize, affinity: Affinity) -> Option { let internal = self.internal(); - let cursor = cosmic_text::Cursor::new_with_affinity( - line, - byte_index, - to_cosmic_affinity(affinity), - ); + let cursor = + cosmic_text::Cursor::new_with_affinity(line, byte_index, to_cosmic_affinity(affinity)); internal .buffer .cursor_position(&cursor) @@ -430,16 +406,10 @@ impl core::text::Paragraph for Paragraph { end: (usize, Affinity), ) -> Vec { let internal = self.internal(); - let start_cursor = cosmic_text::Cursor::new_with_affinity( - line, - start.0, - to_cosmic_affinity(start.1), - ); - let end_cursor = cosmic_text::Cursor::new_with_affinity( - line, - end.0, - to_cosmic_affinity(end.1), - ); + let start_cursor = + cosmic_text::Cursor::new_with_affinity(line, start.0, to_cosmic_affinity(start.1)); + let end_cursor = + cosmic_text::Cursor::new_with_affinity(line, end.0, to_cosmic_affinity(end.1)); internal .buffer diff --git a/graphics/src/viewport.rs b/graphics/src/viewport.rs index b27276d5f2..e70de7f249 100644 --- a/graphics/src/viewport.rs +++ b/graphics/src/viewport.rs @@ -20,10 +20,7 @@ impl Viewport { physical_size, logical_size: size, scale_factor, - projection: Transformation::orthographic( - physical_size.width, - physical_size.height, - ), + projection: Transformation::orthographic(physical_size.width, physical_size.height), } } diff --git a/highlighter/src/lib.rs b/highlighter/src/lib.rs index 3066f36211..8aee9c2228 100644 --- a/highlighter/src/lib.rs +++ b/highlighter/src/lib.rs @@ -12,8 +12,7 @@ use syntect::highlighting; use syntect::parsing; use two_face::re_exports::syntect; -static SYNTAXES: LazyLock = - LazyLock::new(two_face::syntax::extra_no_newlines); +static SYNTAXES: LazyLock = LazyLock::new(two_face::syntax::extra_no_newlines); static THEMES: LazyLock = LazyLock::new(highlighting::ThemeSet::load_defaults); @@ -33,17 +32,14 @@ impl highlighter::Highlighter for Highlighter { type Settings = Settings; type Highlight = Highlight; - type Iterator<'a> = - Box, Self::Highlight)> + 'a>; + type Iterator<'a> = Box, Self::Highlight)> + 'a>; fn new(settings: &Self::Settings) -> Self { let syntax = SYNTAXES .find_syntax_by_token(&settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); - let highlighter = highlighting::Highlighter::new( - &THEMES.themes[settings.theme.key()], - ); + let highlighter = highlighting::Highlighter::new(&THEMES.themes[settings.theme.key()]); let parser = parsing::ParseState::new(syntax); let stack = parsing::ScopeStack::new(); @@ -61,9 +57,7 @@ impl highlighter::Highlighter for Highlighter { .find_syntax_by_token(&new_settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); - self.highlighter = highlighting::Highlighter::new( - &THEMES.themes[new_settings.theme.key()], - ); + self.highlighter = highlighting::Highlighter::new(&THEMES.themes[new_settings.theme.key()]); // Restart the highlighter self.change_line(0); @@ -80,29 +74,26 @@ impl highlighter::Highlighter for Highlighter { self.current_line = 0; } - let (parser, stack) = - self.caches.last().cloned().unwrap_or_else(|| { - ( - parsing::ParseState::new(self.syntax), - parsing::ScopeStack::new(), - ) - }); + let (parser, stack) = self.caches.last().cloned().unwrap_or_else(|| { + ( + parsing::ParseState::new(self.syntax), + parsing::ScopeStack::new(), + ) + }); self.caches.push((parser, stack)); } fn highlight_line(&mut self, line: &str) -> Self::Iterator<'_> { if self.current_line / LINES_PER_SNAPSHOT >= self.caches.len() { - let (parser, stack) = - self.caches.last().expect("Caches must not be empty"); + let (parser, stack) = self.caches.last().expect("Caches must not be empty"); self.caches.push((parser.clone(), stack.clone())); } self.current_line += 1; - let (parser, stack) = - self.caches.last_mut().expect("Caches must not be empty"); + let (parser, stack) = self.caches.last_mut().expect("Caches must not be empty"); let ops = parser.parse_line(line, &SYNTAXES).unwrap_or_default(); @@ -159,9 +150,7 @@ impl Stream { .find_syntax_by_token(&settings.token) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); - let highlighter = highlighting::Highlighter::new( - &THEMES.themes[settings.theme.key()], - ); + let highlighter = highlighting::Highlighter::new(&THEMES.themes[settings.theme.key()]); let state = parsing::ParseState::new(syntax); let stack = parsing::ScopeStack::new(); @@ -223,9 +212,9 @@ impl Highlight { /// /// If `None`, the original text color should be unchanged. pub fn color(&self) -> Option { - self.0.foreground.map(|color| { - Color::from_rgba8(color.r, color.g, color.b, color.a as f32 / 255.0) - }) + self.0 + .foreground + .map(|color| Color::from_rgba8(color.r, color.g, color.b, color.a as f32 / 255.0)) } /// Returns the font of this [`Highlight`]. @@ -294,10 +283,9 @@ impl Theme { /// Returns `true` if the [`Theme`] is dark, and false otherwise. pub fn is_dark(self) -> bool { match self { - Self::SolarizedDark - | Self::Base16Mocha - | Self::Base16Ocean - | Self::Base16Eighties => true, + Self::SolarizedDark | Self::Base16Mocha | Self::Base16Ocean | Self::Base16Eighties => { + true + } Self::InspiredGitHub => false, } } diff --git a/program/src/lib.rs b/program/src/lib.rs index 818300f353..524d1a7b74 100644 --- a/program/src/lib.rs +++ b/program/src/lib.rs @@ -49,11 +49,7 @@ pub trait Program: Sized { fn boot(&self) -> (Self::State, Task); - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task; + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task; fn view<'a>( &self, @@ -90,18 +86,11 @@ pub trait Program: Sized { format!("{title} - Iced") } - fn subscription( - &self, - _state: &Self::State, - ) -> Subscription { + fn subscription(&self, _state: &Self::State) -> Subscription { Subscription::none() } - fn theme( - &self, - _state: &Self::State, - _window: window::Id, - ) -> Option { + fn theme(&self, _state: &Self::State, _window: window::Id) -> Option { None } @@ -159,11 +148,7 @@ pub fn with_title( self.program.boot() } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -175,26 +160,15 @@ pub fn with_title( self.program.view(state, window) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { self.program.theme(state, window) } - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { self.program.subscription(state) } - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } @@ -226,10 +200,7 @@ pub fn with_subscription( type Renderer = P::Renderer; type Executor = P::Executor; - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { (self.subscription)(state) } @@ -249,11 +220,7 @@ pub fn with_subscription( self.program.boot() } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -269,19 +236,11 @@ pub fn with_subscription( self.program.title(state, window) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { self.program.theme(state, window) } - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } @@ -316,11 +275,7 @@ pub fn with_theme( type Renderer = P::Renderer; type Executor = P::Executor; - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { (self.theme)(state, window) } @@ -344,11 +299,7 @@ pub fn with_theme( self.program.title(state, window) } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -360,18 +311,11 @@ pub fn with_theme( self.program.view(state, window) } - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { self.program.subscription(state) } - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } @@ -403,11 +347,7 @@ pub fn with_style( type Renderer = P::Renderer; type Executor = P::Executor; - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { (self.style)(state, theme) } @@ -431,11 +371,7 @@ pub fn with_style( self.program.title(state, window) } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -447,18 +383,11 @@ pub fn with_style( self.program.view(state, window) } - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { self.program.subscription(state) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { self.program.theme(state, window) } @@ -510,11 +439,7 @@ pub fn with_scale_factor( self.program.boot() } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -526,26 +451,15 @@ pub fn with_scale_factor( self.program.view(state, window) } - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { self.program.subscription(state) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { self.program.theme(state, window) } - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } @@ -601,11 +515,7 @@ pub fn with_executor( self.program.boot() } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { self.program.update(state, message) } @@ -617,26 +527,15 @@ pub fn with_executor( self.program.view(state, window) } - fn subscription( - &self, - state: &Self::State, - ) -> Subscription { + fn subscription(&self, state: &Self::State) -> Subscription { self.program.subscription(state) } - fn theme( - &self, - state: &Self::State, - window: window::Id, - ) -> Option { + fn theme(&self, state: &Self::State, window: window::Id) -> Option { self.program.theme(state, window) } - fn style( - &self, - state: &Self::State, - theme: &Self::Theme, - ) -> theme::Style { + fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } @@ -652,10 +551,7 @@ pub fn with_executor( } /// The renderer of some [`Program`]. -pub trait Renderer: - text::Renderer + compositor::Default + renderer::Headless -{ -} +pub trait Renderer: text::Renderer + compositor::Default + renderer::Headless {} impl Renderer for T where T: text::Renderer + compositor::Default + renderer::Headless @@ -687,10 +583,7 @@ impl Instance

{ pub fn title( self, title: impl TitleFn, - ) -> Application< - impl Program, - > { + ) -> Application> { Application { - raw: program::with_title(self.raw, move |state, _window| { - title.title(state) - }), + raw: program::with_title(self.raw, move |state, _window| title.title(state)), settings: self.settings, window: self.window, presets: self.presets, @@ -372,9 +367,7 @@ impl Application

{ pub fn subscription( self, f: impl Fn(&P::State) -> Subscription, - ) -> Application< - impl Program, - > { + ) -> Application> { Application { raw: program::with_subscription(self.raw, f), settings: self.settings, @@ -387,13 +380,9 @@ impl Application

{ pub fn theme( self, f: impl ThemeFn, - ) -> Application< - impl Program, - > { + ) -> Application> { Application { - raw: program::with_theme(self.raw, move |state, _window| { - f.theme(state) - }), + raw: program::with_theme(self.raw, move |state, _window| f.theme(state)), settings: self.settings, window: self.window, presets: self.presets, @@ -404,9 +393,7 @@ impl Application

{ pub fn style( self, f: impl Fn(&P::State, &P::Theme) -> theme::Style, - ) -> Application< - impl Program, - > { + ) -> Application> { Application { raw: program::with_style(self.raw, f), settings: self.settings, @@ -419,13 +406,9 @@ impl Application

{ pub fn scale_factor( self, f: impl Fn(&P::State) -> f32, - ) -> Application< - impl Program, - > { + ) -> Application> { Application { - raw: program::with_scale_factor(self.raw, move |state, _window| { - f(state) as f64 - }), + raw: program::with_scale_factor(self.raw, move |state, _window| f(state) as f64), settings: self.settings, window: self.window, presets: self.presets, @@ -435,9 +418,7 @@ impl Application

{ /// Sets the executor of the [`Application`]. pub fn executor( self, - ) -> Application< - impl Program, - > + ) -> Application> where E: Executor, { @@ -454,10 +435,7 @@ impl Application

{ /// Presets can be used to override the default booting strategy /// of your application during testing to create reproducible /// environments. - pub fn presets( - self, - presets: impl IntoIterator>, - ) -> Self { + pub fn presets(self, presets: impl IntoIterator>) -> Self { Self { presets: presets.into_iter().collect(), ..self @@ -484,9 +462,7 @@ impl Program for Application

{ Some(self.window.clone()) } - fn boot( - &self, - ) -> (::State, Task<::Message>) { + fn boot(&self) -> (::State, Task<::Message>) { self.raw.boot() } @@ -511,11 +487,7 @@ impl Program for Application

{ debug::hot(|| self.raw.view(state, window)) } - fn title( - &self, - state: &::State, - window: window::Id, - ) -> String { + fn title(&self, state: &::State, window: window::Id) -> String { debug::hot(|| self.raw.title(state, window)) } @@ -542,17 +514,11 @@ impl Program for Application

{ debug::hot(|| self.raw.style(state, theme)) } - fn scale_factor( - &self, - state: &::State, - window: window::Id, - ) -> f64 { + fn scale_factor(&self, state: &::State, window: window::Id) -> f64 { debug::hot(|| self.raw.scale_factor(state, window)) } - fn presets( - &self, - ) -> &[Preset<::State, ::Message>] { + fn presets(&self) -> &[Preset<::State, ::Message>] { &self.presets } } @@ -658,8 +624,8 @@ pub trait ViewFn<'a, State, Message, Theme, Renderer> { fn view(&self, state: &'a State) -> Element<'a, Message, Theme, Renderer>; } -impl<'a, T, State, Message, Theme, Renderer, Widget> - ViewFn<'a, State, Message, Theme, Renderer> for T +impl<'a, T, State, Message, Theme, Renderer, Widget> ViewFn<'a, State, Message, Theme, Renderer> + for T where T: Fn(&'a State) -> Widget, State: 'static, diff --git a/src/application/timed.rs b/src/application/timed.rs index 0e2ac597db..e12ef84d6b 100644 --- a/src/application/timed.rs +++ b/src/application/timed.rs @@ -25,9 +25,7 @@ pub fn timed( update: impl UpdateFn, subscription: impl Fn(&State) -> Subscription, view: impl for<'a> ViewFn<'a, State, Message, Theme, Renderer>, -) -> Application< - impl Program, -> +) -> Application> where State: 'static, Message: Send + 'static, @@ -36,16 +34,7 @@ where { use std::marker::PhantomData; - struct Instance< - State, - Message, - Theme, - Renderer, - Boot, - Update, - Subscription, - View, - > { + struct Instance { boot: Boot, update: Update, subscription: Subscription, @@ -56,18 +45,8 @@ where _renderer: PhantomData, } - impl - Program - for Instance< - State, - Message, - Theme, - Renderer, - Boot, - Update, - Subscription, - View, - > + impl Program + for Instance where Message: Send + 'static, Theme: theme::Base + 'static, @@ -137,10 +116,7 @@ where &self, state: &::State, ) -> self::Subscription<::Message> { - debug::hot(|| { - (self.subscription)(state) - .map(|message| (message, Instant::now())) - }) + debug::hot(|| (self.subscription)(state).map(|message| (message, Instant::now()))) } } @@ -167,12 +143,8 @@ where /// but it also takes an [`Instant`]. pub trait UpdateFn { /// Processes the message and updates the state of the [`Application`]. - fn update( - &self, - state: &mut State, - message: Message, - now: Instant, - ) -> impl Into>; + fn update(&self, state: &mut State, message: Message, now: Instant) + -> impl Into>; } impl UpdateFn for () { diff --git a/src/daemon.rs b/src/daemon.rs index 597e52d3e5..30012453a0 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -6,10 +6,7 @@ pub use crate::program::{self, Program}; use crate::shell; use crate::theme; use crate::window; -use crate::{ - Element, Executor, Font, Preset, Result, Settings, Subscription, Theme, - task::Task, -}; +use crate::{Element, Executor, Font, Preset, Result, Settings, Subscription, Theme, task::Task}; use iced_debug as debug; @@ -81,10 +78,7 @@ where None } - fn boot( - &self, - ) -> (::State, Task<::Message>) - { + fn boot(&self) -> (::State, Task<::Message>) { self.boot.boot() } @@ -203,13 +197,9 @@ impl Daemon

{ pub fn title( self, title: impl TitleFn, - ) -> Daemon< - impl Program, - > { + ) -> Daemon> { Daemon { - raw: program::with_title(self.raw, move |state, window| { - title.title(state, window) - }), + raw: program::with_title(self.raw, move |state, window| title.title(state, window)), settings: self.settings, presets: self.presets, } @@ -219,9 +209,7 @@ impl Daemon

{ pub fn subscription( self, f: impl Fn(&P::State) -> Subscription, - ) -> Daemon< - impl Program, - > { + ) -> Daemon> { Daemon { raw: program::with_subscription(self.raw, f), settings: self.settings, @@ -233,13 +221,9 @@ impl Daemon

{ pub fn theme( self, f: impl ThemeFn, - ) -> Daemon< - impl Program, - > { + ) -> Daemon> { Daemon { - raw: program::with_theme(self.raw, move |state, window| { - f.theme(state, window) - }), + raw: program::with_theme(self.raw, move |state, window| f.theme(state, window)), settings: self.settings, presets: self.presets, } @@ -249,9 +233,7 @@ impl Daemon

{ pub fn style( self, f: impl Fn(&P::State, &P::Theme) -> theme::Style, - ) -> Daemon< - impl Program, - > { + ) -> Daemon> { Daemon { raw: program::with_style(self.raw, f), settings: self.settings, @@ -263,9 +245,7 @@ impl Daemon

{ pub fn scale_factor( self, f: impl Fn(&P::State, window::Id) -> f64, - ) -> Daemon< - impl Program, - > { + ) -> Daemon> { Daemon { raw: program::with_scale_factor(self.raw, f), settings: self.settings, @@ -276,9 +256,7 @@ impl Daemon

{ /// Sets the executor of the [`Daemon`]. pub fn executor( self, - ) -> Daemon< - impl Program, - > + ) -> Daemon> where E: Executor, { @@ -294,10 +272,7 @@ impl Daemon

{ /// Presets can be used to override the default booting strategy /// of your application during testing to create reproducible /// environments. - pub fn presets( - self, - presets: impl IntoIterator>, - ) -> Self { + pub fn presets(self, presets: impl IntoIterator>) -> Self { Self { presets: presets.into_iter().collect(), ..self @@ -324,9 +299,7 @@ impl Program for Daemon

{ None } - fn boot( - &self, - ) -> (::State, Task<::Message>) { + fn boot(&self) -> (::State, Task<::Message>) { self.raw.boot() } @@ -351,11 +324,7 @@ impl Program for Daemon

{ debug::hot(|| self.raw.view(state, window)) } - fn title( - &self, - state: &::State, - window: window::Id, - ) -> String { + fn title(&self, state: &::State, window: window::Id) -> String { debug::hot(|| self.raw.title(state, window)) } @@ -382,11 +351,7 @@ impl Program for Daemon

{ debug::hot(|| self.raw.style(state, theme)) } - fn scale_factor( - &self, - state: &::State, - window: window::Id, - ) -> f64 { + fn scale_factor(&self, state: &::State, window: window::Id) -> f64 { debug::hot(|| self.raw.scale_factor(state, window)) } @@ -427,25 +392,17 @@ where /// returns any `Into>`. pub trait ViewFn<'a, State, Message, Theme, Renderer> { /// Produces the widget of the [`Daemon`]. - fn view( - &self, - state: &'a State, - window: window::Id, - ) -> Element<'a, Message, Theme, Renderer>; + fn view(&self, state: &'a State, window: window::Id) -> Element<'a, Message, Theme, Renderer>; } -impl<'a, T, State, Message, Theme, Renderer, Widget> - ViewFn<'a, State, Message, Theme, Renderer> for T +impl<'a, T, State, Message, Theme, Renderer, Widget> ViewFn<'a, State, Message, Theme, Renderer> + for T where T: Fn(&'a State, window::Id) -> Widget, State: 'static, Widget: Into>, { - fn view( - &self, - state: &'a State, - window: window::Id, - ) -> Element<'a, Message, Theme, Renderer> { + fn view(&self, state: &'a State, window: window::Id) -> Element<'a, Message, Theme, Renderer> { self(state, window).into() } } diff --git a/src/error.rs b/src/error.rs index 9db46fe17e..481920415e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -27,16 +27,12 @@ pub enum Error { impl From for Error { fn from(error: shell::Error) -> Error { match error { - shell::Error::ExecutorCreationFailed(error) => { - Error::ExecutorCreationFailed(error) - } + shell::Error::ExecutorCreationFailed(error) => Error::ExecutorCreationFailed(error), #[cfg(feature = "winit")] shell::Error::WindowCreationFailed(error) => { Error::WindowCreationFailed(Box::new(error)) } - shell::Error::GraphicsCreationFailed(error) => { - Error::GraphicsCreationFailed(error) - } + shell::Error::GraphicsCreationFailed(error) => Error::GraphicsCreationFailed(error), shell::Error::EventLoop(error) => Error::EventLoop(Box::new(error)), } } diff --git a/src/lib.rs b/src/lib.rs index 8d4089694a..fffa861057 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -533,9 +533,7 @@ pub mod window; #[cfg(feature = "winit")] pub mod platform_specific { - pub use iced_winit::{ - platform_specific as shell, runtime::platform_specific as runtime, - }; + pub use iced_winit::{platform_specific as shell, runtime::platform_specific as runtime}; } #[cfg(feature = "winit")] @@ -554,10 +552,9 @@ pub use crate::core::gradient; pub use crate::core::padding; pub use crate::core::theme; pub use crate::core::{ - Alignment, Animation, Background, Border, Color, ContentFit, Degrees, - Function, Gradient, Length, Never, Padding, Pixels, Point, Radians, - Rectangle, Rotation, Settings, Shadow, Size, Theme, Transformation, Vector, - id, layout::Limits, never, + Alignment, Animation, Background, Border, Color, ContentFit, Degrees, Function, Gradient, + Length, Never, Padding, Pixels, Point, Radians, Rectangle, Rotation, Settings, Shadow, Size, + Theme, Transformation, Vector, id, layout::Limits, never, }; pub use crate::program::{Preset, message}; pub use crate::runtime::exit; @@ -584,8 +581,8 @@ pub mod task { pub mod clipboard { //! Access the clipboard. pub use crate::runtime::clipboard::{ - read, read_data, read_primary, read_primary_data, write, write_data, - write_primary, write_primary_data, + read, read_data, read_primary, read_primary_data, write, write_data, write_primary, + write_primary_data, }; pub use dnd; pub use mime; @@ -621,9 +618,7 @@ pub mod keyboard { pub mod mouse { //! Listen and react to mouse events. - pub use crate::core::mouse::{ - Button, Cursor, Event, Interaction, ScrollDelta, - }; + pub use crate::core::mouse::{Button, Cursor, Event, Interaction, ScrollDelta}; } pub mod system { @@ -642,12 +637,8 @@ pub mod overlay { /// This is an alias of an [`overlay::Element`] with a default `Renderer`. /// /// [`overlay::Element`]: crate::core::overlay::Element - pub type Element< - 'a, - Message, - Theme = crate::Renderer, - Renderer = crate::Renderer, - > = crate::core::overlay::Element<'a, Message, Theme, Renderer>; + pub type Element<'a, Message, Theme = crate::Renderer, Renderer = crate::Renderer> = + crate::core::overlay::Element<'a, Message, Theme, Renderer>; pub use iced_widget::overlay::*; } @@ -689,12 +680,8 @@ pub use window::Window; /// A generic widget. /// /// This is an alias of an `iced_native` element with a default `Renderer`. -pub type Element< - 'a, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> = crate::core::Element<'a, Message, Theme, Renderer>; +pub type Element<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> = + crate::core::Element<'a, Message, Theme, Renderer>; /// The result of running an iced program. pub type Result = std::result::Result<(), Error>; @@ -733,8 +720,7 @@ pub type Result = std::result::Result<(), Error>; /// ``` pub fn run( update: impl application::UpdateFn + 'static, - view: impl for<'a> application::ViewFn<'a, State, Message, Theme, Renderer> - + 'static, + view: impl for<'a> application::ViewFn<'a, State, Message, Theme, Renderer> + 'static, ) -> Result where State: Default + 'static, diff --git a/src/time.rs b/src/time.rs index fdd8676340..21a6533776 100644 --- a/src/time.rs +++ b/src/time.rs @@ -4,11 +4,7 @@ pub use crate::core::time::*; #[allow(unused_imports)] #[cfg_attr( docsrs, - doc(cfg(any( - feature = "tokio", - feature = "smol", - target_arch = "wasm32" - ))) + doc(cfg(any(feature = "tokio", feature = "smol", target_arch = "wasm32"))) )] pub use iced_futures::backend::default::time::*; diff --git a/test/src/emulator.rs b/test/src/emulator.rs index bdb2415c15..051a38e47f 100644 --- a/test/src/emulator.rs +++ b/test/src/emulator.rs @@ -68,12 +68,7 @@ impl Emulator

{ /// The [`Emulator`] will send [`Event`] notifications through the provided [`mpsc::Sender`]. /// /// When the [`Emulator`] has finished booting, an [`Event::Ready`] will be produced. - pub fn new( - sender: mpsc::Sender>, - program: &P, - mode: Mode, - size: Size, - ) -> Emulator

{ + pub fn new(sender: mpsc::Sender>, program: &P, mode: Mode, size: Size) -> Emulator

{ Self::with_preset(sender, program, mode, size, None) } @@ -219,8 +214,7 @@ impl Emulator

{ let _ = sender.send(self.window); } - window::Action::GetOldest(sender) - | window::Action::GetLatest(sender) => { + window::Action::GetOldest(sender) | window::Action::GetLatest(sender) => { let _ = sender.send(Some(self.window)); } window::Action::GetSize(id, sender) => { @@ -250,8 +244,7 @@ impl Emulator

{ } window::Action::GetMode(id, sender) => { if id == self.window { - let _ = - sender.send(core::window::Mode::Windowed); + let _ = sender.send(core::window::Mode::Windowed); } } _ => { @@ -321,10 +314,7 @@ impl Emulator

{ }; for event in &events { - if let core::Event::Mouse(mouse::Event::CursorMoved { - position, - }) = event - { + if let core::Event::Mouse(mouse::Event::CursorMoved { position }) = event { self.cursor = mouse::Cursor::Available(*position); } } @@ -340,9 +330,11 @@ impl Emulator

{ self.cache = Some(user_interface.into_cache()); let task = self.runtime.enter(|| { - Task::batch(messages.into_iter().map(|message| { - program.update(&mut self.state, message) - })) + Task::batch( + messages + .into_iter() + .map(|message| program.update(&mut self.state, message)), + ) }); self.resubscribe(program); @@ -421,18 +413,13 @@ impl Emulator

{ self.runtime .track(subscription::into_recipes(self.runtime.enter(|| { program.subscription(&self.state).map(|message| { - Event::Action(Action(Action_::Runtime( - runtime::Action::Output(message), - ))) + Event::Action(Action(Action_::Runtime(runtime::Action::Output(message)))) }) }))); } /// Returns the current view of the [`Emulator`]. - pub fn view( - &self, - program: &P, - ) -> Element<'_, P::Message, P::Theme, P::Renderer> { + pub fn view(&self, program: &P) -> Element<'_, P::Message, P::Theme, P::Renderer> { program.view(&self.state, self.window) } @@ -484,11 +471,9 @@ impl Emulator

{ (self.size.height * scale_factor).round() as u32, ); - let rgba = self.renderer.screenshot( - physical_size, - scale_factor, - style.background_color, - ); + let rgba = self + .renderer + .screenshot(physical_size, scale_factor, style.background_color); window::Screenshot { rgba: Bytes::from(rgba), diff --git a/test/src/error.rs b/test/src/error.rs index 96ec47c4d8..3820a8e04d 100644 --- a/test/src/error.rs +++ b/test/src/error.rs @@ -46,9 +46,7 @@ pub enum Error { instruction: Instruction, }, /// The [`Preset`](crate::program::Preset) of a program could not be found. - #[error( - "the preset \"{name}\" does not exist (available presets: {available:?})" - )] + #[error("the preset \"{name}\" does not exist (available presets: {available:?})")] PresetNotFound { /// The name of the [`Preset`](crate::program::Preset). name: String, diff --git a/test/src/ice.rs b/test/src/ice.rs index bc26fd7721..17ecb080a9 100644 --- a/test/src/ice.rs +++ b/test/src/ice.rs @@ -78,8 +78,7 @@ impl Ice { match field.trim() { "viewport" => { viewport = Some( - if let Some((width, height)) = - value.trim().split_once('x') + if let Some((width, height)) = value.trim().split_once('x') && let Ok(width) = width.parse() && let Ok(height) = height.parse() { @@ -130,11 +129,9 @@ impl Ice { .skip(1) .enumerate() .map(|(i, line)| { - Instruction::parse(line).map_err(|error| { - ParseError::InvalidInstruction { - line: metadata.lines().count() + 1 + i, - error, - } + Instruction::parse(line).map_err(|error| ParseError::InvalidInstruction { + line: metadata.lines().count() + 1 + i, + error, }) }) .collect::, _>>()?; @@ -153,7 +150,7 @@ impl std::fmt::Display for Ice { writeln!( f, "viewport: {width}x{height}", - width = self.viewport.width as u32, // TODO + width = self.viewport.width as u32, // TODO height = self.viewport.height as u32, // TODO )?; diff --git a/test/src/instruction.rs b/test/src/instruction.rs index 926619c919..e9ec6c762d 100644 --- a/test/src/instruction.rs +++ b/test/src/instruction.rs @@ -49,9 +49,7 @@ impl Interaction { pub fn from_event(event: &Event) -> Option { Some(match event { Event::Mouse(mouse) => Self::Mouse(match mouse { - mouse::Event::CursorMoved { position } => { - Mouse::Move(Target::Point(*position)) - } + mouse::Event::CursorMoved { position } => Mouse::Move(Target::Point(*position)), mouse::Event::ButtonPressed(button) => Mouse::Press { button: *button, target: None, @@ -70,9 +68,7 @@ impl Interaction { keyboard::Key::Named(keyboard::key::Named::Escape) => { Keyboard::Press(Key::Escape) } - keyboard::Key::Named(keyboard::key::Named::Tab) => { - Keyboard::Press(Key::Tab) - } + keyboard::Key::Named(keyboard::key::Named::Tab) => Keyboard::Press(Key::Tab), keyboard::Key::Named(keyboard::key::Named::Backspace) => { Keyboard::Press(Key::Backspace) } @@ -85,9 +81,7 @@ impl Interaction { keyboard::Key::Named(keyboard::key::Named::Escape) => { Keyboard::Release(Key::Escape) } - keyboard::Key::Named(keyboard::key::Named::Tab) => { - Keyboard::Release(Key::Tab) - } + keyboard::Key::Named(keyboard::key::Named::Tab) => Keyboard::Release(Key::Tab), keyboard::Key::Named(keyboard::key::Named::Backspace) => { Keyboard::Release(Key::Backspace) } @@ -112,111 +106,94 @@ impl Interaction { /// returned as the second element of the tuple. pub fn merge(self, next: Self) -> (Self, Option) { match (self, next) { - (Self::Mouse(current), Self::Mouse(next)) => { - match (current, next) { - (Mouse::Move(_), Mouse::Move(to)) => { - (Self::Mouse(Mouse::Move(to)), None) - } + (Self::Mouse(current), Self::Mouse(next)) => match (current, next) { + (Mouse::Move(_), Mouse::Move(to)) => (Self::Mouse(Mouse::Move(to)), None), + ( + Mouse::Move(to), + Mouse::Press { + button, + target: None, + }, + ) => ( + Self::Mouse(Mouse::Press { + button, + target: Some(to), + }), + None, + ), + ( + Mouse::Move(to), + Mouse::Release { + button, + target: None, + }, + ) => ( + Self::Mouse(Mouse::Release { + button, + target: Some(to), + }), + None, + ), + ( + Mouse::Press { + button: press, + target: press_at, + }, + Mouse::Release { + button: release, + target: release_at, + }, + ) if press == release + && release_at + .as_ref() + .is_none_or(|release_at| Some(release_at) == press_at.as_ref()) => + { ( - Mouse::Move(to), - Mouse::Press { - button, - target: None, - }, - ) => ( - Self::Mouse(Mouse::Press { - button, - target: Some(to), - }), - None, - ), - ( - Mouse::Move(to), - Mouse::Release { - button, - target: None, - }, - ) => ( - Self::Mouse(Mouse::Release { - button, - target: Some(to), - }), - None, - ), - ( - Mouse::Press { + Self::Mouse(Mouse::Click { button: press, target: press_at, - }, - Mouse::Release { - button: release, - target: release_at, - }, - ) if press == release - && release_at.as_ref().is_none_or(|release_at| { - Some(release_at) == press_at.as_ref() - }) => - { - ( - Self::Mouse(Mouse::Click { - button: press, - target: press_at, - }), - None, - ) - } - ( - Mouse::Press { - button, - target: Some(press_at), - }, - Mouse::Move(move_at), - ) if press_at == move_at => ( - Self::Mouse(Mouse::Press { - button, - target: Some(press_at), }), None, - ), - ( - Mouse::Click { - button, - target: Some(click_at), - }, - Mouse::Move(move_at), - ) if click_at == move_at => ( - Self::Mouse(Mouse::Click { - button, - target: Some(click_at), - }), - None, - ), - (current, next) => { - (Self::Mouse(current), Some(Self::Mouse(next))) - } + ) } - } - (Self::Keyboard(current), Self::Keyboard(next)) => { - match (current, next) { - ( - Keyboard::Typewrite(current), - Keyboard::Typewrite(next), - ) => ( - Self::Keyboard(Keyboard::Typewrite(format!( - "{current}{next}" - ))), - None, - ), - (Keyboard::Press(current), Keyboard::Release(next)) - if current == next => - { - (Self::Keyboard(Keyboard::Type(current)), None) - } - (current, next) => { - (Self::Keyboard(current), Some(Self::Keyboard(next))) - } + ( + Mouse::Press { + button, + target: Some(press_at), + }, + Mouse::Move(move_at), + ) if press_at == move_at => ( + Self::Mouse(Mouse::Press { + button, + target: Some(press_at), + }), + None, + ), + ( + Mouse::Click { + button, + target: Some(click_at), + }, + Mouse::Move(move_at), + ) if click_at == move_at => ( + Self::Mouse(Mouse::Click { + button, + target: Some(click_at), + }), + None, + ), + (current, next) => (Self::Mouse(current), Some(Self::Mouse(next))), + }, + (Self::Keyboard(current), Self::Keyboard(next)) => match (current, next) { + (Keyboard::Typewrite(current), Keyboard::Typewrite(next)) => ( + Self::Keyboard(Keyboard::Typewrite(format!("{current}{next}"))), + None, + ), + (Keyboard::Press(current), Keyboard::Release(next)) if current == next => { + (Self::Keyboard(Keyboard::Type(current)), None) } - } + (current, next) => (Self::Keyboard(current), Some(Self::Keyboard(next))), + }, (current, next) => (current, Some(next)), } } @@ -225,18 +202,12 @@ impl Interaction { /// /// The `find_target` closure must convert a [`Target`] into its screen /// coordinates. - pub fn events( - &self, - find_target: impl FnOnce(&Target) -> Option, - ) -> Option> { - let mouse_move_ = - |to| Event::Mouse(mouse::Event::CursorMoved { position: to }); + pub fn events(&self, find_target: impl FnOnce(&Target) -> Option) -> Option> { + let mouse_move_ = |to| Event::Mouse(mouse::Event::CursorMoved { position: to }); - let mouse_press = - |button| Event::Mouse(mouse::Event::ButtonPressed(button)); + let mouse_press = |button| Event::Mouse(mouse::Event::ButtonPressed(button)); - let mouse_release = - |button| Event::Mouse(mouse::Event::ButtonReleased(button)); + let mouse_release = |button| Event::Mouse(mouse::Event::ButtonReleased(button)); let key_press = |key| simulator::press_key(key, None); @@ -288,9 +259,7 @@ impl Interaction { Keyboard::Press(key) => vec![key_press(*key)], Keyboard::Release(key) => vec![key_release(*key)], Keyboard::Type(key) => vec![key_press(*key), key_release(*key)], - Keyboard::Typewrite(text) => { - simulator::typewrite(text).collect() - } + Keyboard::Typewrite(text) => simulator::typewrite(text).collect(), }, }) } @@ -340,25 +309,13 @@ impl fmt::Display for Mouse { write!(f, "move {}", target) } Mouse::Press { button, target } => { - write!( - f, - "press {}", - format::button_at(*button, target.as_ref()) - ) + write!(f, "press {}", format::button_at(*button, target.as_ref())) } Mouse::Release { button, target } => { - write!( - f, - "release {}", - format::button_at(*button, target.as_ref()) - ) + write!(f, "release {}", format::button_at(*button, target.as_ref())) } Mouse::Click { button, target } => { - write!( - f, - "click {}", - format::button_at(*button, target.as_ref()) - ) + write!(f, "click {}", format::button_at(*button, target.as_ref())) } } } @@ -574,9 +531,7 @@ mod parser { Ok((input, Mouse::Release { button, target })) } - fn mouse_button_at( - input: &str, - ) -> IResult<&str, (mouse::Button, Option)> { + fn mouse_button_at(input: &str) -> IResult<&str, (mouse::Button, Option)> { let (input, button) = mouse_button(input)?; let (input, at) = opt(target).parse(input)?; @@ -691,15 +646,12 @@ mod parser { } fn unicode(input: &str) -> IResult<&str, char> { - let parse_hex = - take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit()); + let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit()); let parse_delimited_hex = preceded(char('u'), delimited(char('{'), parse_hex, char('}'))); - let parse_u32 = map_res(parse_delimited_hex, move |hex| { - u32::from_str_radix(hex, 16) - }); + let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16)); map_opt(parse_u32, std::char::from_u32).parse(input) } @@ -726,15 +678,14 @@ mod parser { preceded(char('\\'), multispace1).parse(input) } - let build_string = - fold(0.., fragment, String::new, |mut string, fragment| { - match fragment { - Fragment::Literal(s) => string.push_str(s), - Fragment::EscapedChar(c) => string.push(c), - Fragment::EscapedWS => {} - } - string - }); + let build_string = fold(0.., fragment, String::new, |mut string, fragment| { + match fragment { + Fragment::Literal(s) => string.push_str(s), + Fragment::EscapedChar(c) => string.push(c), + Fragment::EscapedWS => {} + } + string + }); delimited(char('"'), build_string, char('"')).parse(input) } diff --git a/test/src/lib.rs b/test/src/lib.rs index df67ba1f53..a7de89bb77 100644 --- a/test/src/lib.rs +++ b/test/src/lib.rs @@ -181,13 +181,7 @@ pub fn run( for (file, ice, preset) in tests { let (sender, mut receiver) = mpsc::channel(1); - let mut emulator = Emulator::with_preset( - sender, - &program, - ice.mode, - ice.viewport, - preset, - ); + let mut emulator = Emulator::with_preset(sender, &program, ice.mode, ice.viewport, preset); let mut instructions = ice.instructions.into_iter(); @@ -232,12 +226,7 @@ pub fn screenshot( let (sender, mut receiver) = mpsc::channel(100); - let mut emulator = Emulator::new( - sender, - program, - emulator::Mode::Immediate, - viewport.into(), - ); + let mut emulator = Emulator::new(sender, program, emulator::Mode::Immediate, viewport.into()); let start = Instant::now(); @@ -248,9 +237,7 @@ pub fn screenshot( emulator.perform(program, action); } emulator::Event::Failed(_) => { - unreachable!( - "no instructions should be executed during a screenshot" - ); + unreachable!("no instructions should be executed during a screenshot"); } emulator::Event::Ready => {} } diff --git a/test/src/simulator.rs b/test/src/simulator.rs index 63fbe3f7f3..be8ab0de78 100644 --- a/test/src/simulator.rs +++ b/test/src/simulator.rs @@ -23,12 +23,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; /// A user interface that can be interacted with and inspected programmatically. -pub struct Simulator< - 'a, - Message, - Theme = core::Theme, - Renderer = renderer::Renderer, -> { +pub struct Simulator<'a, Message, Theme = core::Theme, Renderer = renderer::Renderer> { raw: UserInterface<'a, Message, Theme, Renderer>, renderer: Renderer, size: Size, @@ -42,9 +37,7 @@ where Renderer: core::Renderer + core::renderer::Headless, { /// Creates a new [`Simulator`] with default [`Settings`] and a default size (1024x768). - pub fn new( - element: impl Into>, - ) -> Self { + pub fn new(element: impl Into>) -> Self { Self::with_settings(Settings::default(), element) } @@ -117,11 +110,9 @@ where ); match operation.finish() { - widget::operation::Outcome::Some(output) => { - output.ok_or(Error::SelectorNotFound { - selector: description, - }) - } + widget::operation::Outcome::Some(output) => output.ok_or(Error::SelectorNotFound { + selector: description, + }), _ => Err(Error::SelectorNotFound { selector: description, }), @@ -178,10 +169,7 @@ where } /// Simulates the given raw sequence of events in the [`Simulator`]. - pub fn simulate( - &mut self, - events: impl IntoIterator, - ) -> Vec { + pub fn simulate(&mut self, events: impl IntoIterator) -> Vec { let events: Vec = events.into_iter().collect(); let (_state, statuses) = self.raw.update( @@ -225,26 +213,18 @@ where (self.size.height * scale_factor).round() as u32, ); - let rgba = self.renderer.screenshot( - physical_size, - scale_factor, - base.background_color, - ); + let rgba = self + .renderer + .screenshot(physical_size, scale_factor, base.background_color); Ok(Snapshot { - screenshot: window::Screenshot::new( - rgba, - physical_size, - scale_factor, - ), + screenshot: window::Screenshot::new(rgba, physical_size, scale_factor), renderer: self.renderer.name(), }) } /// Turns the [`Simulator`] into the sequence of messages produced by any interactions. - pub fn into_messages( - self, - ) -> impl Iterator + use { + pub fn into_messages(self) -> impl Iterator + use { self.messages.into_iter() } } @@ -367,10 +347,7 @@ pub fn click() -> impl Iterator { } /// Returns the sequence of events of a key press. -pub fn press_key( - key: impl Into, - text: Option, -) -> Event { +pub fn press_key(key: impl Into, text: Option) -> Event { let key = key.into(); Event::Keyboard(keyboard::Event::KeyPressed { diff --git a/tester/src/lib.rs b/tester/src/lib.rs index 334f17bcdb..67d2f0100a 100644 --- a/tester/src/lib.rs +++ b/tester/src/lib.rs @@ -27,8 +27,8 @@ use crate::test::ice; use crate::test::instruction; use crate::test::{Emulator, Ice, Instruction}; use crate::widget::{ - button, center, column, combo_box, container, pick_list, row, rule, - scrollable, slider, space, stack, text, text_editor, themer, + button, center, column, combo_box, container, pick_list, row, rule, scrollable, slider, space, + stack, text, text_editor, themer, }; use std::ops::RangeInclusive; @@ -81,11 +81,7 @@ where (Tester::new(&self.program), Task::none()) } - fn update( - &self, - state: &mut Self::State, - message: Self::Message, - ) -> Task { + fn update(&self, state: &mut Self::State, message: Self::Message) -> Task { state.tick(&self.program, message.0).map(Message) } @@ -255,11 +251,9 @@ impl Tester

{ return Task::none(); }; - while let Some(Instruction::Interact( - instruction::Interaction::Mouse(instruction::Mouse::Move( - _, - )), - )) = self.instructions.last() + while let Some(Instruction::Interact(instruction::Interaction::Mouse( + instruction::Mouse::Move(_), + ))) = self.instructions.last() { let _ = self.instructions.pop(); } @@ -306,8 +300,7 @@ impl Tester

{ .and_then(|file| { task::blocking(move |mut sender| { let _ = sender.try_send(Ice::parse( - &fs::read_to_string(file.path()) - .unwrap_or_default(), + &fs::read_to_string(file.path()).unwrap_or_default(), )); }) }) @@ -336,9 +329,7 @@ impl Tester

{ return; }; - let _ = thread::spawn(move || { - fs::write(file.path(), ice.to_string()) - }); + let _ = thread::spawn(move || fs::write(file.path(), ice.to_string())); }) .discard() } @@ -415,16 +406,11 @@ impl Tester

{ State::Recording { emulator } | State::Playing { emulator, .. } => { emulator.theme(program) } - State::Asserting { state, window, .. } => { - program.theme(state, *window) - } + State::Asserting { state, window, .. } => program.theme(state, *window), } } - fn preset<'a>( - &self, - program: &'a P, - ) -> Option<&'a program::Preset> { + fn preset<'a>(&self, program: &'a P) -> Option<&'a program::Preset> { self.preset.as_ref().and_then(|preset| { program .presets() @@ -466,8 +452,7 @@ impl Tester

{ emulator::Event::Ready => { *current += 1; - if let Some(instruction) = - self.instructions.get(*current - 1).cloned() + if let Some(instruction) = self.instructions.get(*current - 1).cloned() { emulator.run(program, instruction); } @@ -477,9 +462,7 @@ impl Tester

{ } } }, - State::Empty - | State::Idle { .. } - | State::Asserting { .. } => {} + State::Empty | State::Idle { .. } | State::Asserting { .. } => {} } Task::none() @@ -488,16 +471,13 @@ impl Tester

{ let mut interaction = Some(interaction); while let Some(new_interaction) = interaction.take() { - if let Some(Instruction::Interact(last_interaction)) = - self.instructions.pop() - { + if let Some(Instruction::Interact(last_interaction)) = self.instructions.pop() { let (merged_interaction, new_interaction) = last_interaction.merge(new_interaction); if let Some(new_interaction) = new_interaction { - self.instructions.push(Instruction::Interact( - merged_interaction, - )); + self.instructions + .push(Instruction::Interact(merged_interaction)); self.instructions .push(Instruction::Interact(new_interaction)); @@ -520,33 +500,29 @@ impl Tester

{ return Task::none(); }; - *last_interaction = - if let Some(last_interaction) = last_interaction.take() { - let (merged, new) = last_interaction.merge(interaction); + *last_interaction = if let Some(last_interaction) = last_interaction.take() { + let (merged, new) = last_interaction.merge(interaction); - Some(new.unwrap_or(merged)) - } else { - Some(interaction) - }; + Some(new.unwrap_or(merged)) + } else { + Some(interaction) + }; let Some(interaction) = last_interaction.take() else { return Task::none(); }; - let instruction::Interaction::Mouse( - instruction::Mouse::Click { - button: mouse::Button::Left, - target: Some(instruction::Target::Text(text)), - }, - ) = interaction + let instruction::Interaction::Mouse(instruction::Mouse::Click { + button: mouse::Button::Left, + target: Some(instruction::Target::Text(text)), + }) = interaction else { *last_interaction = Some(interaction); return Task::none(); }; - self.instructions.push(Instruction::Expect( - instruction::Expectation::Text(text), - )); + self.instructions + .push(Instruction::Expect(instruction::Expectation::Text(text))); Task::none() } @@ -570,56 +546,39 @@ impl Tester

{ }, }; - container(row![icon.size(14), label].align_y(Center).spacing(8)) - .style(|theme: &Theme| { + container(row![icon.size(14), label].align_y(Center).spacing(8)).style( + |theme: &Theme| { let palette = theme.extended_palette(); container::Style { text_color: Some(match &self.state { - State::Empty | State::Idle { .. } => { - palette.background.strongest.color - } - State::Recording { .. } => { - palette.danger.base.color - } - State::Asserting { .. } => { - palette.warning.base.color - } + State::Empty | State::Idle { .. } => palette.background.strongest.color, + State::Recording { .. } => palette.danger.base.color, + State::Asserting { .. } => palette.warning.base.color, State::Playing { outcome, .. } => match outcome { Outcome::Running => theme.palette().primary, Outcome::Failed => theme.palette().danger, - Outcome::Success => { - theme - .extended_palette() - .success - .strong - .color - } + Outcome::Success => theme.extended_palette().success.strong.color, }, }), ..container::Style::default() } - }) + }, + ) }; let view = match &self.state { State::Empty => Element::from(space()), - State::Idle { state } => { - program.view(state, window).map(Tick::Program) - } - State::Recording { emulator } => { - recorder(emulator.view(program).map(Tick::Program)) - .on_record(Tick::Record) - .into() - } + State::Idle { state } => program.view(state, window).map(Tick::Program), + State::Recording { emulator } => recorder(emulator.view(program).map(Tick::Program)) + .on_record(Tick::Record) + .into(), State::Asserting { state, window, .. } => { recorder(program.view(state, *window).map(Tick::Program)) .on_record(Tick::Assert) .into() } - State::Playing { emulator, .. } => { - emulator.view(program).map(Tick::Program) - } + State::Playing { emulator, .. } => emulator.view(program).map(Tick::Program), }; let viewport = container( @@ -638,9 +597,7 @@ impl Tester

{ container::Style { border: border::width(2.0).color(match &self.state { - State::Empty | State::Idle { .. } => { - palette.background.strongest.color - } + State::Empty | State::Idle { .. } => palette.background.strongest.color, State::Recording { .. } => palette.danger.base.color, State::Asserting { .. } => palette.warning.weak.color, State::Playing { outcome, .. } => match outcome { @@ -655,15 +612,13 @@ impl Tester

{ .padding(10); row![ - center(column![status, viewport].spacing(10).align_x(Right)) - .padding(10), + center(column![status, viewport].spacing(10).align_x(Right)).padding(10), rule::vertical(1).style(rule::weak), container(self.controls().map(Tick::Tester)) .width(250) .padding(10) - .style(|theme| container::Style::default().background( - theme.extended_palette().background.weakest.color - )), + .style(|theme| container::Style::default() + .background(theme.extended_palette().background.weakest.color)), ] .into() } @@ -702,13 +657,9 @@ impl Tester

{ .size(14) .width(Fill); - let mode = pick_list( - emulator::Mode::ALL, - Some(self.mode), - Event::ModeSelected, - ) - .text_size(14) - .width(Fill); + let mode = pick_list(emulator::Mode::ALL, Some(self.mode), Event::ModeSelected) + .text_size(14) + .width(Fill); let player = { let instructions = if let Some(edit) = &self.edit { @@ -728,57 +679,56 @@ impl Tester

{ )) } else { scrollable( - column(self.instructions.iter().enumerate().map( - |(i, instruction)| { - text(instruction.to_string()) - .wrapping(text::Wrapping::None) // TODO: Ellipsize? - .size(10) - .font(Font::MONOSPACE) - .style(move |theme: &Theme| text::Style { - color: match &self.state { - State::Playing { - current, - outcome, - .. - } => { - if *current == i + 1 { - Some(match outcome { - Outcome::Running => { - theme.palette().primary - } - Outcome::Failed => { - theme - .extended_palette() - .danger - .strong - .color - } - Outcome::Success => { + column( + self.instructions + .iter() + .enumerate() + .map(|(i, instruction)| { + text(instruction.to_string()) + .wrapping(text::Wrapping::None) // TODO: Ellipsize? + .size(10) + .font(Font::MONOSPACE) + .style(move |theme: &Theme| text::Style { + color: match &self.state { + State::Playing { + current, outcome, .. + } => { + if *current == i + 1 { + Some(match outcome { + Outcome::Running => theme.palette().primary, + Outcome::Failed => { + theme + .extended_palette() + .danger + .strong + .color + } + Outcome::Success => { + theme + .extended_palette() + .success + .strong + .color + } + }) + } else if *current > i + 1 { + Some( theme .extended_palette() .success .strong - .color - } - }) - } else if *current > i + 1 { - Some( - theme - .extended_palette() - .success - .strong - .color, - ) - } else { - None + .color, + ) + } else { + None + } } - } - _ => None, - }, - }) - .into() - }, - )) + _ => None, + }, + }) + .into() + }), + ) .spacing(5), ) .width(Fill) @@ -792,9 +742,8 @@ impl Tester

{ }; let play = control(icon::play()).on_press_maybe( - (!matches!(self.state, State::Recording { .. }) - && !self.instructions.is_empty()) - .then_some(Event::Play), + (!matches!(self.state, State::Recording { .. }) && !self.instructions.is_empty()) + .then_some(Event::Play), ); let record = if let State::Recording { .. } = &self.state { @@ -819,8 +768,7 @@ impl Tester

{ ) .style(button::success); - let controls = - row![import, export, play, record].height(30).spacing(10); + let controls = row![import, export, play, record].height(30).spacing(10); column![instructions, controls].spacing(10).align_x(Center) }; @@ -915,13 +863,10 @@ where rail: slider::Rail { backgrounds: ( match status { - slider::Status::Active - | slider::Status::Dragged => { + slider::Status::Active | slider::Status::Dragged => { palette.background.strongest.color } - slider::Status::Hovered => { - palette.background.stronger.color - } + slider::Status::Hovered => palette.background.stronger.color, } .into(), Color::TRANSPARENT.into(), diff --git a/tester/src/recorder.rs b/tester/src/recorder.rs index 890acd819d..4962870e13 100644 --- a/tester/src/recorder.rs +++ b/tester/src/recorder.rs @@ -7,8 +7,8 @@ use crate::core::widget; use crate::core::widget::operation; use crate::core::widget::tree; use crate::core::{ - self, Clipboard, Color, Element, Event, Layout, Length, Point, Rectangle, - Shell, Size, Vector, Widget, + self, Clipboard, Color, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, + Widget, }; use crate::test::Selector; use crate::test::instruction::{Interaction, Mouse, Target}; @@ -27,9 +27,7 @@ pub struct Recorder<'a, Message, Theme, Renderer> { } impl<'a, Message, Theme, Renderer> Recorder<'a, Message, Theme, Renderer> { - pub fn new( - content: impl Into>, - ) -> Self { + pub fn new(content: impl Into>) -> Self { Self { content: content.into(), on_record: None, @@ -37,10 +35,7 @@ impl<'a, Message, Theme, Renderer> Recorder<'a, Message, Theme, Renderer> { } } - pub fn on_record( - mut self, - on_record: impl Fn(Interaction) -> Message + 'a, - ) -> Self { + pub fn on_record(mut self, on_record: impl Fn(Interaction) -> Message + 'a) -> Self { self.on_record = Some(Box::new(on_record)); self } @@ -140,11 +135,9 @@ where renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { - self.content.as_widget_mut().layout( - &mut tree.children[0], - renderer, - limits, - ) + self.content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) } fn draw( @@ -208,12 +201,9 @@ where renderer: &Renderer, operation: &mut dyn widget::Operation, ) { - self.content.as_widget_mut().operate( - &mut tree.children[0], - layout, - renderer, - operation, - ); + self.content + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); } fn overlay<'a>( @@ -400,14 +390,13 @@ fn record( return; } - let interaction = - if let Event::Mouse(mouse::Event::CursorMoved { position }) = event { - Interaction::from_event(&Event::Mouse(mouse::Event::CursorMoved { - position: *position - (bounds.position() - Point::ORIGIN), - })) - } else { - Interaction::from_event(event) - }; + let interaction = if let Event::Mouse(mouse::Event::CursorMoved { position }) = event { + Interaction::from_event(&Event::Mouse(mouse::Event::CursorMoved { + position: *position - (bounds.position() - Point::ORIGIN), + })) + } else { + Interaction::from_event(event) + }; let Some(mut interaction) = interaction else { return; @@ -463,24 +452,23 @@ fn find_text( return None; }; - let (content, visible_bounds) = - targets.into_iter().rev().find_map(|target| { - if let selector::Target::Text { - content, - visible_bounds, - .. - } - | selector::Target::TextInput { - content, - visible_bounds, - .. - } = target - { - Some((content, visible_bounds)) - } else { - None - } - })?; + let (content, visible_bounds) = targets.into_iter().rev().find_map(|target| { + if let selector::Target::Text { + content, + visible_bounds, + .. + } + | selector::Target::TextInput { + content, + visible_bounds, + .. + } = target + { + Some((content, visible_bounds)) + } else { + None + } + })?; let mut by_text = content.clone().find_all(); operate(&mut operation::black_box(&mut by_text)); diff --git a/tiny_skia/src/engine.rs b/tiny_skia/src/engine.rs index 61323f0426..060ba5ea05 100644 --- a/tiny_skia/src/engine.rs +++ b/tiny_skia/src/engine.rs @@ -2,9 +2,7 @@ use crate::Primitive; use tiny_skia::Transform; use crate::core::renderer::Quad; -use crate::core::{ - Background, Color, Gradient, Rectangle, Size, Transformation, Vector, -}; +use crate::core::{Background, Color, Gradient, Rectangle, Size, Transformation, Vector}; use crate::graphics::{Image, Text}; use crate::text; @@ -44,8 +42,8 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within_strict(&clip_bounds)) - .then_some(clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within_strict(&clip_bounds)).then_some(clip_mask as &_); let transform = into_transform(transformation); @@ -101,48 +99,37 @@ impl Engine { let colors = (y..y + height) .flat_map(|y| (x..x + width).map(move |x| (x as f32, y as f32))) .filter_map(|(x, y)| { - tiny_skia::Size::from_wh(half_width, half_height).map( - |size| { - let shadow_distance = rounded_box_sdf( - Vector::new( - x - physical_bounds.position().x - - (shadow.offset.x - * transformation.scale_factor()) - - half_width, - y - physical_bounds.position().y - - (shadow.offset.y - * transformation.scale_factor()) - - half_height, - ), - size, - &radii, - ) - .max(0.0); - let shadow_alpha = 1.0 - - smoothstep( - -shadow.blur_radius - * transformation.scale_factor(), - shadow.blur_radius - * transformation.scale_factor(), - shadow_distance, - ); - - let mut color = into_color(shadow.color); - color.apply_opacity(shadow_alpha); - - color.to_color_u8().premultiply() - }, - ) + tiny_skia::Size::from_wh(half_width, half_height).map(|size| { + let shadow_distance = rounded_box_sdf( + Vector::new( + x - physical_bounds.position().x + - (shadow.offset.x * transformation.scale_factor()) + - half_width, + y - physical_bounds.position().y + - (shadow.offset.y * transformation.scale_factor()) + - half_height, + ), + size, + &radii, + ) + .max(0.0); + let shadow_alpha = 1.0 + - smoothstep( + -shadow.blur_radius * transformation.scale_factor(), + shadow.blur_radius * transformation.scale_factor(), + shadow_distance, + ); + + let mut color = into_color(shadow.color); + color.apply_opacity(shadow_alpha); + + color.to_color_u8().premultiply() + }) }) .collect(); if let Some(pixmap) = tiny_skia::IntSize::from_wh(width, height) - .and_then(|size| { - tiny_skia::Pixmap::from_vec( - bytemuck::cast_vec(colors), - size, - ) - }) + .and_then(|size| tiny_skia::Pixmap::from_vec(bytemuck::cast_vec(colors), size)) { pixels.draw_pixmap( x as i32, @@ -159,12 +146,9 @@ impl Engine { &path, &tiny_skia::Paint { shader: match background { - Background::Color(color) => { - tiny_skia::Shader::SolidColor(into_color(*color)) - } + Background::Color(color) => tiny_skia::Shader::SolidColor(into_color(*color)), Background::Gradient(Gradient::Linear(linear)) => { - let (start, end) = - linear.angle.to_distance(&quad.bounds); + let (start, end) = linear.angle.to_distance(&quad.bounds); let stops: Vec = linear .stops @@ -191,10 +175,7 @@ impl Engine { }, tiny_skia::Point { x: end.x, y: end.y }, if stops.is_empty() { - vec![tiny_skia::GradientStop::new( - 0.0, - tiny_skia::Color::BLACK, - )] + vec![tiny_skia::GradientStop::new(0.0, tiny_skia::Color::BLACK)] } else { stops }, @@ -241,15 +222,12 @@ impl Engine { // Stroking a path works well in this case if is_simple_border { - let border_path = - rounded_rectangle(border_bounds, border_radius); + let border_path = rounded_rectangle(border_bounds, border_radius); pixels.stroke_path( &border_path, &tiny_skia::Paint { - shader: tiny_skia::Shader::SolidColor(into_color( - quad.border.color, - )), + shader: tiny_skia::Shader::SolidColor(into_color(quad.border.color)), anti_alias: true, ..tiny_skia::Paint::default() }, @@ -263,17 +241,13 @@ impl Engine { } else { // Draw corners that have too small border radii as having no border radius, // but mask them with the rounded rectangle with the correct border radius. - let mut temp_pixmap = tiny_skia::Pixmap::new( - path_bounds.width as u32, - path_bounds.height as u32, - ) - .unwrap(); - - let mut quad_mask = tiny_skia::Mask::new( - path_bounds.width as u32, - path_bounds.height as u32, - ) - .unwrap(); + let mut temp_pixmap = + tiny_skia::Pixmap::new(path_bounds.width as u32, path_bounds.height as u32) + .unwrap(); + + let mut quad_mask = + tiny_skia::Mask::new(path_bounds.width as u32, path_bounds.height as u32) + .unwrap(); let zero_bounds = Rectangle { x: 0.0, @@ -283,12 +257,7 @@ impl Engine { }; let path = rounded_rectangle(zero_bounds, fill_border_radius); - quad_mask.fill_path( - &path, - tiny_skia::FillRule::EvenOdd, - true, - transform, - ); + quad_mask.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, transform); let path_bounds = Rectangle { x: (border_width / 2.0), y: (border_width / 2.0), @@ -296,15 +265,12 @@ impl Engine { height: path_bounds.height - border_width, }; - let border_radius_path = - rounded_rectangle(path_bounds, border_radius); + let border_radius_path = rounded_rectangle(path_bounds, border_radius); temp_pixmap.stroke_path( &border_radius_path, &tiny_skia::Paint { - shader: tiny_skia::Shader::SolidColor(into_color( - quad.border.color, - )), + shader: tiny_skia::Shader::SolidColor(into_color(quad.border.color)), anti_alias: true, ..tiny_skia::Paint::default() }, @@ -345,28 +311,26 @@ impl Engine { transformation: local_transformation, } => { let transformation = transformation * *local_transformation; - let Some(clip_bounds) = clip_bounds - .intersection(&(*local_clip_bounds * transformation)) + let Some(clip_bounds) = + clip_bounds.intersection(&(*local_clip_bounds * transformation)) else { return; }; let physical_bounds = - Rectangle::new(*position, paragraph.min_bounds) - * transformation; + Rectangle::new(*position, paragraph.min_bounds) * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } - let clip_mask = - match physical_bounds.is_within_strict(&clip_bounds) { - true => None, - false => { - adjust_clip_mask(clip_mask, clip_bounds); - Some(clip_mask as &_) - } - }; + let clip_mask = match physical_bounds.is_within_strict(&clip_bounds) { + true => None, + false => { + adjust_clip_mask(clip_mask, clip_bounds); + Some(clip_mask as &_) + } + }; self.text_pipeline.draw_paragraph( paragraph, @@ -385,27 +349,25 @@ impl Engine { transformation: local_transformation, } => { let transformation = transformation * *local_transformation; - let Some(clip_bounds) = clip_bounds - .intersection(&(*local_clip_bounds * transformation)) + let Some(clip_bounds) = + clip_bounds.intersection(&(*local_clip_bounds * transformation)) else { return; }; - let physical_bounds = - Rectangle::new(*position, editor.bounds) * transformation; + let physical_bounds = Rectangle::new(*position, editor.bounds) * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } - let clip_mask = - match physical_bounds.is_within_strict(&clip_bounds) { - true => None, - false => { - adjust_clip_mask(clip_mask, clip_bounds); - Some(clip_mask as &_) - } - }; + let clip_mask = match physical_bounds.is_within_strict(&clip_bounds) { + true => None, + false => { + adjust_clip_mask(clip_mask, clip_bounds); + Some(clip_mask as &_) + } + }; self.text_pipeline.draw_editor( editor, @@ -434,14 +396,13 @@ impl Engine { return; } - let clip_mask = - match physical_bounds.is_within_strict(&clip_bounds) { - true => None, - false => { - adjust_clip_mask(clip_mask, clip_bounds); - Some(clip_mask as &_) - } - }; + let clip_mask = match physical_bounds.is_within_strict(&clip_bounds) { + true => None, + false => { + adjust_clip_mask(clip_mask, clip_bounds); + Some(clip_mask as &_) + } + }; self.text_pipeline.draw_cached( content, @@ -481,8 +442,8 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within(&clip_bounds)) - .then_some(clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); self.text_pipeline.draw_raw( &buffer, @@ -521,8 +482,8 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within(&clip_bounds)) - .then_some(clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); pixels.fill_path( path, @@ -552,8 +513,8 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within(&clip_bounds)) - .then_some(clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); pixels.stroke_path( path, @@ -583,17 +544,14 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within(&_clip_bounds)) - .then_some(_clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within(&_clip_bounds)).then_some(_clip_mask as &_); let center = physical_bounds.center(); let radians = f32::from(image.rotation); - let transform = Transform::default().post_rotate_at( - radians.to_degrees(), - center.x, - center.y, - ); + let transform = + Transform::default().post_rotate_at(radians.to_degrees(), center.x, center.y); self.raster_pipeline.draw( &image.handle, @@ -614,8 +572,8 @@ impl Engine { return; } - let clip_mask = (!physical_bounds.is_within(&_clip_bounds)) - .then_some(_clip_mask as &_); + let clip_mask = + (!physical_bounds.is_within(&_clip_bounds)).then_some(_clip_mask as &_); let center = physical_bounds.center(); let radians = f32::from(svg.rotation); @@ -638,15 +596,11 @@ impl Engine { } #[cfg(not(feature = "image"))] Image::Raster { .. } => { - log::warn!( - "Unsupported primitive in `iced_tiny_skia`: {image:?}", - ); + log::warn!("Unsupported primitive in `iced_tiny_skia`: {image:?}",); } #[cfg(not(feature = "svg"))] Image::Vector { .. } => { - log::warn!( - "Unsupported primitive in `iced_tiny_skia`: {image:?}", - ); + log::warn!("Unsupported primitive in `iced_tiny_skia`: {image:?}",); } } } @@ -680,25 +634,13 @@ fn into_transform(transformation: Transformation) -> tiny_skia::Transform { } } -fn rounded_rectangle( - bounds: Rectangle, - border_radius: [f32; 4], -) -> tiny_skia::Path { +fn rounded_rectangle(bounds: Rectangle, border_radius: [f32; 4]) -> tiny_skia::Path { let [top_left, top_right, bottom_right, bottom_left] = border_radius; - if top_left == 0.0 - && top_right == 0.0 - && bottom_right == 0.0 - && bottom_left == 0.0 - { + if top_left == 0.0 && top_right == 0.0 && bottom_right == 0.0 && bottom_left == 0.0 { return tiny_skia::PathBuilder::from_rect( - tiny_skia::Rect::from_xywh( - bounds.x, - bounds.y, - bounds.width, - bounds.height, - ) - .expect("Build quad rectangle"), + tiny_skia::Rect::from_xywh(bounds.x, bounds.y, bounds.width, bounds.height) + .expect("Build quad rectangle"), ); } @@ -830,11 +772,7 @@ fn smoothstep(a: f32, b: f32, x: f32) -> f32 { x * x * (3.0 - 2.0 * x) } -fn rounded_box_sdf( - to_center: Vector, - size: tiny_skia::Size, - radii: &[f32], -) -> f32 { +fn rounded_box_sdf(to_center: Vector, size: tiny_skia::Size, radii: &[f32]) -> f32 { let radius = match (to_center.x > 0.0, to_center.y > 0.0) { (true, true) => radii[2], (true, false) => radii[1], @@ -854,13 +792,7 @@ pub fn adjust_clip_mask(clip_mask: &mut tiny_skia::Mask, bounds: Rectangle) { let path = { let mut builder = tiny_skia::PathBuilder::new(); builder.push_rect( - tiny_skia::Rect::from_xywh( - bounds.x, - bounds.y, - bounds.width, - bounds.height, - ) - .unwrap(), + tiny_skia::Rect::from_xywh(bounds.x, bounds.y, bounds.width, bounds.height).unwrap(), ); builder.finish().unwrap() diff --git a/tiny_skia/src/geometry.rs b/tiny_skia/src/geometry.rs index a45d952213..a971d96519 100644 --- a/tiny_skia/src/geometry.rs +++ b/tiny_skia/src/geometry.rs @@ -96,9 +96,7 @@ impl geometry::frame::Backend for Frame { } fn fill(&mut self, path: &Path, fill: impl Into) { - let Some(path) = - convert_path(path).and_then(|path| path.transform(self.transform)) - else { + let Some(path) = convert_path(path).and_then(|path| path.transform(self.transform)) else { return; }; @@ -114,12 +112,7 @@ impl geometry::frame::Backend for Frame { }); } - fn fill_rectangle( - &mut self, - top_left: Point, - size: Size, - fill: impl Into, - ) { + fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into) { let Some(path) = convert_path(&Path::rectangle(top_left, size)) .and_then(|path| path.transform(self.transform)) else { @@ -142,9 +135,7 @@ impl geometry::frame::Backend for Frame { } fn stroke<'a>(&mut self, path: &Path, stroke: impl Into>) { - let Some(path) = - convert_path(path).and_then(|path| path.transform(self.transform)) - else { + let Some(path) = convert_path(path).and_then(|path| path.transform(self.transform)) else { return; }; @@ -161,12 +152,7 @@ impl geometry::frame::Backend for Frame { }); } - fn stroke_rectangle<'a>( - &mut self, - top_left: Point, - size: Size, - stroke: impl Into>, - ) { + fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into>) { self.stroke(&Path::rectangle(top_left, size), stroke); } @@ -175,17 +161,10 @@ impl geometry::frame::Backend for Frame { let (scale_x, scale_y) = self.transform.get_scale(); - if !self.transform.has_skew() - && scale_x == scale_y - && scale_x > 0.0 - && scale_y > 0.0 - { + if !self.transform.has_skew() && scale_x == scale_y && scale_x > 0.0 && scale_y > 0.0 { let (bounds, size, line_height) = if self.transform.is_identity() { ( - Rectangle::new( - text.position, - Size::new(text.max_width, f32::INFINITY), - ), + Rectangle::new(text.position, Size::new(text.max_width, f32::INFINITY)), text.size, text.line_height, ) @@ -200,12 +179,8 @@ impl geometry::frame::Backend for Frame { let size = text.size.0 * scale_y; let line_height = match text.line_height { - LineHeight::Absolute(size) => { - LineHeight::Absolute(Pixels(size.0 * scale_y)) - } - LineHeight::Relative(factor) => { - LineHeight::Relative(factor) - } + LineHeight::Absolute(size) => LineHeight::Absolute(Pixels(size.0 * scale_y)), + LineHeight::Relative(factor) => LineHeight::Relative(factor), }; ( @@ -238,11 +213,7 @@ impl geometry::frame::Backend for Frame { } } - fn stroke_text<'a>( - &mut self, - text: impl Into, - stroke: impl Into>, - ) { + fn stroke_text<'a>(&mut self, text: impl Into, stroke: impl Into>) { let text = text.into(); let stroke = stroke.into(); @@ -268,14 +239,13 @@ impl geometry::frame::Backend for Frame { } fn translate(&mut self, translation: Vector) { - self.transform = - self.transform.pre_translate(translation.x, translation.y); + self.transform = self.transform.pre_translate(translation.x, translation.y); } fn rotate(&mut self, angle: impl Into) { - self.transform = self.transform.pre_concat( - tiny_skia::Transform::from_rotate(angle.into().0.to_degrees()), - ); + self.transform = self.transform.pre_concat(tiny_skia::Transform::from_rotate( + angle.into().0.to_degrees(), + )); } fn scale(&mut self, scale: impl Into) { @@ -302,8 +272,7 @@ impl geometry::frame::Backend for Frame { fn draw_image(&mut self, bounds: Rectangle, image: impl Into) { let mut image = image.into(); - let (bounds, external_rotation) = - transform_rectangle(bounds, self.transform); + let (bounds, external_rotation) = transform_rectangle(bounds, self.transform); image.rotation += external_rotation; @@ -317,8 +286,7 @@ impl geometry::frame::Backend for Frame { fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into) { let mut svg = svg.into(); - let (bounds, external_rotation) = - transform_rectangle(bounds, self.transform); + let (bounds, external_rotation) = transform_rectangle(bounds, self.transform); svg.rotation += external_rotation; @@ -401,8 +369,7 @@ fn convert_path(path: &Path) -> Option { builder.move_to(from.x, from.y); } - builder - .cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y); + builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y); last_point = to; } @@ -461,10 +428,7 @@ pub fn into_paint(style: Style) -> tiny_skia::Paint<'static> { y: linear.end.y, }, if stops.is_empty() { - vec![tiny_skia::GradientStop::new( - 0.0, - tiny_skia::Color::BLACK, - )] + vec![tiny_skia::GradientStop::new(0.0, tiny_skia::Color::BLACK)] } else { stops }, diff --git a/tiny_skia/src/layer.rs b/tiny_skia/src/layer.rs index 43ddbde5c5..3095338601 100644 --- a/tiny_skia/src/layer.rs +++ b/tiny_skia/src/layer.rs @@ -1,8 +1,6 @@ use crate::Primitive; use crate::core::renderer::Quad; -use crate::core::{ - self, Background, Color, Point, Rectangle, Svg, Transformation, -}; +use crate::core::{self, Background, Color, Point, Rectangle, Svg, Transformation}; use crate::graphics::damage; use crate::graphics::layer; use crate::graphics::text::{Editor, Paragraph, Raw, Text}; @@ -83,8 +81,7 @@ impl Layer { bounds: Rectangle::new(position, text.bounds) * transformation, color, size: text.size * transformation.scale_factor(), - line_height: text.line_height.to_absolute(text.size) - * transformation.scale_factor(), + line_height: text.line_height.to_absolute(text.size) * transformation.scale_factor(), font: text.font, align_x: text.align_x, align_y: text.align_y, @@ -95,11 +92,7 @@ impl Layer { self.text.push(Item::Live(text)); } - pub fn draw_text_raw( - &mut self, - raw: graphics::text::Raw, - transformation: Transformation, - ) { + pub fn draw_text_raw(&mut self, raw: graphics::text::Raw, transformation: Transformation) { let raw = Text::Raw { raw, transformation, @@ -165,8 +158,7 @@ impl Layer { ) { let image = Image::Raster { image: core::Image { - border_radius: image.border_radius - * transformation.scale_factor(), + border_radius: image.border_radius * transformation.scale_factor(), ..image }, bounds: bounds * transformation, @@ -268,15 +260,13 @@ impl Layer { ¤t.primitives, |item| match item { Item::Live(primitive) => vec![primitive.visible_bounds()], - Item::Group(primitives, group_bounds, transformation) => { - primitives - .as_slice() - .iter() - .map(Primitive::visible_bounds) - .map(|bounds| bounds * *transformation) - .filter_map(|bounds| bounds.intersection(group_bounds)) - .collect() - } + Item::Group(primitives, group_bounds, transformation) => primitives + .as_slice() + .iter() + .map(Primitive::visible_bounds) + .map(|bounds| bounds * *transformation) + .filter_map(|bounds| bounds.intersection(group_bounds)) + .collect(), Item::Cached(_primitives, bounds, _transformation) => { vec![*bounds] } @@ -406,16 +396,16 @@ impl Item { pub fn transformation(&self) -> Transformation { match self { Item::Live(_) => Transformation::IDENTITY, - Item::Group(_, _, transformation) - | Item::Cached(_, _, transformation) => *transformation, + Item::Group(_, _, transformation) | Item::Cached(_, _, transformation) => { + *transformation + } } } pub fn clip_bounds(&self) -> Rectangle { match self { Item::Live(_) => Rectangle::INFINITE, - Item::Group(_, clip_bounds, _) - | Item::Cached(_, clip_bounds, _) => *clip_bounds, + Item::Group(_, clip_bounds, _) | Item::Cached(_, clip_bounds, _) => *clip_bounds, } } diff --git a/tiny_skia/src/lib.rs b/tiny_skia/src/lib.rs index b29e9eef0a..067731df35 100644 --- a/tiny_skia/src/lib.rs +++ b/tiny_skia/src/lib.rs @@ -29,9 +29,7 @@ pub use settings::Settings; pub use geometry::Geometry; use crate::core::renderer; -use crate::core::{ - Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, -}; +use crate::core::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation}; use crate::engine::Engine; use crate::graphics::Viewport; use crate::graphics::compositor; @@ -92,9 +90,7 @@ impl Renderer { pixels.fill_path( &path, &tiny_skia::Paint { - shader: tiny_skia::Shader::SolidColor(engine::into_color( - background_color, - )), + shader: tiny_skia::Shader::SolidColor(engine::into_color(background_color)), anti_alias: false, blend_mode: tiny_skia::BlendMode::Source, ..Default::default() @@ -105,8 +101,7 @@ impl Renderer { ); for layer in self.layers.iter() { - let Some(layer_bounds) = - damage_bounds.intersection(&(layer.bounds * scale_factor)) + let Some(layer_bounds) = damage_bounds.intersection(&(layer.bounds * scale_factor)) else { continue; }; @@ -132,9 +127,8 @@ impl Renderer { let render_span = debug::render(debug::Primitive::Triangle); for group in &layer.primitives { - let Some(group_bounds) = (group.clip_bounds() - * scale_factor) - .intersection(&layer_bounds) + let Some(group_bounds) = + (group.clip_bounds() * scale_factor).intersection(&layer_bounds) else { continue; }; @@ -144,8 +138,7 @@ impl Renderer { for primitive in group.as_slice() { self.engine.draw_primitive( primitive, - Transformation::scale(scale_factor) - * group.transformation(), + Transformation::scale(scale_factor) * group.transformation(), pixels, clip_mask, group_bounds, @@ -181,8 +174,7 @@ impl Renderer { for text in group.as_slice() { self.engine.draw_text( text, - Transformation::scale(scale_factor) - * group.transformation(), + Transformation::scale(scale_factor) * group.transformation(), pixels, clip_mask, layer_bounds, @@ -216,11 +208,7 @@ impl core::Renderer for Renderer { self.layers.pop_transformation(); } - fn fill_quad( - &mut self, - quad: renderer::Quad, - background: impl Into, - ) { + fn fill_quad(&mut self, quad: renderer::Quad, background: impl Into) { let (layer, transformation) = self.layers.current_mut(); layer.draw_quad(quad, background.into(), transformation); } @@ -232,9 +220,7 @@ impl core::Renderer for Renderer { fn allocate_image( &mut self, _handle: &core::image::Handle, - callback: impl FnOnce(Result) - + Send - + 'static, + callback: impl FnOnce(Result) + Send + 'static, ) { #[cfg(feature = "image")] #[allow(unsafe_code)] @@ -277,13 +263,7 @@ impl core::text::Renderer for Renderer { clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); - layer.draw_paragraph( - text, - position, - color, - clip_bounds, - transformation, - ); + layer.draw_paragraph(text, position, color, clip_bounds, transformation); } fn fill_editor( @@ -340,11 +320,7 @@ impl graphics::geometry::Renderer for Renderer { text, clip_bounds, } => { - layer.draw_primitive_group( - primitives, - clip_bounds, - transformation, - ); + layer.draw_primitive_group(primitives, clip_bounds, transformation); for image in images { layer.draw_image(image, transformation); @@ -353,21 +329,13 @@ impl graphics::geometry::Renderer for Renderer { layer.draw_text_group(text, clip_bounds, transformation); } Geometry::Cache(cache) => { - layer.draw_primitive_cache( - cache.primitives, - cache.clip_bounds, - transformation, - ); + layer.draw_primitive_cache(cache.primitives, cache.clip_bounds, transformation); for image in cache.images.iter() { layer.draw_image(image.clone(), transformation); } - layer.draw_text_cache( - cache.text, - cache.clip_bounds, - transformation, - ); + layer.draw_text_cache(cache.text, cache.clip_bounds, transformation); } } } @@ -394,19 +362,11 @@ impl core::image::Renderer for Renderer { self.engine.raster_pipeline.load(handle) } - fn measure_image( - &self, - handle: &Self::Handle, - ) -> Option> { + fn measure_image(&self, handle: &Self::Handle) -> Option> { self.engine.raster_pipeline.dimensions(handle) } - fn draw_image( - &mut self, - image: core::Image, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_image(&mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_raster(image, bounds, clip_bounds, transformation); } @@ -414,19 +374,11 @@ impl core::image::Renderer for Renderer { #[cfg(feature = "svg")] impl core::svg::Renderer for Renderer { - fn measure_svg( - &self, - handle: &core::svg::Handle, - ) -> crate::core::Size { + fn measure_svg(&self, handle: &core::svg::Handle) -> crate::core::Size { self.engine.vector_pipeline.viewport_dimensions(handle) } - fn draw_svg( - &mut self, - svg: core::Svg, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_svg(&mut self, svg: core::Svg, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_svg(svg, bounds, clip_bounds, transformation); } @@ -442,9 +394,7 @@ impl renderer::Headless for Renderer { default_text_size: Pixels, backend: Option<&str>, ) -> Option { - if backend.is_some_and(|backend| { - !["tiny-skia", "tiny_skia"].contains(&backend) - }) { + if backend.is_some_and(|backend| !["tiny-skia", "tiny_skia"].contains(&backend)) { return None; } diff --git a/tiny_skia/src/raster.rs b/tiny_skia/src/raster.rs index 7c8209175b..23964d1af7 100644 --- a/tiny_skia/src/raster.rs +++ b/tiny_skia/src/raster.rs @@ -18,17 +18,12 @@ impl Pipeline { } } - pub fn load( - &self, - handle: &raster::Handle, - ) -> Result { + pub fn load(&self, handle: &raster::Handle) -> Result { let mut cache = self.cache.borrow_mut(); let image = cache.allocate(handle)?; #[allow(unsafe_code)] - Ok(unsafe { - raster::allocate(handle, Size::new(image.width(), image.height())) - }) + Ok(unsafe { raster::allocate(handle, Size::new(image.width(), image.height())) }) } pub fn dimensions(&self, handle: &raster::Handle) -> Option> { @@ -133,15 +128,12 @@ impl Cache { return Err(raster::Error::Empty); } - let mut buffer = - vec![0u32; image.width() as usize * image.height() as usize]; + let mut buffer = vec![0u32; image.width() as usize * image.height() as usize]; for (i, pixel) in image.pixels().enumerate() { let [r, g, b, a] = pixel.0; - buffer[i] = bytemuck::cast( - tiny_skia::ColorU8::from_rgba(b, g, r, a).premultiply(), - ); + buffer[i] = bytemuck::cast(tiny_skia::ColorU8::from_rgba(b, g, r, a).premultiply()); } let _ = entry.insert(Some(Entry { @@ -223,8 +215,7 @@ fn border_radius( ((width as usize * y as usize) + x as usize) * 4 } - let clear_pixel = |img: &mut tiny_skia::PixmapMut<'_>, - (x, y): (u32, u32)| { + let clear_pixel = |img: &mut tiny_skia::PixmapMut<'_>, (x, y): (u32, u32)| { let pixel = pixel_id(img.width(), (x, y)); img.data_mut()[pixel..pixel + 4].copy_from_slice(&[0; 4]); }; diff --git a/tiny_skia/src/text.rs b/tiny_skia/src/text.rs index add4dee886..508d8da757 100644 --- a/tiny_skia/src/text.rs +++ b/tiny_skia/src/text.rs @@ -126,9 +126,7 @@ impl Pipeline { let height = entry.min_bounds.height; let x = match align_x { - Alignment::Default | Alignment::Left | Alignment::Justified => { - bounds.x - } + Alignment::Default | Alignment::Left | Alignment::Justified => bounds.x, Alignment::Center => bounds.x - width / 2.0, Alignment::Right => bounds.x - width, }; @@ -196,10 +194,8 @@ fn draw( for run in buffer.layout_runs() { for glyph in run.glyphs { - let physical_glyph = glyph.physical( - (position.x, position.y), - transformation.scale_factor(), - ); + let physical_glyph = + glyph.physical((position.x, position.y), transformation.scale_factor()); if let Some((buffer, placement)) = glyph_cache.allocate( physical_glyph.cache_key, @@ -207,24 +203,17 @@ fn draw( font_system, &mut swash, ) { - let pixmap = tiny_skia::PixmapRef::from_bytes( - buffer, - placement.width, - placement.height, - ) - .expect("Create glyph pixel map"); - - let opacity = color.a - * glyph - .color_opt - .map(|c| c.a() as f32 / 255.0) - .unwrap_or(1.0); + let pixmap = + tiny_skia::PixmapRef::from_bytes(buffer, placement.width, placement.height) + .expect("Create glyph pixel map"); + + let opacity = + color.a * glyph.color_opt.map(|c| c.a() as f32 / 255.0).unwrap_or(1.0); pixels.draw_pixmap( physical_glyph.x + placement.left, physical_glyph.y - placement.top - + (run.line_y * transformation.scale_factor()).round() - as i32, + + (run.line_y * transformation.scale_factor()).round() as i32, pixmap, &tiny_skia::PixmapPaint { opacity, @@ -246,10 +235,7 @@ fn from_color(color: cosmic_text::Color) -> Color { #[derive(Debug, Clone, Default)] struct GlyphCache { - entries: FxHashMap< - (cosmic_text::CacheKey, [u8; 3]), - (Vec, cosmic_text::Placement), - >, + entries: FxHashMap<(cosmic_text::CacheKey, [u8; 3]), (Vec, cosmic_text::Placement)>, recently_used: FxHashSet<(cosmic_text::CacheKey, [u8; 3])>, trim_count: usize, } @@ -276,8 +262,7 @@ impl GlyphCache { // TODO: Outline support let image = swash.get_image_uncached(font_system, cache_key)?; - let glyph_size = image.placement.width as usize - * image.placement.height as usize; + let glyph_size = image.placement.width as usize * image.placement.height as usize; if glyph_size == 0 { return None; @@ -294,13 +279,7 @@ impl GlyphCache { for _y in 0..image.placement.height { for _x in 0..image.placement.width { buffer[i] = bytemuck::cast( - tiny_skia::ColorU8::from_rgba( - b, - g, - r, - image.data[i], - ) - .premultiply(), + tiny_skia::ColorU8::from_rgba(b, g, r, image.data[i]).premultiply(), ); i += 1; @@ -337,14 +316,13 @@ impl GlyphCache { let _ = self.recently_used.insert(key); - self.entries.get(&key).map(|(buffer, placement)| { - (bytemuck::cast_slice(buffer.as_slice()), *placement) - }) + self.entries + .get(&key) + .map(|(buffer, placement)| (bytemuck::cast_slice(buffer.as_slice()), *placement)) } pub fn trim(&mut self) { - if self.trim_count > Self::TRIM_INTERVAL - || self.recently_used.len() >= Self::CAPACITY_LIMIT + if self.trim_count > Self::TRIM_INTERVAL || self.recently_used.len() >= Self::CAPACITY_LIMIT { self.entries .retain(|key, _| self.recently_used.contains(key)); diff --git a/tiny_skia/src/vector.rs b/tiny_skia/src/vector.rs index 59cd199307..9b18be83ad 100644 --- a/tiny_skia/src/vector.rs +++ b/tiny_skia/src/vector.rs @@ -106,14 +106,10 @@ impl Cache { if let hash_map::Entry::Vacant(entry) = self.trees.entry(id) { let svg = match handle.data() { - Data::Path(path) => { - fs::read_to_string(path).ok().and_then(|contents| { - usvg::Tree::from_str(&contents, &options).ok() - }) - } - Data::Bytes(bytes) => { - usvg::Tree::from_data(bytes, &options).ok() - } + Data::Path(path) => fs::read_to_string(path) + .ok() + .and_then(|contents| usvg::Tree::from_str(&contents, &options).ok()), + Data::Bytes(bytes) => usvg::Tree::from_data(bytes, &options).ok(), }; let _ = entry.insert(svg); @@ -174,39 +170,25 @@ impl Cache { // SVG rendering can panic on malformed or complex vectors. // We catch panics to prevent crashes and continue gracefully. - let render_result = - panic::catch_unwind(panic::AssertUnwindSafe(|| { - resvg::render(tree, transform, &mut image.as_mut()); - })); + let render_result = panic::catch_unwind(panic::AssertUnwindSafe(|| { + resvg::render(tree, transform, &mut image.as_mut()); + })); if render_result.is_err() { - log::warn!( - "SVG rendering panicked for handle ID: {}", - handle.id() - ); + log::warn!("SVG rendering panicked for handle ID: {}", handle.id()); return None; } if let Some([r, g, b, _]) = key.color { // Apply color filter - for pixel in - bytemuck::cast_slice_mut::(image.data_mut()) - { + for pixel in bytemuck::cast_slice_mut::(image.data_mut()) { *pixel = bytemuck::cast( - tiny_skia::ColorU8::from_rgba( - b, - g, - r, - (*pixel >> 24) as u8, - ) - .premultiply(), + tiny_skia::ColorU8::from_rgba(b, g, r, (*pixel >> 24) as u8).premultiply(), ); } } else { // Swap R and B channels for `softbuffer` presentation - for pixel in - bytemuck::cast_slice_mut::(image.data_mut()) - { + for pixel in bytemuck::cast_slice_mut::(image.data_mut()) { *pixel = *pixel & 0xFF00_FF00 | ((0x0000_00FF & *pixel) << 16) | ((0x00FF_0000 & *pixel) >> 16); diff --git a/tiny_skia/src/window/compositor.rs b/tiny_skia/src/window/compositor.rs index b841c24201..d0c84c5510 100644 --- a/tiny_skia/src/window/compositor.rs +++ b/tiny_skia/src/window/compositor.rs @@ -14,10 +14,7 @@ pub struct Compositor { } pub struct Surface { - window: softbuffer::Surface< - Box, - Box, - >, + window: softbuffer::Surface, Box>, clip_mask: tiny_skia::Mask, layer_stack: VecDeque>, background_color: Color, @@ -36,9 +33,7 @@ impl crate::graphics::Compositor for Compositor { backend: Option<&str>, ) -> Result { match backend { - None | Some("tiny-skia") | Some("tiny_skia") => { - Ok(new(settings.into(), display)) - } + None | Some("tiny-skia") | Some("tiny_skia") => Ok(new(settings.into(), display)), Some(backend) => Err(Error::GraphicsAdapterNotFound { backend: "tiny-skia", reason: error::Reason::DidNotMatch { @@ -49,10 +44,7 @@ impl crate::graphics::Compositor for Compositor { } fn create_renderer(&self) -> Self::Renderer { - Renderer::new( - self.settings.default_font, - self.settings.default_text_size, - ) + Renderer::new(self.settings.default_font, self.settings.default_text_size) } fn create_surface( @@ -61,11 +53,8 @@ impl crate::graphics::Compositor for Compositor { width: u32, height: u32, ) -> Self::Surface { - let window = softbuffer::Surface::new( - &self.context, - Box::new(window.clone()) as _, - ) - .expect("Create softbuffer surface for window"); + let window = softbuffer::Surface::new(&self.context, Box::new(window.clone()) as _) + .expect("Create softbuffer surface for window"); let mut surface = Surface { window, @@ -82,12 +71,7 @@ impl crate::graphics::Compositor for Compositor { surface } - fn configure_surface( - &mut self, - surface: &mut Self::Surface, - width: u32, - height: u32, - ) { + fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { surface .window .resize( @@ -96,8 +80,7 @@ impl crate::graphics::Compositor for Compositor { ) .expect("Resize surface"); - surface.clip_mask = - tiny_skia::Mask::new(width, height).expect("Create clip mask"); + surface.clip_mask = tiny_skia::Mask::new(width, height).expect("Create clip mask"); surface.layer_stack.clear(); } @@ -135,13 +118,10 @@ impl crate::graphics::Compositor for Compositor { } } -pub fn new( - settings: Settings, - display: impl compositor::Display, -) -> Compositor { +pub fn new(settings: Settings, display: impl compositor::Display) -> Compositor { #[allow(unsafe_code)] - let context = softbuffer::Context::new(Box::new(display) as _) - .expect("Create softbuffer context"); + let context = + softbuffer::Context::new(Box::new(display) as _).expect("Create softbuffer context"); Compositor { context, settings } } @@ -194,10 +174,7 @@ pub fn present( surface.layer_stack.push_front(renderer.layers().to_vec()); surface.background_color = background_color; - let damage = damage::group( - damage, - Rectangle::with_size(viewport.logical_size()), - ); + let damage = damage::group(damage, Rectangle::with_size(viewport.logical_size())); let mut pixels = tiny_skia::PixmapMut::from_bytes( bytemuck::cast_slice_mut(&mut buffer), @@ -226,11 +203,9 @@ pub fn screenshot( ) -> Vec { let size = viewport.physical_size(); - let mut offscreen_buffer: Vec = - vec![0; size.width as usize * size.height as usize]; + let mut offscreen_buffer: Vec = vec![0; size.width as usize * size.height as usize]; - let mut clip_mask = tiny_skia::Mask::new(size.width, size.height) - .expect("Create clip mask"); + let mut clip_mask = tiny_skia::Mask::new(size.width, size.height).expect("Create clip mask"); renderer.draw( &mut tiny_skia::PixmapMut::from_bytes( diff --git a/wgpu/src/buffer.rs b/wgpu/src/buffer.rs index e251e97915..27ddbd88e4 100644 --- a/wgpu/src/buffer.rs +++ b/wgpu/src/buffer.rs @@ -4,8 +4,8 @@ use std::ops::RangeBounds; pub const MAX_WRITE_SIZE: usize = 100 * 1024; -const MAX_WRITE_SIZE_U64: NonZeroU64 = NonZeroU64::new(MAX_WRITE_SIZE as u64) - .expect("MAX_WRITE_SIZE must be non-zero"); +const MAX_WRITE_SIZE_U64: NonZeroU64 = + NonZeroU64::new(MAX_WRITE_SIZE as u64).expect("MAX_WRITE_SIZE must be non-zero"); #[derive(Debug)] pub struct Buffer { @@ -79,9 +79,7 @@ impl Buffer { (offset + bytes_written) as u64, MAX_WRITE_SIZE_U64, ) - .copy_from_slice( - &bytes[bytes_written..bytes_written + MAX_WRITE_SIZE], - ); + .copy_from_slice(&bytes[bytes_written..bytes_written + MAX_WRITE_SIZE]); bytes_written += MAX_WRITE_SIZE; } @@ -104,10 +102,7 @@ impl Buffer { bytes.len() } - pub fn slice( - &self, - bounds: impl RangeBounds, - ) -> wgpu::BufferSlice<'_> { + pub fn slice(&self, bounds: impl RangeBounds) -> wgpu::BufferSlice<'_> { self.raw.slice(bounds) } @@ -122,8 +117,6 @@ impl Buffer { fn next_copy_size(amount: usize) -> u64 { let align_mask = wgpu::COPY_BUFFER_ALIGNMENT - 1; - (((std::mem::size_of::() * amount).next_power_of_two() as u64 - + align_mask) - & !align_mask) + (((std::mem::size_of::() * amount).next_power_of_two() as u64 + align_mask) & !align_mask) .max(wgpu::COPY_BUFFER_ALIGNMENT) } diff --git a/wgpu/src/color.rs b/wgpu/src/color.rs index 642d4ea72b..7d50320a1d 100644 --- a/wgpu/src/color.rs +++ b/wgpu/src/color.rs @@ -37,121 +37,108 @@ pub fn convert( usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, }); - let constant_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu.offscreen.blit.sampler_layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler( - wgpu::SamplerBindingType::NonFiltering, - ), - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - let constant_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu.offscreen.sampler.bind_group"), - layout: &constant_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Sampler(&sampler), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: ratio.as_entire_binding(), - }, - ], - }); - - let texture_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu.offscreen.blit.texture_layout"), - entries: &[wgpu::BindGroupLayoutEntry { + let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu.offscreen.blit.sampler_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: false, - }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, }, count: None, - }], - }); + }, + ], + }); - let pipeline_layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu.offscreen.blit.pipeline_layout"), - bind_group_layouts: &[&constant_layout, &texture_layout], - immediate_size: 0, - }); + let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu.offscreen.sampler.bind_group"), + layout: &constant_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: ratio.as_entire_binding(), + }, + ], + }); + + let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu.offscreen.blit.texture_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu.offscreen.blit.pipeline_layout"), + bind_group_layouts: &[&constant_layout, &texture_layout], + immediate_size: 0, + }); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("iced_wgpu.offscreen.blit.shader"), - source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!( - "shader/blit.wgsl" - ))), + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader/blit.wgsl"))), }); - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu.offscreen.blit.pipeline"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: &[], - compilation_options: wgpu::PipelineCompilationOptions::default( - ), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState { - color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - alpha: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::One, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - }), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: wgpu::PipelineCompilationOptions::default( - ), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..wgpu::PrimitiveState::default() - }, - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu.offscreen.blit.pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..wgpu::PrimitiveState::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("iced_wgpu.offscreen.conversion.source_texture"), @@ -160,25 +147,22 @@ pub fn convert( sample_count: 1, dimension: wgpu::TextureDimension::D2, format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::COPY_SRC, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let view = &texture.create_view(&wgpu::TextureViewDescriptor::default()); - let texture_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu.offscreen.blit.texture_bind_group"), - layout: &texture_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView( - &source - .create_view(&wgpu::TextureViewDescriptor::default()), - ), - }], - }); + let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu.offscreen.blit.texture_bind_group"), + layout: &texture_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView( + &source.create_view(&wgpu::TextureViewDescriptor::default()), + ), + }], + }); let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu.offscreen.blit.render_pass"), diff --git a/wgpu/src/engine.rs b/wgpu/src/engine.rs index d86499eb6a..0334a8655c 100644 --- a/wgpu/src/engine.rs +++ b/wgpu/src/engine.rs @@ -35,11 +35,7 @@ impl Engine { quad_pipeline: quad::Pipeline::new(&device, format), text_pipeline: text::Pipeline::new(&device, &queue, format), - triangle_pipeline: triangle::Pipeline::new( - &device, - format, - antialiasing, - ), + triangle_pipeline: triangle::Pipeline::new(&device, format, antialiasing), #[cfg(any(feature = "image", feature = "svg"))] image_pipeline: { @@ -48,9 +44,7 @@ impl Engine { crate::image::Pipeline::new(&device, format, backend) }, - primitive_storage: Arc::new(RwLock::new( - primitive::Storage::default(), - )), + primitive_storage: Arc::new(RwLock::new(primitive::Storage::default())), device, queue, @@ -60,11 +54,8 @@ impl Engine { #[cfg(any(feature = "image", feature = "svg"))] pub fn create_image_cache(&self) -> crate::image::Cache { - self.image_pipeline.create_cache( - &self.device, - &self.queue, - &self._shell, - ) + self.image_pipeline + .create_cache(&self.device, &self.queue, &self._shell) } pub fn trim(&mut self) { diff --git a/wgpu/src/geometry.rs b/wgpu/src/geometry.rs index c1433c4541..0e6517a180 100644 --- a/wgpu/src/geometry.rs +++ b/wgpu/src/geometry.rs @@ -1,14 +1,10 @@ //! Build and draw geometry. use crate::core::text::LineHeight; -use crate::core::{ - self, Pixels, Point, Radians, Rectangle, Size, Svg, Transformation, Vector, -}; +use crate::core::{self, Pixels, Point, Radians, Rectangle, Size, Svg, Transformation, Vector}; use crate::graphics::cache::{self, Cached}; use crate::graphics::color; use crate::graphics::geometry::fill::{self, Fill}; -use crate::graphics::geometry::{ - self, LineCap, LineDash, LineJoin, Path, Stroke, Style, -}; +use crate::graphics::geometry::{self, LineCap, LineDash, LineJoin, Path, Stroke, Style}; use crate::graphics::gradient::{self, Gradient}; use crate::graphics::mesh::{self, Mesh}; use crate::graphics::{Image, Text}; @@ -44,11 +40,7 @@ impl Cached for Geometry { Geometry::Cached(cache.clone()) } - fn cache( - self, - group: cache::Group, - previous: Option, - ) -> Self::Cache { + fn cache(self, group: cache::Group, previous: Option) -> Self::Cache { match self { Self::Live { meshes, @@ -161,33 +153,21 @@ impl geometry::frame::Backend for Frame { .buffers .get_fill(&self.transforms.current.transform_style(style)); - let options = tessellation::FillOptions::default() - .with_fill_rule(into_fill_rule(rule)); + let options = tessellation::FillOptions::default().with_fill_rule(into_fill_rule(rule)); if self.transforms.current.is_identity() { - self.fill_tessellator.tessellate_path( - path.raw(), - &options, - buffer.as_mut(), - ) + self.fill_tessellator + .tessellate_path(path.raw(), &options, buffer.as_mut()) } else { let path = path.transform(&self.transforms.current.0); - self.fill_tessellator.tessellate_path( - path.raw(), - &options, - buffer.as_mut(), - ) + self.fill_tessellator + .tessellate_path(path.raw(), &options, buffer.as_mut()) } .expect("Tessellate path."); } - fn fill_rectangle( - &mut self, - top_left: Point, - size: Size, - fill: impl Into, - ) { + fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into) { let Fill { style, rule } = fill.into(); let mut buffer = self @@ -200,13 +180,13 @@ impl geometry::frame::Backend for Frame { .0 .transform_point(lyon::math::Point::new(top_left.x, top_left.y)); - let size = - self.transforms.current.0.transform_vector( - lyon::math::Vector::new(size.width, size.height), - ); + let size = self + .transforms + .current + .0 + .transform_vector(lyon::math::Vector::new(size.width, size.height)); - let options = tessellation::FillOptions::default() - .with_fill_rule(into_fill_rule(rule)); + let options = tessellation::FillOptions::default().with_fill_rule(into_fill_rule(rule)); self.fill_tessellator .tessellate_rectangle( @@ -237,29 +217,18 @@ impl geometry::frame::Backend for Frame { }; if self.transforms.current.is_identity() { - self.stroke_tessellator.tessellate_path( - path.raw(), - &options, - buffer.as_mut(), - ) + self.stroke_tessellator + .tessellate_path(path.raw(), &options, buffer.as_mut()) } else { let path = path.transform(&self.transforms.current.0); - self.stroke_tessellator.tessellate_path( - path.raw(), - &options, - buffer.as_mut(), - ) + self.stroke_tessellator + .tessellate_path(path.raw(), &options, buffer.as_mut()) } .expect("Stroke path"); } - fn stroke_rectangle<'a>( - &mut self, - top_left: Point, - size: Size, - stroke: impl Into>, - ) { + fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into>) { let stroke = stroke.into(); let mut buffer = self @@ -272,10 +241,11 @@ impl geometry::frame::Backend for Frame { .0 .transform_point(lyon::math::Point::new(top_left.x, top_left.y)); - let size = - self.transforms.current.0.transform_vector( - lyon::math::Vector::new(size.width, size.height), - ); + let size = self + .transforms + .current + .0 + .transform_vector(lyon::math::Vector::new(size.width, size.height)); let mut options = tessellation::StrokeOptions::default(); options.line_width = stroke.width; @@ -292,11 +262,7 @@ impl geometry::frame::Backend for Frame { .expect("Stroke rectangle"); } - fn stroke_text<'a>( - &mut self, - text: impl Into, - stroke: impl Into>, - ) { + fn stroke_text<'a>(&mut self, text: impl Into, stroke: impl Into>) { let text = text.into(); let stroke = stroke.into(); @@ -313,41 +279,29 @@ impl geometry::frame::Backend for Frame { && scale_x > 0.0 && scale_y > 0.0 { - let (bounds, size, line_height) = - if self.transforms.current.is_identity() { - ( - Rectangle::new( - text.position, - Size::new(text.max_width, f32::INFINITY), - ), - text.size, - text.line_height, - ) - } else { - let position = - self.transforms.current.transform_point(text.position); - - let size = Pixels(text.size.0 * scale_y); - - let line_height = match text.line_height { - LineHeight::Absolute(size) => { - LineHeight::Absolute(Pixels(size.0 * scale_y)) - } - LineHeight::Relative(factor) => { - LineHeight::Relative(factor) - } - }; - - ( - Rectangle::new( - position, - Size::new(text.max_width, f32::INFINITY), - ), - size, - line_height, - ) + let (bounds, size, line_height) = if self.transforms.current.is_identity() { + ( + Rectangle::new(text.position, Size::new(text.max_width, f32::INFINITY)), + text.size, + text.line_height, + ) + } else { + let position = self.transforms.current.transform_point(text.position); + + let size = Pixels(text.size.0 * scale_y); + + let line_height = match text.line_height { + LineHeight::Absolute(size) => LineHeight::Absolute(Pixels(size.0 * scale_y)), + LineHeight::Relative(factor) => LineHeight::Relative(factor), }; + ( + Rectangle::new(position, Size::new(text.max_width, f32::INFINITY)), + size, + line_height, + ) + }; + self.text.push(Text::Cached { content: text.content, bounds, @@ -367,14 +321,11 @@ impl geometry::frame::Backend for Frame { #[inline] fn translate(&mut self, translation: Vector) { - self.transforms.current.0 = - self.transforms - .current - .0 - .pre_translate(lyon::math::Vector::new( - translation.x, - translation.y, - )); + self.transforms.current.0 = self + .transforms + .current + .0 + .pre_translate(lyon::math::Vector::new(translation.x, translation.y)); } #[inline] @@ -397,8 +348,7 @@ impl geometry::frame::Backend for Frame { fn scale_nonuniform(&mut self, scale: impl Into) { let scale = scale.into(); - self.transforms.current.0 = - self.transforms.current.0.pre_scale(scale.x, scale.y); + self.transforms.current.0 = self.transforms.current.0.pre_scale(scale.x, scale.y); } fn push_transform(&mut self) { @@ -436,12 +386,10 @@ impl geometry::frame::Backend for Frame { fn draw_image(&mut self, bounds: Rectangle, image: impl Into) { let mut image = image.into(); - let (bounds, external_rotation) = - self.transforms.current.transform_rectangle(bounds); + let (bounds, external_rotation) = self.transforms.current.transform_rectangle(bounds); image.rotation += external_rotation; - image.border_radius = - image.border_radius * self.transforms.current.scale().0; + image.border_radius = image.border_radius * self.transforms.current.scale().0; self.images.push(Image::Raster { image, @@ -453,8 +401,7 @@ impl geometry::frame::Backend for Frame { fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into) { let mut svg = svg.into(); - let (bounds, external_rotation) = - self.transforms.current.transform_rectangle(bounds); + let (bounds, external_rotation) = self.transforms.current.transform_rectangle(bounds); svg.rotation += external_rotation; @@ -485,17 +432,15 @@ impl BufferStack { Style::Solid(_) => match self.stack.last() { Some(Buffer::Solid(_)) => {} _ => { - self.stack.push(Buffer::Solid( - tessellation::VertexBuffers::new(), - )); + self.stack + .push(Buffer::Solid(tessellation::VertexBuffers::new())); } }, Style::Gradient(_) => match self.stack.last() { Some(Buffer::Gradient(_)) => {} _ => { - self.stack.push(Buffer::Gradient( - tessellation::VertexBuffers::new(), - )); + self.stack + .push(Buffer::Gradient(tessellation::VertexBuffers::new())); } }, } @@ -553,26 +498,22 @@ impl BufferStack { self.stack .into_iter() .filter_map(move |buffer| match buffer { - Buffer::Solid(buffer) if !buffer.indices.is_empty() => { - Some(Mesh::Solid { - buffers: mesh::Indexed { - vertices: buffer.vertices, - indices: buffer.indices, - }, - clip_bounds, - transformation: Transformation::IDENTITY, - }) - } - Buffer::Gradient(buffer) if !buffer.indices.is_empty() => { - Some(Mesh::Gradient { - buffers: mesh::Indexed { - vertices: buffer.vertices, - indices: buffer.indices, - }, - clip_bounds, - transformation: Transformation::IDENTITY, - }) - } + Buffer::Solid(buffer) if !buffer.indices.is_empty() => Some(Mesh::Solid { + buffers: mesh::Indexed { + vertices: buffer.vertices, + indices: buffer.indices, + }, + clip_bounds, + transformation: Transformation::IDENTITY, + }), + Buffer::Gradient(buffer) if !buffer.indices.is_empty() => Some(Mesh::Gradient { + buffers: mesh::Indexed { + vertices: buffer.vertices, + indices: buffer.indices, + }, + clip_bounds, + transformation: Transformation::IDENTITY, + }), _ => None, }) } @@ -593,8 +534,7 @@ impl Transform { } fn is_scale_translation(&self) -> bool { - self.0.m12.abs() < 2.0 * f32::EPSILON - && self.0.m21.abs() < 2.0 * f32::EPSILON + self.0.m12.abs() < 2.0 * f32::EPSILON && self.0.m21.abs() < 2.0 * f32::EPSILON } fn scale(&self) -> (f32, f32) { @@ -615,9 +555,7 @@ impl Transform { fn transform_style(&self, style: Style) -> Style { match style { Style::Solid(color) => Style::Solid(color), - Style::Gradient(gradient) => { - Style::Gradient(self.transform_gradient(gradient)) - } + Style::Gradient(gradient) => Style::Gradient(self.transform_gradient(gradient)), } } @@ -632,17 +570,12 @@ impl Transform { gradient } - fn transform_rectangle( - &self, - rectangle: Rectangle, - ) -> (Rectangle, Radians) { + fn transform_rectangle(&self, rectangle: Rectangle) -> (Rectangle, Radians) { let top_left = self.transform_point(rectangle.position()); - let top_right = self.transform_point( - rectangle.position() + Vector::new(rectangle.width, 0.0), - ); - let bottom_left = self.transform_point( - rectangle.position() + Vector::new(0.0, rectangle.height), - ); + let top_right = + self.transform_point(rectangle.position() + Vector::new(rectangle.width, 0.0)); + let bottom_left = + self.transform_point(rectangle.position() + Vector::new(0.0, rectangle.height)); Rectangle::with_vertices(top_left, top_right, bottom_left) } @@ -651,13 +584,8 @@ struct GradientVertex2DBuilder { gradient: gradient::Packed, } -impl tessellation::FillVertexConstructor - for GradientVertex2DBuilder -{ - fn new_vertex( - &mut self, - vertex: tessellation::FillVertex<'_>, - ) -> mesh::GradientVertex2D { +impl tessellation::FillVertexConstructor for GradientVertex2DBuilder { + fn new_vertex(&mut self, vertex: tessellation::FillVertex<'_>) -> mesh::GradientVertex2D { let position = vertex.position(); mesh::GradientVertex2D { @@ -667,13 +595,8 @@ impl tessellation::FillVertexConstructor } } -impl tessellation::StrokeVertexConstructor - for GradientVertex2DBuilder -{ - fn new_vertex( - &mut self, - vertex: tessellation::StrokeVertex<'_, '_>, - ) -> mesh::GradientVertex2D { +impl tessellation::StrokeVertexConstructor for GradientVertex2DBuilder { + fn new_vertex(&mut self, vertex: tessellation::StrokeVertex<'_, '_>) -> mesh::GradientVertex2D { let position = vertex.position(); mesh::GradientVertex2D { @@ -685,13 +608,8 @@ impl tessellation::StrokeVertexConstructor struct TriangleVertex2DBuilder(color::Packed); -impl tessellation::FillVertexConstructor - for TriangleVertex2DBuilder -{ - fn new_vertex( - &mut self, - vertex: tessellation::FillVertex<'_>, - ) -> mesh::SolidVertex2D { +impl tessellation::FillVertexConstructor for TriangleVertex2DBuilder { + fn new_vertex(&mut self, vertex: tessellation::FillVertex<'_>) -> mesh::SolidVertex2D { let position = vertex.position(); mesh::SolidVertex2D { @@ -701,13 +619,8 @@ impl tessellation::FillVertexConstructor } } -impl tessellation::StrokeVertexConstructor - for TriangleVertex2DBuilder -{ - fn new_vertex( - &mut self, - vertex: tessellation::StrokeVertex<'_, '_>, - ) -> mesh::SolidVertex2D { +impl tessellation::StrokeVertexConstructor for TriangleVertex2DBuilder { + fn new_vertex(&mut self, vertex: tessellation::StrokeVertex<'_, '_>) -> mesh::SolidVertex2D { let position = vertex.position(); mesh::SolidVertex2D { @@ -741,9 +654,7 @@ fn into_fill_rule(rule: fill::Rule) -> lyon::tessellation::FillRule { } pub(super) fn dashed(path: &Path, line_dash: LineDash<'_>) -> Path { - use lyon::algorithms::walk::{ - RepeatedPattern, WalkerEvent, walk_along_path, - }; + use lyon::algorithms::walk::{RepeatedPattern, WalkerEvent, walk_along_path}; use lyon::path::iterator::PathIterator; Path::new(|builder| { @@ -753,9 +664,9 @@ pub(super) fn dashed(path: &Path, line_dash: LineDash<'_>) -> Path { let mut draw_line = false; walk_along_path( - path.raw().iter().flattened( - lyon::tessellation::StrokeOptions::DEFAULT_TOLERANCE, - ), + path.raw() + .iter() + .flattened(lyon::tessellation::StrokeOptions::DEFAULT_TOLERANCE), 0.0, lyon::tessellation::StrokeOptions::DEFAULT_TOLERANCE, &mut RepeatedPattern { @@ -776,9 +687,7 @@ pub(super) fn dashed(path: &Path, line_dash: LineDash<'_>) -> Path { true }, index: line_dash.offset, - intervals: segments_odd - .as_deref() - .unwrap_or(line_dash.segments), + intervals: segments_odd.as_deref().unwrap_or(line_dash.segments), }, ); }) diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index d23e745203..494558ab19 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -82,15 +82,14 @@ impl Atlas { ..Default::default() }); - let texture_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::image texture atlas bind group"), - layout: &texture_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView(&texture_view), - }], - }); + let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::image texture atlas bind group"), + layout: &texture_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&texture_view), + }], + }); Atlas { size, @@ -131,9 +130,7 @@ impl Atlas { match &entry { Entry::Contiguous(allocation) => { - self.upload_allocation( - pixels, width, 0, allocation, encoder, belt, - ); + self.upload_allocation(pixels, width, 0, allocation, encoder, belt); } Entry::Fragmented { fragments, .. } => { for fragment in fragments { @@ -326,8 +323,7 @@ impl Atlas { let bytes_per_row = (4 * (width + padding.width * 2)) .next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) as usize; - let total_bytes = - bytes_per_row * (height + padding.height * 2) as usize; + let total_bytes = bytes_per_row * (height + padding.height * 2) as usize; let buffer_slice = belt.allocate( wgpu::BufferSize::new(total_bytes as u64).unwrap(), @@ -349,21 +345,14 @@ impl Atlas { // Using `h` instead of `h-1` over-estimates by one full image_width // row, causing false positives for bottom-right fragments whose // x-offset is non-zero and whose bottom edge reaches the image edge. - if h > 0 - && pixels.len() - < offset + (h - 1) * PIXEL * image_width as usize + stride - { + if h > 0 && pixels.len() < offset + (h - 1) * PIXEL * image_width as usize + stride { return; } // bounds check for pad_w low / high to fragment if pad_w > 0 && (offset + stride < PIXEL - || offset - + image_width as usize - * PIXEL - * (h.checked_sub(1).unwrap_or(0)) - + PIXEL + || offset + image_width as usize * PIXEL * (h.checked_sub(1).unwrap_or(0)) + PIXEL > pixels.len()) { return; @@ -382,11 +371,9 @@ impl Atlas { fragment[dst + PIXEL * i..dst + PIXEL * (i + 1)] .copy_from_slice(&pixels[src..src + PIXEL]); - fragment[dst + stride + PIXEL * (pad_w + i) - ..dst + stride + PIXEL * (pad_w + i + 1)] - .copy_from_slice( - &pixels[src + stride - PIXEL..src + stride], - ); + fragment + [dst + stride + PIXEL * (pad_w + i)..dst + stride + PIXEL * (pad_w + i + 1)] + .copy_from_slice(&pixels[src + stride - PIXEL..src + stride]); } } @@ -402,8 +389,7 @@ impl Atlas { .copy_from_slice(&pixels[src_top..src_top + PIXEL * w]); // Bottom - fragment - [dst_bottom + PIXEL * pad_w..dst_bottom + PIXEL * (pad_w + w)] + fragment[dst_bottom + PIXEL * pad_w..dst_bottom + PIXEL * (pad_w + w)] .copy_from_slice(&pixels[src_bottom..src_bottom + PIXEL * w]); // Corners @@ -413,11 +399,8 @@ impl Atlas { .copy_from_slice(&pixels[offset..offset + PIXEL]); // Top right - fragment[dst_top + PIXEL * (w + pad_w + i) - ..dst_top + PIXEL * (w + pad_w + i + 1)] - .copy_from_slice( - &pixels[offset + PIXEL * (w - 1)..offset + PIXEL * w], - ); + fragment[dst_top + PIXEL * (w + pad_w + i)..dst_top + PIXEL * (w + pad_w + i + 1)] + .copy_from_slice(&pixels[offset + PIXEL * (w - 1)..offset + PIXEL * w]); // Bottom left fragment[dst_bottom + PIXEL * i..dst_bottom + PIXEL * (i + 1)] @@ -426,10 +409,7 @@ impl Atlas { // Bottom right fragment[dst_bottom + PIXEL * (w + pad_w + i) ..dst_bottom + PIXEL * (w + pad_w + i + 1)] - .copy_from_slice( - &pixels[src_bottom + PIXEL * (w - 1) - ..src_bottom + PIXEL * w], - ); + .copy_from_slice(&pixels[src_bottom + PIXEL * (w - 1)..src_bottom + PIXEL * w]); } } @@ -507,9 +487,7 @@ impl Atlas { let amount_to_copy = self.layers.len() - amount; - for (i, layer) in - self.layers.iter_mut().take(amount_to_copy).enumerate() - { + for (i, layer) in self.layers.iter_mut().take(amount_to_copy).enumerate() { if layer.is_empty() { continue; } @@ -544,22 +522,18 @@ impl Atlas { } self.texture = new_texture; - self.texture_view = - self.texture.create_view(&wgpu::TextureViewDescriptor { - dimension: Some(wgpu::TextureViewDimension::D2Array), - ..Default::default() - }); + self.texture_view = self.texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); - self.texture_bind_group = - Arc::new(device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::image texture atlas bind group"), - layout: &self.texture_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView( - &self.texture_view, - ), - }], - })); + self.texture_bind_group = Arc::new(device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::image texture atlas bind group"), + layout: &self.texture_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&self.texture_view), + }], + })); } } diff --git a/wgpu/src/image/cache.rs b/wgpu/src/image/cache.rs index 88a486403b..a70b500f1a 100644 --- a/wgpu/src/image/cache.rs +++ b/wgpu/src/image/cache.rs @@ -29,8 +29,7 @@ impl Cache { _shell: &Shell, ) -> Self { #[cfg(all(feature = "image", not(target_arch = "wasm32")))] - let worker = - Worker::new(device, _queue, backend, layout.clone(), _shell); + let worker = Worker::new(device, _queue, backend, layout.clone(), _shell); Self { atlas: Atlas::new(device, backend, layout), @@ -38,10 +37,7 @@ impl Cache { raster: Raster { cache: crate::image::raster::Cache::default(), pending: HashMap::new(), - belt: wgpu::util::StagingBelt::new( - device.clone(), - 2 * 1024 * 1024, - ), + belt: wgpu::util::StagingBelt::new(device.clone(), 2 * 1024 * 1024), }, #[cfg(feature = "svg")] vector: crate::image::vector::Cache::default(), @@ -54,9 +50,7 @@ impl Cache { pub fn allocate_image( &mut self, handle: &core::image::Handle, - callback: impl FnOnce(Result) - + Send - + 'static, + callback: impl FnOnce(Result) + Send + 'static, ) { use crate::image::raster::Memory; @@ -108,11 +102,9 @@ impl Cache { match self.raster.cache.get_mut(handle).unwrap() { Memory::Host(image) => { - let mut encoder = device.create_command_encoder( - &wgpu::CommandEncoderDescriptor { - label: Some("raster image upload"), - }, - ); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("raster image upload"), + }); let entry = self.atlas.upload( device, @@ -138,10 +130,7 @@ impl Cache { #[allow(unsafe_code)] let allocation = unsafe { - core::image::allocate( - handle, - Size::new(image.width(), image.height()), - ) + core::image::allocate(handle, Size::new(image.width(), image.height())) }; self.raster.cache.insert( @@ -166,8 +155,7 @@ impl Cache { } #[allow(unsafe_code)] - let new = - unsafe { core::image::allocate(handle, entry.size()) }; + let new = unsafe { core::image::allocate(handle, entry.size()) }; *allocation = Some(new.downgrade()); @@ -178,10 +166,7 @@ impl Cache { } #[cfg(feature = "image")] - pub fn measure_image( - &mut self, - handle: &core::image::Handle, - ) -> Option> { + pub fn measure_image(&mut self, handle: &core::image::Handle) -> Option> { self.receive(); let image = load_image( @@ -239,14 +224,9 @@ impl Cache { // TODO: Concurrent Wasm support if image.len() < MAX_SYNC_SIZE || cfg!(target_arch = "wasm32") { - let entry = self.atlas.upload( - device, - encoder, - belt, - image.width(), - image.height(), - &image, - )?; + let entry = + self.atlas + .upload(device, encoder, belt, image.width(), image.height(), &image)?; *memory = Memory::Device { entry, @@ -325,9 +305,7 @@ impl Cache { let allocation = if let Some(callbacks) = callbacks { #[allow(unsafe_code)] - let allocation = unsafe { - core::image::allocate(&handle, entry.size()) - }; + let allocation = unsafe { core::image::allocate(&handle, entry.size()) }; let reference = allocation.downgrade(); @@ -380,8 +358,7 @@ struct Raster { } #[cfg(feature = "image")] -type Callback = - Box) + Send>; +type Callback = Box) + Send>; #[cfg(feature = "image")] fn load_image<'a>( @@ -454,10 +431,7 @@ mod worker { backend, texture_layout, shell: shell.clone(), - belt: wgpu::util::StagingBelt::new( - device.clone(), - 4 * 1024 * 1024, - ), + belt: wgpu::util::StagingBelt::new(device.clone(), 4 * 1024 * 1024), jobs: jobs_receiver, output: work_sender, quit: quit_receiver, @@ -550,35 +524,25 @@ mod worker { }; match job { - Job::Load(handle) => { - match crate::graphics::image::load(&handle) { - Ok(image) => self.upload( - handle, - image.width(), - image.height(), - image.into_raw(), - Shell::invalidate_layout, - ), - Err(error) => { - let _ = self - .output - .send(Work::Error { handle, error }); - } + Job::Load(handle) => match crate::graphics::image::load(&handle) { + Ok(image) => self.upload( + handle, + image.width(), + image.height(), + image.into_raw(), + Shell::invalidate_layout, + ), + Err(error) => { + let _ = self.output.send(Work::Error { handle, error }); } - } + }, Job::Upload { handle, rgba, width, height, } => { - self.upload( - handle, - width, - height, - rgba, - Shell::request_redraw, - ); + self.upload(handle, width, height, rgba, Shell::request_redraw); } Job::Drop(bind_group) => { drop(bind_group); @@ -596,11 +560,11 @@ mod worker { rgba: Bytes, callback: fn(&Shell), ) { - let mut encoder = self.device.create_command_encoder( - &wgpu::CommandEncoderDescriptor { + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("raster image upload"), - }, - ); + }); let mut atlas = Atlas::with_size( &self.device, diff --git a/wgpu/src/image/mod.rs b/wgpu/src/image/mod.rs index d0665ee423..fcaa7e2f5c 100644 --- a/wgpu/src/image/mod.rs +++ b/wgpu/src/image/mod.rs @@ -34,11 +34,7 @@ pub struct Pipeline { } impl Pipeline { - pub fn new( - device: &wgpu::Device, - format: wgpu::TextureFormat, - backend: wgpu::Backend, - ) -> Self { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, backend: wgpu::Backend) -> Self { let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, @@ -59,141 +55,126 @@ impl Pipeline { ..Default::default() }); - let constant_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::image constants layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new( - mem::size_of::() as u64, - ), - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler( - wgpu::SamplerBindingType::Filtering, - ), - count: None, - }, - ], - }); - - let texture_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::image texture atlas layout"), - entries: &[wgpu::BindGroupLayoutEntry { + let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::image constants layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: true, - }, - view_dimension: wgpu::TextureViewDimension::D2Array, - multisampled: false, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(mem::size_of::() as u64), }, count: None, - }], - }); - - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu::image pipeline layout"), - bind_group_layouts: &[&constant_layout, &texture_layout], - immediate_size: 0, - }); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu image shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - concat!( - include_str!("../shader/vertex.wgsl"), - "\n", - include_str!("../shader/image.wgsl"), - ), - )), - }); - - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu::image pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: &[wgpu::VertexBufferLayout { - array_stride: mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &wgpu::vertex_attr_array!( - // Center - 0 => Float32x2, - // Clip bounds - 1 => Float32x4, - // Border radius - 2 => Float32x4, - // Tile - 3 => Float32x4, - // Rotation - 4 => Float32, - // Opacity - 5 => Float32, - // Atlas position - 6 => Float32x2, - // Atlas scale - 7 => Float32x2, - // Layer - 8 => Sint32, - // Snap - 9 => Uint32, - ), - }], - compilation_options: - wgpu::PipelineCompilationOptions::default(), }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState { - color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - alpha: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::One, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - }), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..Default::default() + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, + ], + }); + + let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::image texture atlas layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, }, - multiview_mask: None, - cache: None, - }); + count: None, + }], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu::image pipeline layout"), + bind_group_layouts: &[&constant_layout, &texture_layout], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu image shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( + include_str!("../shader/vertex.wgsl"), + "\n", + include_str!("../shader/image.wgsl"), + ))), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu::image pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[wgpu::VertexBufferLayout { + array_stride: mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &wgpu::vertex_attr_array!( + // Center + 0 => Float32x2, + // Clip bounds + 1 => Float32x4, + // Border radius + 2 => Float32x4, + // Tile + 3 => Float32x4, + // Rotation + 4 => Float32, + // Opacity + 5 => Float32, + // Atlas position + 6 => Float32x2, + // Atlas scale + 7 => Float32x2, + // Layer + 8 => Sint32, + // Snap + 9 => Uint32, + ), + }], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview_mask: None, + cache: None, + }); Pipeline { raw: pipeline, @@ -205,12 +186,7 @@ impl Pipeline { } } - pub fn create_cache( - &self, - device: &wgpu::Device, - queue: &wgpu::Queue, - shell: &Shell, - ) -> Cache { + pub fn create_cache(&self, device: &wgpu::Device, queue: &wgpu::Queue, shell: &Shell) -> Cache { Cache::new( device, queue, @@ -266,19 +242,15 @@ impl State { bounds, clip_bounds, } => { - if let Some((atlas_entry, bind_group)) = cache - .upload_raster(device, encoder, belt, &image.handle) + if let Some((atlas_entry, bind_group)) = + cache.upload_raster(device, encoder, belt, &image.handle) { match atlas.as_mut() { None => { atlas = Some(bind_group.clone()); } Some(atlas) if atlas != bind_group => { - layer.push( - atlas, - &self.nearest_instances, - &self.linear_instances, - ); + layer.push(atlas, &self.nearest_instances, &self.linear_instances); *atlas = Arc::clone(bind_group); } @@ -313,27 +285,21 @@ impl State { bounds, clip_bounds, } => { - if let Some((atlas_entry, bind_group)) = cache - .upload_vector( - device, - encoder, - belt, - &svg.handle, - svg.color, - bounds.size(), - scale, - ) - { + if let Some((atlas_entry, bind_group)) = cache.upload_vector( + device, + encoder, + belt, + &svg.handle, + svg.color, + bounds.size(), + scale, + ) { match atlas.as_mut() { None => { atlas = Some(bind_group.clone()); } Some(atlas) if atlas != bind_group => { - layer.push( - atlas, - &self.nearest_instances, - &self.linear_instances, - ); + layer.push(atlas, &self.nearest_instances, &self.linear_instances); *atlas = bind_group.clone(); } @@ -386,12 +352,7 @@ impl State { if let Some(layer) = self.layers.get(layer) { render_pass.set_pipeline(&pipeline.raw); - render_pass.set_scissor_rect( - bounds.x, - bounds.y, - bounds.width, - bounds.height, - ); + render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); layer.render(render_pass); } @@ -445,53 +406,43 @@ impl Layer { wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, ); - let nearest_layout = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::image constants bind group"), - layout: constant_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer: &uniforms, - offset: 0, - size: None, - }, - ), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Sampler( - nearest_sampler, - ), - }, - ], - }); + let nearest_layout = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::image constants bind group"), + layout: constant_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniforms, + offset: 0, + size: None, + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(nearest_sampler), + }, + ], + }); - let linear_layout = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("iced_wgpu::image constants bind group"), - layout: constant_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer: &uniforms, - offset: 0, - size: None, - }, - ), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Sampler( - linear_sampler, - ), - }, - ], - }); + let linear_layout = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("iced_wgpu::image constants bind group"), + layout: constant_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniforms, + offset: 0, + size: None, + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(linear_sampler), + }, + ], + }); Self { uniforms, @@ -546,12 +497,7 @@ impl Layer { } } - fn push( - &mut self, - atlas: &Arc, - nearest: &[Instance], - linear: &[Instance], - ) { + fn push(&mut self, atlas: &Arc, nearest: &[Instance], linear: &[Instance]) { let new_nearest = nearest.len() - self.nearest_total; if new_nearest > 0 { @@ -585,8 +531,7 @@ impl Layer { for group in &self.nearest { render_pass.set_bind_group(1, group.atlas.as_ref(), &[]); - render_pass - .draw(0..6, offset..offset + group.instance_count as u32); + render_pass.draw(0..6, offset..offset + group.instance_count as u32); offset += group.instance_count as u32; } @@ -597,8 +542,7 @@ impl Layer { for group in &self.linear { render_pass.set_bind_group(1, group.atlas.as_ref(), &[]); - render_pass - .draw(0..6, offset..offset + group.instance_count as u32); + render_pass.draw(0..6, offset..offset + group.instance_count as u32); offset += group.instance_count as u32; } @@ -741,10 +685,7 @@ fn add_instance( _tile: tile, _rotation: rotation, _opacity: opacity, - _position_in_atlas: [ - x as f32 / atlas_size as f32, - y as f32 / atlas_size as f32, - ], + _position_in_atlas: [x as f32 / atlas_size as f32, y as f32 / atlas_size as f32], _size_in_atlas: [ width as f32 / atlas_size as f32, height as f32 / atlas_size as f32, diff --git a/wgpu/src/image/raster.rs b/wgpu/src/image/raster.rs index 881e75e3df..034eb83fbc 100644 --- a/wgpu/src/image/raster.rs +++ b/wgpu/src/image/raster.rs @@ -75,11 +75,7 @@ impl Cache { self.map.contains_key(&handle.id()) } - pub fn trim( - &mut self, - atlas: &mut Atlas, - on_drop: impl Fn(Arc), - ) { + pub fn trim(&mut self, atlas: &mut Atlas, on_drop: impl Fn(Arc)) { // Only trim if new entries have landed in the `Cache` if !self.should_trim { return; diff --git a/wgpu/src/image/vector.rs b/wgpu/src/image/vector.rs index 0704a966ed..f89a53ec5d 100644 --- a/wgpu/src/image/vector.rs +++ b/wgpu/src/image/vector.rs @@ -71,17 +71,13 @@ impl Cache { let svg = match handle.data() { svg::Data::Path(path) => fs::read_to_string(path) .ok() - .and_then(|contents| { - usvg::Tree::from_str(&contents, &options).ok() - }) + .and_then(|contents| usvg::Tree::from_str(&contents, &options).ok()) .map(Svg::Loaded) .unwrap_or(Svg::NotFound), - svg::Data::Bytes(bytes) => { - match usvg::Tree::from_data(bytes, &options) { - Ok(tree) => Svg::Loaded(tree), - Err(_) => Svg::NotFound, - } - } + svg::Data::Bytes(bytes) => match usvg::Tree::from_data(bytes, &options) { + Ok(tree) => Svg::Loaded(tree), + Err(_) => Svg::NotFound, + }, }; self.should_trim = true; @@ -157,15 +153,12 @@ impl Cache { // SVG rendering can panic on malformed or complex vectors. // We catch panics to prevent crashes and continue gracefully. - let render = - panic::catch_unwind(panic::AssertUnwindSafe(|| { - resvg::render(tree, transform, &mut img.as_mut()); - })); + let render = panic::catch_unwind(panic::AssertUnwindSafe(|| { + resvg::render(tree, transform, &mut img.as_mut()); + })); if let Err(error) = render { - log::warn!( - "SVG rendering for {handle:?} panicked: {error:?}" - ); + log::warn!("SVG rendering for {handle:?} panicked: {error:?}"); } let mut rgba = img.take(); @@ -180,8 +173,7 @@ impl Cache { }); } - let allocation = atlas - .upload(device, encoder, belt, width, height, &rgba)?; + let allocation = atlas.upload(device, encoder, belt, width, height, &rgba)?; log::debug!("allocating {id} {width}x{height}"); diff --git a/wgpu/src/layer.rs b/wgpu/src/layer.rs index d4a96ef815..d7a4f06d70 100644 --- a/wgpu/src/layer.rs +++ b/wgpu/src/layer.rs @@ -1,7 +1,5 @@ use crate::core::Radians; -use crate::core::{ - self, Background, Color, Point, Rectangle, Svg, Transformation, renderer, -}; +use crate::core::{self, Background, Color, Point, Rectangle, Svg, Transformation, renderer}; use crate::graphics; use crate::graphics::Mesh; use crate::graphics::color; @@ -51,14 +49,11 @@ impl Layer { position: [bounds.x, bounds.y], size: [bounds.width, bounds.height], border_color: color::pack(quad.border.color), - border_radius: (quad.border.radius * transformation.scale_factor()) - .into(), + border_radius: (quad.border.radius * transformation.scale_factor()).into(), border_width: quad.border.width * transformation.scale_factor(), shadow_color: color::pack(quad.shadow.color), - shadow_offset: (quad.shadow.offset * transformation.scale_factor()) - .into(), - shadow_blur_radius: quad.shadow.blur_radius - * transformation.scale_factor(), + shadow_offset: (quad.shadow.offset * transformation.scale_factor()).into(), + shadow_blur_radius: quad.shadow.blur_radius * transformation.scale_factor(), snap: quad.snap as u32, }; @@ -116,8 +111,7 @@ impl Layer { bounds: Rectangle::new(position, text.bounds) * transformation, color, size: text.size * transformation.scale_factor(), - line_height: text.line_height.to_absolute(text.size) - * transformation.scale_factor(), + line_height: text.line_height.to_absolute(text.size) * transformation.scale_factor(), font: text.font, align_x: text.align_x, align_y: text.align_y, @@ -128,11 +122,7 @@ impl Layer { self.pending_text.push(text); } - pub fn draw_text_raw( - &mut self, - raw: graphics::text::Raw, - transformation: Transformation, - ) { + pub fn draw_text_raw(&mut self, raw: graphics::text::Raw, transformation: Transformation) { let raw = Text::Raw { raw, transformation, @@ -169,8 +159,7 @@ impl Layer { ) { let image = Image::Raster { image: core::Image { - border_radius: image.border_radius - * transformation.scale_factor(), + border_radius: image.border_radius * transformation.scale_factor(), ..image }, bounds: bounds * transformation, @@ -196,11 +185,7 @@ impl Layer { self.images.push(svg); } - pub fn draw_mesh( - &mut self, - mut mesh: Mesh, - transformation: Transformation, - ) { + pub fn draw_mesh(&mut self, mut mesh: Mesh, transformation: Transformation) { match &mut mesh { Mesh::Solid { transformation: local_transformation, @@ -217,11 +202,7 @@ impl Layer { self.pending_meshes.push(mesh); } - pub fn draw_mesh_group( - &mut self, - meshes: Vec, - transformation: Transformation, - ) { + pub fn draw_mesh_group(&mut self, meshes: Vec, transformation: Transformation) { self.flush_meshes(); self.triangles.push(triangle::Item::Group { @@ -230,11 +211,7 @@ impl Layer { }); } - pub fn draw_mesh_cache( - &mut self, - cache: mesh::Cache, - transformation: Transformation, - ) { + pub fn draw_mesh_cache(&mut self, cache: mesh::Cache, transformation: Transformation) { self.flush_meshes(); self.triangles.push(triangle::Item::Cached { @@ -243,11 +220,7 @@ impl Layer { }); } - pub fn draw_text_group( - &mut self, - text: Vec, - transformation: Transformation, - ) { + pub fn draw_text_group(&mut self, text: Vec, transformation: Transformation) { self.flush_text(); self.text.push(text::Item::Group { @@ -256,11 +229,7 @@ impl Layer { }); } - pub fn draw_text_cache( - &mut self, - cache: text::Cache, - transformation: Transformation, - ) { + pub fn draw_text_cache(&mut self, cache: text::Cache, transformation: Transformation) { self.flush_text(); self.text.push(text::Item::Cached { diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 03a72042d3..3f3457a2c1 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -64,8 +64,8 @@ pub use geometry::Geometry; use crate::core::renderer; use crate::core::{ - Background, Color, Font, Pixels, Point, Radians, Rectangle, Size, - Transformation, Vector, image::FilterMethod, + Background, Color, Font, Pixels, Point, Radians, Rectangle, Size, Transformation, Vector, + image::FilterMethod, }; use crate::graphics::mesh; use crate::graphics::text::{Editor, Paragraph}; @@ -98,21 +98,14 @@ pub struct Renderer { } impl Renderer { - pub fn new( - engine: Engine, - default_font: Font, - default_text_size: Pixels, - ) -> Self { + pub fn new(engine: Engine, default_font: Font, default_text_size: Pixels) -> Self { Self { default_font, default_text_size, layers: layer::Stack::new(), quad: quad::State::new(), - triangle: triangle::State::new( - &engine.device, - &engine.triangle_pipeline, - ), + triangle: triangle::State::new(&engine.device, &engine.triangle_pipeline), text: text::State::new(), text_viewport: engine.text_pipeline.create_viewport(&engine.device), @@ -140,11 +133,12 @@ impl Renderer { target: &wgpu::TextureView, viewport: &Viewport, ) -> wgpu::CommandEncoder { - let mut encoder = self.engine.device.create_command_encoder( - &wgpu::CommandEncoderDescriptor { - label: Some("iced_wgpu encoder"), - }, - ); + let mut encoder = + self.engine + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("iced_wgpu encoder"), + }); self.prepare(&mut encoder, viewport); self.render(&mut encoder, target, clear_color, viewport); @@ -183,11 +177,7 @@ impl Renderer { /// Renders the current surface to an offscreen buffer. /// /// Returns RGBA bytes of the texture data. - pub fn screenshot( - &mut self, - viewport: &Viewport, - background_color: Color, - ) -> Vec { + pub fn screenshot(&mut self, viewport: &Viewport, background_color: Color) -> Vec { #[derive(Clone, Copy, Debug)] struct BufferDimensions { width: u32, @@ -200,11 +190,9 @@ impl Renderer { fn new(size: Size) -> Self { let unpadded_bytes_per_row = size.width as usize * 4; //slice of buffer per row; always RGBA let alignment = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; //256 - let padded_bytes_per_row_padding = (alignment - - unpadded_bytes_per_row % alignment) - % alignment; - let padded_bytes_per_row = - unpadded_bytes_per_row + padded_bytes_per_row_padding; + let padded_bytes_per_row_padding = + (alignment - unpadded_bytes_per_row % alignment) % alignment; + let padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding; Self { width: size.width, @@ -223,19 +211,18 @@ impl Renderer { depth_or_array_layers: 1, }; - let texture = - self.engine.device.create_texture(&wgpu::TextureDescriptor { - label: Some("iced_wgpu.offscreen.source_texture"), - size: texture_extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: self.engine.format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::COPY_SRC - | wgpu::TextureUsages::TEXTURE_BINDING, - view_formats: &[], - }); + let texture = self.engine.device.create_texture(&wgpu::TextureDescriptor { + label: Some("iced_wgpu.offscreen.source_texture"), + size: texture_extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.engine.format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -252,15 +239,12 @@ impl Renderer { }, ); - let output_buffer = - self.engine.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("iced_wgpu.offscreen.output_texture_buffer"), - size: (dimensions.padded_bytes_per_row - * dimensions.height as usize) as u64, - usage: wgpu::BufferUsages::MAP_READ - | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + let output_buffer = self.engine.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("iced_wgpu.offscreen.output_texture_buffer"), + size: (dimensions.padded_bytes_per_row * dimensions.height as usize) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); encoder.copy_texture_to_buffer( texture.as_image_copy(), @@ -289,28 +273,22 @@ impl Renderer { let mapped_buffer = slice.get_mapped_range(); - mapped_buffer.chunks(dimensions.padded_bytes_per_row).fold( - vec![], - |mut acc, row| { + mapped_buffer + .chunks(dimensions.padded_bytes_per_row) + .fold(vec![], |mut acc, row| { acc.extend(&row[..dimensions.unpadded_bytes_per_row]); acc - }, - ) + }) } - fn prepare( - &mut self, - encoder: &mut wgpu::CommandEncoder, - viewport: &Viewport, - ) { + fn prepare(&mut self, encoder: &mut wgpu::CommandEncoder, viewport: &Viewport) { let scale_factor = viewport.scale_factor(); self.text_viewport .update(&self.engine.queue, viewport.physical_size()); - let physical_bounds = Rectangle::::from(Rectangle::with_size( - viewport.physical_size(), - )); + let physical_bounds = + Rectangle::::from(Rectangle::with_size(viewport.physical_size())); self.layers.merge(); @@ -426,8 +404,8 @@ impl Renderer { ) { use std::mem::ManuallyDrop; - let mut render_pass = ManuallyDrop::new(encoder.begin_render_pass( - &wgpu::RenderPassDescriptor { + let mut render_pass = + ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: frame, @@ -437,8 +415,7 @@ impl Renderer { load: match clear_color { Some(background_color) => wgpu::LoadOp::Clear({ let [r, g, b, a] = - graphics::color::pack(background_color) - .components(); + graphics::color::pack(background_color).components(); wgpu::Color { r: f64::from(r), @@ -456,8 +433,7 @@ impl Renderer { timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, - }, - )); + })); let mut quad_layer = 0; let mut mesh_layer = 0; @@ -467,15 +443,14 @@ impl Renderer { let mut image_layer = 0; let scale_factor = viewport.scale_factor(); - let physical_bounds = Rectangle::::from(Rectangle::with_size( - viewport.physical_size(), - )); + let physical_bounds = + Rectangle::::from(Rectangle::with_size(viewport.physical_size())); let scale = Transformation::scale(scale_factor as f32); for layer in self.layers.iter() { - let Some(physical_bounds) = physical_bounds - .intersection(&(layer.bounds * scale_factor as f32)) + let Some(physical_bounds) = + physical_bounds.intersection(&(layer.bounds * scale_factor as f32)) else { continue; }; @@ -513,26 +488,23 @@ impl Renderer { ); render_span.finish(); - render_pass = ManuallyDrop::new(encoder.begin_render_pass( - &wgpu::RenderPassDescriptor { + render_pass = + ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), - color_attachments: &[Some( - wgpu::RenderPassColorAttachment { - view: frame, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: frame, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, }, - )], + })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, - }, - )); + })); } if !layer.primitives.is_empty() { @@ -599,34 +571,28 @@ impl Renderer { let _ = ManuallyDrop::into_inner(render_pass); for (instance, clip_bounds) in need_render { - instance.primitive.render( - &primitive_storage, - encoder, - frame, - &clip_bounds, - ); + instance + .primitive + .render(&primitive_storage, encoder, frame, &clip_bounds); } - render_pass = ManuallyDrop::new(encoder.begin_render_pass( - &wgpu::RenderPassDescriptor { + render_pass = + ManuallyDrop::new(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("iced_wgpu render pass"), - color_attachments: &[Some( - wgpu::RenderPassColorAttachment { - view: frame, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: frame, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, }, - )], + })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, - }, - )); + })); } render_span.finish(); @@ -675,49 +641,41 @@ impl Renderer { }); } - fn draw_overlay( - &mut self, - overlay: &[impl AsRef], - viewport: &Viewport, - ) { + fn draw_overlay(&mut self, overlay: &[impl AsRef], viewport: &Viewport) { use crate::core::Renderer as _; use crate::core::alignment; use crate::core::text::Renderer as _; - self.with_layer( - Rectangle::with_size(viewport.logical_size()), - |renderer| { - for (i, line) in overlay.iter().enumerate() { - let text = crate::core::Text { - content: line.as_ref().to_owned(), - bounds: viewport.logical_size(), - size: Pixels(20.0), - line_height: core::text::LineHeight::default(), - font: Font::MONOSPACE, - align_x: core::text::Alignment::Left, - align_y: alignment::Vertical::Top, - shaping: core::text::Shaping::Advanced, - wrapping: core::text::Wrapping::Word, - ellipsize: core::text::Ellipsize::None, - }; - - renderer.fill_text( - text.clone(), - Point::new(11.0, 11.0 + 25.0 * i as f32), - Color::from_rgba(0.9, 0.9, 0.9, 1.0), - Rectangle::with_size(Size::INFINITE), - ); + self.with_layer(Rectangle::with_size(viewport.logical_size()), |renderer| { + for (i, line) in overlay.iter().enumerate() { + let text = crate::core::Text { + content: line.as_ref().to_owned(), + bounds: viewport.logical_size(), + size: Pixels(20.0), + line_height: core::text::LineHeight::default(), + font: Font::MONOSPACE, + align_x: core::text::Alignment::Left, + align_y: alignment::Vertical::Top, + shaping: core::text::Shaping::Advanced, + wrapping: core::text::Wrapping::Word, + ellipsize: core::text::Ellipsize::None, + }; + + renderer.fill_text( + text.clone(), + Point::new(11.0, 11.0 + 25.0 * i as f32), + Color::from_rgba(0.9, 0.9, 0.9, 1.0), + Rectangle::with_size(Size::INFINITE), + ); - renderer.fill_text( - text, - Point::new(11.0, 11.0 + 25.0 * i as f32) - + Vector::new(-1.0, -1.0), - Color::BLACK, - Rectangle::with_size(Size::INFINITE), - ); - } - }, - ); + renderer.fill_text( + text, + Point::new(11.0, 11.0 + 25.0 * i as f32) + Vector::new(-1.0, -1.0), + Color::BLACK, + Rectangle::with_size(Size::INFINITE), + ); + } + }); } } @@ -738,11 +696,7 @@ impl core::Renderer for Renderer { self.layers.pop_transformation(); } - fn fill_quad( - &mut self, - quad: core::renderer::Quad, - background: impl Into, - ) { + fn fill_quad(&mut self, quad: core::renderer::Quad, background: impl Into) { let (layer, transformation) = self.layers.current_mut(); layer.draw_quad(quad, background.into(), transformation); } @@ -754,9 +708,7 @@ impl core::Renderer for Renderer { fn allocate_image( &mut self, _handle: &core::image::Handle, - _callback: impl FnOnce(Result) - + Send - + 'static, + _callback: impl FnOnce(Result) + Send + 'static, ) { #[cfg(feature = "image")] self.image_cache @@ -797,13 +749,7 @@ impl core::text::Renderer for Renderer { ) { let (layer, transformation) = self.layers.current_mut(); - layer.draw_paragraph( - text, - position, - color, - clip_bounds, - transformation, - ); + layer.draw_paragraph(text, position, color, clip_bounds, transformation); } fn fill_editor( @@ -849,23 +795,16 @@ impl core::image::Renderer for Renderer { &self, handle: &Self::Handle, ) -> Result { - self.image_cache.borrow_mut().load_image( - &self.engine.device, - &self.engine.queue, - handle, - ) + self.image_cache + .borrow_mut() + .load_image(&self.engine.device, &self.engine.queue, handle) } fn measure_image(&self, handle: &Self::Handle) -> Option> { self.image_cache.borrow_mut().measure_image(handle) } - fn draw_image( - &mut self, - image: core::Image, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_image(&mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_raster(image, bounds, clip_bounds, transformation); } @@ -877,12 +816,7 @@ impl core::svg::Renderer for Renderer { self.image_cache.borrow_mut().measure_svg(handle) } - fn draw_svg( - &mut self, - svg: core::Svg, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_svg(&mut self, svg: core::Svg, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_svg(svg, bounds, clip_bounds, transformation); } @@ -977,8 +911,7 @@ impl renderer::Headless for Renderer { } let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { - backends: wgpu::Backends::from_env() - .unwrap_or(wgpu::Backends::PRIMARY), + backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::PRIMARY), flags: wgpu::InstanceFlags::empty(), ..wgpu::InstanceDescriptor::default() }); diff --git a/wgpu/src/primitive.rs b/wgpu/src/primitive.rs index 4c18bb6a01..b6ff68c7ee 100644 --- a/wgpu/src/primitive.rs +++ b/wgpu/src/primitive.rs @@ -44,11 +44,7 @@ pub trait Primitive: Debug + MaybeSend + MaybeSync + 'static { /// [`render`](Self::render) by returning `false` here. /// /// By default, it does nothing and returns `false`. - fn draw( - &self, - _pipeline: &Self::Pipeline, - _render_pass: &mut wgpu::RenderPass<'_>, - ) -> bool { + fn draw(&self, _pipeline: &Self::Pipeline, _render_pass: &mut wgpu::RenderPass<'_>) -> bool { false } @@ -73,11 +69,7 @@ pub trait Pipeline: Any + MaybeSend + MaybeSync { /// /// This will only be called once, when the first [`Primitive`] with this kind /// of [`Pipeline`] is encountered. - fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - format: wgpu::TextureFormat, - ) -> Self + fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self where Self: Sized; @@ -87,9 +79,7 @@ pub trait Pipeline: Any + MaybeSend + MaybeSync { fn trim(&mut self) {} } -pub(crate) trait Stored: - Debug + MaybeSend + MaybeSync + 'static -{ +pub(crate) trait Stored: Debug + MaybeSend + MaybeSync + 'static { fn prepare( &self, storage: &mut Storage, @@ -100,11 +90,7 @@ pub(crate) trait Stored: viewport: &Viewport, ); - fn draw( - &self, - storage: &Storage, - render_pass: &mut wgpu::RenderPass<'_>, - ) -> bool; + fn draw(&self, storage: &Storage, render_pass: &mut wgpu::RenderPass<'_>) -> bool; fn render( &self, @@ -144,11 +130,7 @@ impl Stored for BlackBox

{ .prepare(renderer, device, queue, bounds, viewport); } - fn draw( - &self, - storage: &Storage, - render_pass: &mut wgpu::RenderPass<'_>, - ) -> bool { + fn draw(&self, storage: &Storage, render_pass: &mut wgpu::RenderPass<'_>) -> bool { let renderer = storage .get::

() .expect("renderer should be initialized") diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index 4cab2598ba..8d4e9beaf1 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -94,12 +94,7 @@ impl State { render_pass: &mut wgpu::RenderPass<'a>, ) { if let Some(layer) = self.layers.get(layer) { - render_pass.set_scissor_rect( - bounds.x, - bounds.y, - bounds.width, - bounds.height, - ); + render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); let mut solid_offset = 0; let mut gradient_offset = 0; @@ -138,22 +133,21 @@ impl State { impl Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipeline { - let constant_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::quad uniforms layout"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new( - mem::size_of::() as wgpu::BufferAddress, - ), - }, - count: None, - }], - }); + let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::quad uniforms layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new( + mem::size_of::() as wgpu::BufferAddress + ), + }, + count: None, + }], + }); Self { solid: solid::Pipeline::new(device, format, &constant_layout), @@ -172,10 +166,7 @@ pub struct Layer { } impl Layer { - pub fn new( - device: &wgpu::Device, - constant_layout: &wgpu::BindGroupLayout, - ) -> Self { + pub fn new(device: &wgpu::Device, constant_layout: &wgpu::BindGroupLayout) -> Self { let constants_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("iced_wgpu::quad uniforms buffer"), size: mem::size_of::() as wgpu::BufferAddress, @@ -319,9 +310,7 @@ enum Kind { Gradient, } -fn color_target_state( - format: wgpu::TextureFormat, -) -> [Option; 1] { +fn color_target_state(format: wgpu::TextureFormat) -> [Option; 1] { [Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), diff --git a/wgpu/src/quad/gradient.rs b/wgpu/src/quad/gradient.rs index 55e62e7945..4200f53b3a 100644 --- a/wgpu/src/quad/gradient.rs +++ b/wgpu/src/quad/gradient.rs @@ -72,93 +72,83 @@ impl Pipeline { ) -> Self { #[cfg(not(target_arch = "wasm32"))] { - let layout = device.create_pipeline_layout( - &wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu.quad.gradient.pipeline"), - bind_group_layouts: &[constants_layout], - immediate_size: 0, + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu.quad.gradient.pipeline"), + bind_group_layouts: &[constants_layout], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu.quad.gradient.shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( + include_str!("../shader/quad.wgsl"), + "\n", + include_str!("../shader/vertex.wgsl"), + "\n", + include_str!("../shader/quad/gradient.wgsl"), + "\n", + include_str!("../shader/color.wgsl"), + "\n", + include_str!("../shader/color/linear_rgb.wgsl") + ))), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu.quad.gradient.pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("gradient_vs_main"), + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &wgpu::vertex_attr_array!( + // Colors 1-2 + 0 => Uint32x4, + // Colors 3-4 + 1 => Uint32x4, + // Colors 5-6 + 2 => Uint32x4, + // Colors 7-8 + 3 => Uint32x4, + // Offsets 1-8 + 4 => Uint32x4, + // Direction + 5 => Float32x4, + // Position & Scale + 6 => Float32x4, + // Border color + 7 => Float32x4, + // Border radius + 8 => Float32x4, + // Border width + 9 => Float32, + // Snap + 10 => Uint32, + ), + }], + compilation_options: wgpu::PipelineCompilationOptions::default(), }, - ); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu.quad.gradient.shader"), - source: wgpu::ShaderSource::Wgsl( - std::borrow::Cow::Borrowed(concat!( - include_str!("../shader/quad.wgsl"), - "\n", - include_str!("../shader/vertex.wgsl"), - "\n", - include_str!("../shader/quad/gradient.wgsl"), - "\n", - include_str!("../shader/color.wgsl"), - "\n", - include_str!("../shader/color/linear_rgb.wgsl") - )), - ), - }); - - let pipeline = device.create_render_pipeline( - &wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu.quad.gradient.pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("gradient_vs_main"), - buffers: &[wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() - as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &wgpu::vertex_attr_array!( - // Colors 1-2 - 0 => Uint32x4, - // Colors 3-4 - 1 => Uint32x4, - // Colors 5-6 - 2 => Uint32x4, - // Colors 7-8 - 3 => Uint32x4, - // Offsets 1-8 - 4 => Uint32x4, - // Direction - 5 => Float32x4, - // Position & Scale - 6 => Float32x4, - // Border color - 7 => Float32x4, - // Border radius - 8 => Float32x4, - // Border width - 9 => Float32, - // Snap - 10 => Uint32, - ), - }], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("gradient_fs_main"), - targets: &quad::color_target_state(format), - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..Default::default() - }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, - }, - multiview_mask: None, - cache: None, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("gradient_fs_main"), + targets: &quad::color_target_state(format), + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..Default::default() }, - ); + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview_mask: None, + cache: None, + }); Self { pipeline } } diff --git a/wgpu/src/quad/solid.rs b/wgpu/src/quad/solid.rs index 49e4cf0181..c84f79be27 100644 --- a/wgpu/src/quad/solid.rs +++ b/wgpu/src/quad/solid.rs @@ -62,86 +62,79 @@ impl Pipeline { format: wgpu::TextureFormat, constants_layout: &wgpu::BindGroupLayout, ) -> Self { - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu.quad.solid.pipeline"), - bind_group_layouts: &[constants_layout], - immediate_size: 0, - }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu.quad.solid.pipeline"), + bind_group_layouts: &[constants_layout], + immediate_size: 0, + }); - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu.quad.solid.shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - concat!( - include_str!("../shader/color.wgsl"), - "\n", - include_str!("../shader/quad.wgsl"), - "\n", - include_str!("../shader/vertex.wgsl"), - "\n", - include_str!("../shader/quad/solid.wgsl"), - ), - )), - }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu.quad.solid.shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( + include_str!("../shader/color.wgsl"), + "\n", + include_str!("../shader/quad.wgsl"), + "\n", + include_str!("../shader/vertex.wgsl"), + "\n", + include_str!("../shader/quad/solid.wgsl"), + ))), + }); - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu.quad.solid.pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("solid_vs_main"), - buffers: &[wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &wgpu::vertex_attr_array!( - // Color - 0 => Float32x4, - // Position - 1 => Float32x2, - // Size - 2 => Float32x2, - // Border color - 3 => Float32x4, - // Border radius - 4 => Float32x4, - // Border width - 5 => Float32, - // Shadow color - 6 => Float32x4, - // Shadow offset - 7 => Float32x2, - // Shadow blur radius - 8 => Float32, - // Snap - 9 => Uint32, - ), - }], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("solid_fs_main"), - targets: &quad::color_target_state(format), - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..Default::default() - }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, - }, - multiview_mask: None, - cache: None, - }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu.quad.solid.pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("solid_vs_main"), + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &wgpu::vertex_attr_array!( + // Color + 0 => Float32x4, + // Position + 1 => Float32x2, + // Size + 2 => Float32x2, + // Border color + 3 => Float32x4, + // Border radius + 4 => Float32x4, + // Border width + 5 => Float32, + // Shadow color + 6 => Float32x4, + // Shadow offset + 7 => Float32x2, + // Shadow blur radius + 8 => Float32, + // Snap + 9 => Uint32, + ), + }], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("solid_fs_main"), + targets: &quad::color_target_state(format), + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview_mask: None, + cache: None, + }); Self { pipeline } } diff --git a/wgpu/src/text.rs b/wgpu/src/text.rs index b6d9e67900..0b893a4486 100644 --- a/wgpu/src/text.rs +++ b/wgpu/src/text.rs @@ -160,8 +160,7 @@ impl Storage { } // Only trim if glyphs have changed - group.should_trim = - group.should_trim || upload.version != cache.version; + group.should_trim = group.should_trim || upload.version != cache.version; upload.text = Arc::downgrade(&cache.text); upload.version = cache.version; @@ -276,15 +275,10 @@ pub struct Pipeline { } impl Pipeline { - pub fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - format: wgpu::TextureFormat, - ) -> Self { + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { let cache = cryoglyph::Cache::new(device); - let atlas = cryoglyph::TextAtlas::with_color_mode( - device, queue, &cache, format, COLOR_MODE, - ); + let atlas = + cryoglyph::TextAtlas::with_color_mode(device, queue, &cache, format, COLOR_MODE); Pipeline { format, @@ -400,12 +394,7 @@ impl State { let atlas = pipeline.atlas.read().expect("Read text atlas"); let mut layer_count = 0; - render_pass.set_scissor_rect( - bounds.x, - bounds.y, - bounds.width, - bounds.height, - ); + render_pass.set_scissor_rect(bounds.x, bounds.y, bounds.width, bounds.height); for item in batch { match item { @@ -465,12 +454,8 @@ fn prepare( let allocations: Vec<_> = sections .iter() .map(|section| match section { - Text::Paragraph { paragraph, .. } => { - paragraph.upgrade().map(Allocation::Paragraph) - } - Text::Editor { editor, .. } => { - editor.upgrade().map(Allocation::Editor) - } + Text::Paragraph { paragraph, .. } => paragraph.upgrade().map(Allocation::Paragraph), + Text::Editor { editor, .. } => editor.upgrade().map(Allocation::Editor), Text::Cached { content, bounds, @@ -503,127 +488,113 @@ fn prepare( }) .collect(); - let text_areas = sections.iter().zip(allocations.iter()).filter_map( - |(section, allocation)| { - let (buffer, position, color, clip_bounds, transformation) = - match section { - Text::Paragraph { - position, - color, - clip_bounds, - transformation, - .. - } => { - let Some(Allocation::Paragraph(paragraph)) = allocation - else { - return None; - }; - - ( - paragraph.buffer(), - *position, - *color, - *clip_bounds, - *transformation, - ) - } - Text::Editor { + let text_areas = sections + .iter() + .zip(allocations.iter()) + .filter_map(|(section, allocation)| { + let (buffer, position, color, clip_bounds, transformation) = match section { + Text::Paragraph { + position, + color, + clip_bounds, + transformation, + .. + } => { + let Some(Allocation::Paragraph(paragraph)) = allocation else { + return None; + }; + + ( + paragraph.buffer(), + *position, + *color, + *clip_bounds, + *transformation, + ) + } + Text::Editor { + position, + color, + clip_bounds, + transformation, + .. + } => { + let Some(Allocation::Editor(editor)) = allocation else { + return None; + }; + + ( + editor.buffer(), + *position, + *color, + *clip_bounds, + *transformation, + ) + } + Text::Cached { + bounds, + align_x, + align_y, + color, + clip_bounds, + .. + } => { + let Some(Allocation::Cache(key)) = allocation else { + return None; + }; + + let entry = buffer_cache.get(key).expect("Get cached buffer"); + + let mut position = bounds.position(); + + position.x = match align_x { + Alignment::Default | Alignment::Left | Alignment::Justified => position.x, + Alignment::Center => position.x - entry.min_bounds.width / 2.0, + Alignment::Right => position.x - entry.min_bounds.width, + }; + + position.y = match align_y { + alignment::Vertical::Top => position.y, + alignment::Vertical::Center => position.y - entry.min_bounds.height / 2.0, + alignment::Vertical::Bottom => position.y - entry.min_bounds.height, + }; + + ( + &entry.buffer, position, - color, - clip_bounds, - transformation, - .. - } => { - let Some(Allocation::Editor(editor)) = allocation - else { - return None; - }; - - ( - editor.buffer(), - *position, - *color, - *clip_bounds, - *transformation, - ) - } - Text::Cached { - bounds, - align_x, - align_y, - color, - clip_bounds, - .. - } => { - let Some(Allocation::Cache(key)) = allocation else { - return None; - }; - - let entry = - buffer_cache.get(key).expect("Get cached buffer"); - - let mut position = bounds.position(); - - position.x = match align_x { - Alignment::Default - | Alignment::Left - | Alignment::Justified => position.x, - Alignment::Center => { - position.x - entry.min_bounds.width / 2.0 - } - Alignment::Right => { - position.x - entry.min_bounds.width - } - }; - - position.y = match align_y { - alignment::Vertical::Top => position.y, - alignment::Vertical::Center => { - position.y - entry.min_bounds.height / 2.0 - } - alignment::Vertical::Bottom => { - position.y - entry.min_bounds.height - } - }; - - ( - &entry.buffer, - position, - *color, - *clip_bounds, - Transformation::IDENTITY, - ) - } - Text::Raw { - raw, - transformation, - } => { - let Some(Allocation::Raw(buffer)) = allocation else { - return None; - }; - - ( - buffer.as_ref(), - raw.position, - raw.color, - raw.clip_bounds, - *transformation, - ) - } - }; + *color, + *clip_bounds, + Transformation::IDENTITY, + ) + } + Text::Raw { + raw, + transformation, + } => { + let Some(Allocation::Raw(buffer)) = allocation else { + return None; + }; + + ( + buffer.as_ref(), + raw.position, + raw.color, + raw.clip_bounds, + *transformation, + ) + } + }; let position = position * transformation * layer_transformation; - let clip_bounds = layer_bounds.intersection( - &(clip_bounds * transformation * layer_transformation), - )?; + let clip_bounds = layer_bounds + .intersection(&(clip_bounds * transformation * layer_transformation))?; Some(cryoglyph::TextArea { text: buffer.layout_runs(), left: position.x, top: position.y, - scale: transformation.scale_factor() - * layer_transformation.scale_factor(), + scale: transformation.scale_factor() * layer_transformation.scale_factor(), bounds: cryoglyph::TextBounds { left: clip_bounds.x.round() as i32, top: clip_bounds.y.round() as i32, @@ -632,8 +603,7 @@ fn prepare( }, default_color: to_color(color), }) - }, - ); + }); renderer.prepare( device, diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index 5607d03a2e..bf031e5a00 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -158,14 +158,12 @@ impl State { scale: Transformation, target_size: Size, ) { - let projection = if let Some((state, pipeline)) = - self.msaa.as_mut().zip(pipeline.msaa.as_ref()) - { - state.prepare(device, encoder, belt, pipeline, target_size) * scale - } else { - Transformation::orthographic(target_size.width, target_size.height) - * scale - }; + let projection = + if let Some((state, pipeline)) = self.msaa.as_mut().zip(pipeline.msaa.as_ref()) { + state.prepare(device, encoder, belt, pipeline, target_size) * scale + } else { + Transformation::orthographic(target_size.width, target_size.height) * scale + }; for item in items { match item { @@ -174,11 +172,8 @@ impl State { meshes, } => { if self.layers.len() <= self.prepare_layer { - self.layers.push(Layer::new( - device, - &pipeline.solid, - &pipeline.gradient, - )); + self.layers + .push(Layer::new(device, &pipeline.solid, &pipeline.gradient)); } let layer = &mut self.layers[self.prepare_layer]; @@ -342,11 +337,7 @@ pub struct Layer { } impl Layer { - fn new( - device: &wgpu::Device, - solid: &solid::Pipeline, - gradient: &gradient::Pipeline, - ) -> Self { + fn new(device: &wgpu::Device, solid: &solid::Pipeline, gradient: &gradient::Pipeline) -> Self { Self { index_buffer: Buffer::new( device, @@ -384,11 +375,8 @@ impl Layer { .resize(device, count.gradient_vertices); if self.solid.uniforms.resize(device, count.solids) { - self.solid.constants = solid::Layer::bind_group( - device, - &self.solid.uniforms.raw, - &solid.constants_layout, - ); + self.solid.constants = + solid::Layer::bind_group(device, &self.solid.uniforms.raw, &solid.constants_layout); } if self.gradient.uniforms.resize(device, count.gradients) { @@ -418,17 +406,14 @@ impl Layer { let uniforms = Uniforms::new( transformation * mesh.transformation() - * Transformation::translate( - snap_distance.x, - snap_distance.y, - ), + * Transformation::translate(snap_distance.x, snap_distance.y), ); let indices = mesh.indices(); - index_offset += - self.index_buffer - .write(encoder, belt, index_offset, indices); + index_offset += self + .index_buffer + .write(encoder, belt, index_offset, indices); match mesh { Mesh::Solid { buffers, .. } => { @@ -439,12 +424,10 @@ impl Layer { &buffers.vertices, ); - solid_uniform_offset += self.solid.uniforms.write( - encoder, - belt, - solid_uniform_offset, - &[uniforms], - ) + solid_uniform_offset += + self.solid + .uniforms + .write(encoder, belt, solid_uniform_offset, &[uniforms]) } Mesh::Gradient { buffers, .. } => { gradient_vertex_offset += self.gradient.vertices.write( @@ -517,16 +500,14 @@ impl Layer { render_pass.set_bind_group( 0, &self.solid.constants, - &[(num_solids * std::mem::size_of::()) - as u32], + &[(num_solids * std::mem::size_of::()) as u32], ); render_pass.set_vertex_buffer( 0, - self.solid.vertices.range( - solid_offset, - solid_offset + buffers.vertices.len(), - ), + self.solid + .vertices + .range(solid_offset, solid_offset + buffers.vertices.len()), ); num_solids += 1; @@ -542,16 +523,14 @@ impl Layer { render_pass.set_bind_group( 0, &self.gradient.constants, - &[(num_gradients * std::mem::size_of::()) - as u32], + &[(num_gradients * std::mem::size_of::()) as u32], ); render_pass.set_vertex_buffer( 0, - self.gradient.vertices.range( - gradient_offset, - gradient_offset + buffers.vertices.len(), - ), + self.gradient + .vertices + .range(gradient_offset, gradient_offset + buffers.vertices.len()), ); num_gradients += 1; @@ -572,9 +551,7 @@ impl Layer { } } -fn fragment_target( - texture_format: wgpu::TextureFormat, -) -> wgpu::ColorTargetState { +fn fragment_target(texture_format: wgpu::TextureFormat) -> wgpu::ColorTargetState { wgpu::ColorTargetState { format: texture_format, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), @@ -590,9 +567,7 @@ fn primitive_state() -> wgpu::PrimitiveState { } } -fn multisample_state( - antialiasing: Option, -) -> wgpu::MultisampleState { +fn multisample_state(antialiasing: Option) -> wgpu::MultisampleState { wgpu::MultisampleState { count: antialiasing.map(Antialiasing::sample_count).unwrap_or(1), mask: !0, @@ -624,9 +599,7 @@ impl Uniforms { ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, - min_binding_size: wgpu::BufferSize::new( - std::mem::size_of::() as u64, - ), + min_binding_size: wgpu::BufferSize::new(std::mem::size_of::() as u64), }, count: None, } @@ -657,10 +630,7 @@ mod solid { } impl Layer { - pub fn new( - device: &wgpu::Device, - constants_layout: &wgpu::BindGroupLayout, - ) -> Self { + pub fn new(device: &wgpu::Device, constants_layout: &wgpu::BindGroupLayout) -> Self { let vertices = Buffer::new( device, "iced_wgpu.triangle.solid.vertex_buffer", @@ -675,8 +645,7 @@ mod solid { wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, ); - let constants = - Self::bind_group(device, &uniforms.raw, constants_layout); + let constants = Self::bind_group(device, &uniforms.raw, constants_layout); Self { vertices, @@ -695,13 +664,11 @@ mod solid { layout, entries: &[wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer, - offset: 0, - size: triangle::Uniforms::min_size(), - }, - ), + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: 0, + size: triangle::Uniforms::min_size(), + }), }], }) } @@ -713,74 +680,59 @@ mod solid { format: wgpu::TextureFormat, antialiasing: Option, ) -> Self { - let constants_layout = device.create_bind_group_layout( - &wgpu::BindGroupLayoutDescriptor { + let constants_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("iced_wgpu.triangle.solid.bind_group_layout"), entries: &[triangle::Uniforms::entry()], - }, - ); - - let layout = device.create_pipeline_layout( - &wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu.triangle.solid.pipeline_layout"), - bind_group_layouts: &[&constants_layout], - immediate_size: 0, - }, - ); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu.triangle.solid.shader"), - source: wgpu::ShaderSource::Wgsl( - std::borrow::Cow::Borrowed(concat!( - include_str!("shader/triangle.wgsl"), - "\n", - include_str!("shader/triangle/solid.wgsl"), - "\n", - include_str!("shader/color.wgsl"), - )), - ), }); - let pipeline = - device.create_render_pipeline( - &wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu::triangle::solid pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("solid_vs_main"), - buffers: &[wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::< - mesh::SolidVertex2D, - >( - ) - as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &wgpu::vertex_attr_array!( - // Position - 0 => Float32x2, - // Color - 1 => Float32x4, - ), - }], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("solid_fs_main"), - targets: &[Some(triangle::fragment_target(format))], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: triangle::primitive_state(), - depth_stencil: None, - multisample: triangle::multisample_state(antialiasing), - multiview_mask: None, - cache: None, - }, - ); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu.triangle.solid.pipeline_layout"), + bind_group_layouts: &[&constants_layout], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu.triangle.solid.shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( + include_str!("shader/triangle.wgsl"), + "\n", + include_str!("shader/triangle/solid.wgsl"), + "\n", + include_str!("shader/color.wgsl"), + ))), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu::triangle::solid pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("solid_vs_main"), + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array!( + // Position + 0 => Float32x2, + // Color + 1 => Float32x4, + ), + }], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("solid_fs_main"), + targets: &[Some(triangle::fragment_target(format))], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: triangle::primitive_state(), + depth_stencil: None, + multisample: triangle::multisample_state(antialiasing), + multiview_mask: None, + cache: None, + }); Self { pipeline, @@ -810,10 +762,7 @@ mod gradient { } impl Layer { - pub fn new( - device: &wgpu::Device, - constants_layout: &wgpu::BindGroupLayout, - ) -> Self { + pub fn new(device: &wgpu::Device, constants_layout: &wgpu::BindGroupLayout) -> Self { let vertices = Buffer::new( device, "iced_wgpu.triangle.gradient.vertex_buffer", @@ -828,8 +777,7 @@ mod gradient { wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, ); - let constants = - Self::bind_group(device, &uniforms.raw, constants_layout); + let constants = Self::bind_group(device, &uniforms.raw, constants_layout); Self { vertices, @@ -848,13 +796,11 @@ mod gradient { layout, entries: &[wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer( - wgpu::BufferBinding { - buffer: uniform_buffer, - offset: 0, - size: triangle::Uniforms::min_size(), - }, - ), + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: uniform_buffer, + offset: 0, + size: triangle::Uniforms::min_size(), + }), }], }) } @@ -866,86 +812,71 @@ mod gradient { format: wgpu::TextureFormat, antialiasing: Option, ) -> Self { - let constants_layout = device.create_bind_group_layout( - &wgpu::BindGroupLayoutDescriptor { - label: Some( - "iced_wgpu.triangle.gradient.bind_group_layout", - ), + let constants_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu.triangle.gradient.bind_group_layout"), entries: &[triangle::Uniforms::entry()], - }, - ); - - let layout = device.create_pipeline_layout( - &wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu.triangle.gradient.pipeline_layout"), - bind_group_layouts: &[&constants_layout], - immediate_size: 0, - }, - ); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu.triangle.gradient.shader"), - source: wgpu::ShaderSource::Wgsl( - std::borrow::Cow::Borrowed(concat!( - include_str!("shader/triangle.wgsl"), - "\n", - include_str!("shader/triangle/gradient.wgsl"), - "\n", - include_str!("shader/color.wgsl"), - "\n", - include_str!("shader/color/linear_rgb.wgsl") - )), - ), }); - let pipeline = device.create_render_pipeline( - &wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu.triangle.gradient.pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("gradient_vs_main"), - buffers: &[wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::< - mesh::GradientVertex2D, - >() - as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &wgpu::vertex_attr_array!( - // Position - 0 => Float32x2, - // Colors 1-2 - 1 => Uint32x4, - // Colors 3-4 - 2 => Uint32x4, - // Colors 5-6 - 3 => Uint32x4, - // Colors 7-8 - 4 => Uint32x4, - // Offsets - 5 => Uint32x4, - // Direction - 6 => Float32x4 - ), - }], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("gradient_fs_main"), - targets: &[Some(triangle::fragment_target(format))], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: triangle::primitive_state(), - depth_stencil: None, - multisample: triangle::multisample_state(antialiasing), - multiview_mask: None, - cache: None, + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu.triangle.gradient.pipeline_layout"), + bind_group_layouts: &[&constants_layout], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu.triangle.gradient.shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!( + include_str!("shader/triangle.wgsl"), + "\n", + include_str!("shader/triangle/gradient.wgsl"), + "\n", + include_str!("shader/color.wgsl"), + "\n", + include_str!("shader/color/linear_rgb.wgsl") + ))), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu.triangle.gradient.pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("gradient_vs_main"), + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array!( + // Position + 0 => Float32x2, + // Colors 1-2 + 1 => Uint32x4, + // Colors 3-4 + 2 => Uint32x4, + // Colors 5-6 + 3 => Uint32x4, + // Colors 7-8 + 4 => Uint32x4, + // Offsets + 5 => Uint32x4, + // Direction + 6 => Float32x4 + ), + }], + compilation_options: wgpu::PipelineCompilationOptions::default(), }, - ); + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("gradient_fs_main"), + targets: &[Some(triangle::fragment_target(format))], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: triangle::primitive_state(), + depth_stencil: None, + multisample: triangle::multisample_state(antialiasing), + multiview_mask: None, + cache: None, + }); Self { pipeline, diff --git a/wgpu/src/triangle/msaa.rs b/wgpu/src/triangle/msaa.rs index 4611836163..f42728b7f1 100644 --- a/wgpu/src/triangle/msaa.rs +++ b/wgpu/src/triangle/msaa.rs @@ -21,104 +21,90 @@ impl Pipeline { format: wgpu::TextureFormat, antialiasing: graphics::Antialiasing, ) -> Pipeline { - let sampler = - device.create_sampler(&wgpu::SamplerDescriptor::default()); - - let constant_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::triangle:msaa uniforms layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler( - wgpu::SamplerBindingType::NonFiltering, - ), - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default()); - let texture_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("iced_wgpu::triangle::msaa texture layout"), - entries: &[wgpu::BindGroupLayoutEntry { + let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::triangle:msaa uniforms layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { - filterable: false, - }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering), count: None, - }], - }); - - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("iced_wgpu::triangle::msaa pipeline layout"), - bind_group_layouts: &[&constant_layout, &texture_layout], - immediate_size: 0, - }); - - let shader = - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("iced_wgpu triangle blit_shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( - include_str!("../shader/blit.wgsl"), - )), - }); - - let pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("iced_wgpu::triangle::msaa pipeline"), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: &[], - compilation_options: - wgpu::PipelineCompilationOptions::default(), }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some( - wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING, - ), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: - wgpu::PipelineCompilationOptions::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Cw, - ..Default::default() + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, + ], + }); + + let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("iced_wgpu::triangle::msaa texture layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, }, - multiview_mask: None, - cache: None, - }); + count: None, + }], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("iced_wgpu::triangle::msaa pipeline layout"), + bind_group_layouts: &[&constant_layout, &texture_layout], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("iced_wgpu triangle blit_shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!( + "../shader/blit.wgsl" + ))), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("iced_wgpu::triangle::msaa pipeline"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview_mask: None, + cache: None, + }); Self { format, @@ -131,11 +117,7 @@ impl Pipeline { } } - fn targets( - &self, - device: &wgpu::Device, - region_size: Size, - ) -> Targets { + fn targets(&self, device: &wgpu::Device, region_size: Size) -> Targets { let mut targets = self.targets.write().expect("Write MSAA targets"); match targets.as_mut() { @@ -156,10 +138,7 @@ impl Pipeline { targets.as_ref().unwrap().clone() } - pub fn render_pass<'a>( - &self, - encoder: &'a mut wgpu::CommandEncoder, - ) -> wgpu::RenderPass<'a> { + pub fn render_pass<'a>(&self, encoder: &'a mut wgpu::CommandEncoder) -> wgpu::RenderPass<'a> { let targets = self.targets.read().expect("Read MSAA targets"); let targets = targets.as_ref().unwrap(); @@ -222,16 +201,13 @@ impl Targets { sample_count: 1, dimension: wgpu::TextureDimension::D2, format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::TEXTURE_BINDING, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); - let attachment = - attachment.create_view(&wgpu::TextureViewDescriptor::default()); + let attachment = attachment.create_view(&wgpu::TextureViewDescriptor::default()); - let resolve = - resolve.create_view(&wgpu::TextureViewDescriptor::default()); + let resolve = resolve.create_view(&wgpu::TextureViewDescriptor::default()); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("iced_wgpu::triangle::msaa texture bind group"), @@ -319,8 +295,7 @@ impl State { encoder, &self.ratio, 0, - NonZeroU64::new(std::mem::size_of::() as u64) - .expect("non-empty ratio"), + NonZeroU64::new(std::mem::size_of::() as u64).expect("non-empty ratio"), ) .copy_from_slice(bytemuck::bytes_of(&ratio)); @@ -336,23 +311,22 @@ impl State { encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, ) { - let mut render_pass = - encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("iced_wgpu::triangle::msaa render pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("iced_wgpu::triangle::msaa render pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); render_pass.set_pipeline(&pipeline.raw); render_pass.set_bind_group(0, &self.constants, &[]); diff --git a/wgpu/src/window.rs b/wgpu/src/window.rs index b9ec54bd8f..fb8212fa45 100644 --- a/wgpu/src/window.rs +++ b/wgpu/src/window.rs @@ -30,16 +30,14 @@ fn ids_from_dev(dev: u64) -> Option<(u16, u16)> { let mut file = File::open(&path).ok()?; let mut contents = String::new(); let _ = file.read_to_string(&mut contents).ok()?; - u16::from_str_radix(contents.trim().trim_start_matches("0x"), 16) - .ok()? + u16::from_str_radix(contents.trim().trim_start_matches("0x"), 16).ok()? }; let device = { let path = path.join("device"); let mut file = File::open(&path).ok()?; let mut contents = String::new(); let _ = file.read_to_string(&mut contents).ok()?; - u16::from_str_radix(contents.trim().trim_start_matches("0x"), 16) - .ok()? + u16::from_str_radix(contents.trim().trim_start_matches("0x"), 16).ok()? }; Some((vendor, device)) diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index d3f4bf8cbb..8d3409eb07 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -72,8 +72,7 @@ impl Compositor { not(target_os = "redox") ))] let ids = compatible_window.as_ref().and_then(|window| { - get_wayland_device_ids(window) - .or_else(|| get_x11_device_ids(window)) + get_wayland_device_ids(window).or_else(|| get_x11_device_ids(window)) }); // HACK: @@ -89,8 +88,7 @@ impl Compositor { not(target_os = "redox") ))] if !matches!(ids, Some((0x10de, _))) - && std::env::var_os("__NV_PRIME_RENDER_OFFLOAD") - .is_none_or(|var| var == "0") + && std::env::var_os("__NV_PRIME_RENDER_OFFLOAD").is_none_or(|var| var == "0") && std::env::var_os("WGPU_ADAPTER_NAME").is_none() && std::env::var("WGPU_POWER_PREF").as_deref() != Ok("high") { @@ -103,8 +101,8 @@ impl Compositor { // Otherwise it will panic when it drops the available adapters! let non_gl_backends = settings.backends.difference(Backends::GL); // only load the instance after setting environment variables, this initializes the vulkan loader - let mut instance = wgpu::util::new_instance_with_webgpu_detection( - &wgpu::InstanceDescriptor { + let mut instance = + wgpu::util::new_instance_with_webgpu_detection(&wgpu::InstanceDescriptor { backends: non_gl_backends, flags: if cfg!(feature = "strict-assertions") { wgpu::InstanceFlags::debugging() @@ -112,9 +110,8 @@ impl Compositor { wgpu::InstanceFlags::empty() }, ..Default::default() - }, - ) - .await; + }) + .await; log::info!("{settings:#?}"); @@ -160,8 +157,7 @@ impl Compositor { .into_iter() .filter(|adapter| { let info = adapter.get_info(); - info.device == device_id as u32 - && info.vendor == vendor_id as u32 + info.device == device_id as u32 && info.vendor == vendor_id as u32 }) .find(|adapter| { if let Some(surface) = compatible_surface.as_ref() { @@ -193,8 +189,8 @@ impl Compositor { Some(adapter) => adapter, None => { // fall back to allowing GL backend if enabled - instance = wgpu::util::new_instance_with_webgpu_detection( - &wgpu::InstanceDescriptor { + instance = + wgpu::util::new_instance_with_webgpu_detection(&wgpu::InstanceDescriptor { backends: settings.backends, flags: if cfg!(feature = "strict-assertions") { wgpu::InstanceFlags::debugging() @@ -202,20 +198,20 @@ impl Compositor { wgpu::InstanceFlags::empty() }, ..Default::default() - }, - ) - .await; - compatible_surface = compatible_window - .and_then(|window| instance.create_surface(window).ok()); + }) + .await; + compatible_surface = + compatible_window.and_then(|window| instance.create_surface(window).ok()); adapter_options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::from_env() .unwrap_or(wgpu::PowerPreference::HighPerformance), compatible_surface: compatible_surface.as_ref(), force_fallback_adapter: false, }; - instance.request_adapter(&adapter_options).await.map_err( - |_| Error::NoAdapterFound(format!("{:?}", adapter_options)), - )? + instance + .request_adapter(&adapter_options) + .await + .map_err(|_| Error::NoAdapterFound(format!("{:?}", adapter_options)))? } }; log::info!("Selected: {:#?}", adapter.get_info()); @@ -255,33 +251,26 @@ impl Compositor { log::info!("Available alpha modes: {alpha_modes:#?}"); - let preferred_alpha = if alpha_modes - .contains(&wgpu::CompositeAlphaMode::PostMultiplied) - { - wgpu::CompositeAlphaMode::PostMultiplied - } else if alpha_modes - .contains(&wgpu::CompositeAlphaMode::PreMultiplied) - { - wgpu::CompositeAlphaMode::PreMultiplied - } else { - wgpu::CompositeAlphaMode::Auto - }; + let preferred_alpha = + if alpha_modes.contains(&wgpu::CompositeAlphaMode::PostMultiplied) { + wgpu::CompositeAlphaMode::PostMultiplied + } else if alpha_modes.contains(&wgpu::CompositeAlphaMode::PreMultiplied) { + wgpu::CompositeAlphaMode::PreMultiplied + } else { + wgpu::CompositeAlphaMode::Auto + }; format.zip(Some(preferred_alpha)) }) .ok_or(Error::IncompatibleSurface)?; - log::info!( - "Selected format: {format:?} with alpha mode: {alpha_mode:?}" - ); + log::info!("Selected format: {format:?} with alpha mode: {alpha_mode:?}"); #[cfg(target_arch = "wasm32")] - let limits = [wgpu::Limits::downlevel_webgl2_defaults() - .using_resolution(adapter.limits())]; + let limits = [wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits())]; #[cfg(not(target_arch = "wasm32"))] - let limits = - [wgpu::Limits::default(), wgpu::Limits::downlevel_defaults()]; + let limits = [wgpu::Limits::default(), wgpu::Limits::downlevel_defaults()]; let limits = limits.into_iter().map(|limits| wgpu::Limits { max_bind_groups: 2, @@ -294,15 +283,12 @@ impl Compositor { for required_limits in limits { let result = adapter .request_device(&wgpu::DeviceDescriptor { - label: Some( - "iced_wgpu::window::compositor device descriptor", - ), + label: Some("iced_wgpu::window::compositor device descriptor"), required_features: wgpu::Features::SHADER_F16, required_limits: required_limits.clone(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, - experimental_features: wgpu::ExperimentalFeatures::disabled( - ), + experimental_features: wgpu::ExperimentalFeatures::disabled(), }) .await; @@ -373,16 +359,10 @@ pub fn present( Ok(()) } Err(error) => match error { - wgpu::SurfaceError::Timeout => { - Err(compositor::SurfaceError::Timeout) - } - wgpu::SurfaceError::Outdated => { - Err(compositor::SurfaceError::Outdated) - } + wgpu::SurfaceError::Timeout => Err(compositor::SurfaceError::Timeout), + wgpu::SurfaceError::Outdated => Err(compositor::SurfaceError::Outdated), wgpu::SurfaceError::Lost => Err(compositor::SurfaceError::Lost), - wgpu::SurfaceError::OutOfMemory => { - Err(compositor::SurfaceError::OutOfMemory) - } + wgpu::SurfaceError::OutOfMemory => Err(compositor::SurfaceError::OutOfMemory), wgpu::SurfaceError::Other => Err(compositor::SurfaceError::Other), }, } @@ -448,12 +428,7 @@ impl graphics::Compositor for Compositor { surface } - fn configure_surface( - &mut self, - surface: &mut Self::Surface, - width: u32, - height: u32, - ) { + fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { surface.configure( &self.engine.device, &wgpu::SurfaceConfiguration { diff --git a/wgpu/src/window/wayland.rs b/wgpu/src/window/wayland.rs index 48e00def30..c02808daef 100644 --- a/wgpu/src/window/wayland.rs +++ b/wgpu/src/window/wayland.rs @@ -6,8 +6,7 @@ use cctk::sctk::{ }; use raw_window_handle::{RawDisplayHandle, WaylandDisplayHandle}; use wayland_client::{ - Connection, QueueHandle, backend::Backend, globals::registry_queue_init, - protocol::wl_buffer, + Connection, QueueHandle, backend::Backend, globals::registry_queue_init, protocol::wl_buffer, }; use wayland_protocols::wp::linux_dmabuf::zv1::client::{ zwp_linux_buffer_params_v1, zwp_linux_dmabuf_feedback_v1, @@ -74,11 +73,11 @@ pub fn get_wayland_device_ids(window: &W) -> Option<(u16, u16)> { let conn = match window.display_handle().map(|handle| handle.as_raw()) { #[allow(unsafe_code)] - Ok(RawDisplayHandle::Wayland(WaylandDisplayHandle { - display, .. - })) => Connection::from_backend(unsafe { - Backend::from_foreign_display(display.as_ptr() as *mut _) - }), + Ok(RawDisplayHandle::Wayland(WaylandDisplayHandle { display, .. })) => { + Connection::from_backend(unsafe { + Backend::from_foreign_display(display.as_ptr() as *mut _) + }) + } _ => { return None; } diff --git a/wgpu/src/window/x11.rs b/wgpu/src/window/x11.rs index 58da401a2e..1f311cd5a5 100644 --- a/wgpu/src/window/x11.rs +++ b/wgpu/src/window/x11.rs @@ -7,19 +7,14 @@ use std::{ use crate::graphics::compositor::Window; use as_raw_xcb_connection::AsRawXcbConnection; -use raw_window_handle::{ - RawDisplayHandle, XcbDisplayHandle, XlibDisplayHandle, -}; +use raw_window_handle::{RawDisplayHandle, XcbDisplayHandle, XlibDisplayHandle}; use rustix::fs::{fstat, stat}; use tiny_xlib::Display; use x11rb::{ connection::{Connection, RequestConnection}, protocol::{ dri3::{ConnectionExt as _, X11_EXTENSION_NAME as DRI3_NAME}, - randr::{ - ConnectionExt as _, ProviderCapability, - X11_EXTENSION_NAME as RANDR_NAME, - }, + randr::{ConnectionExt as _, ProviderCapability, X11_EXTENSION_NAME as RANDR_NAME}, }, xcb_ffi::XCBConnection, }; @@ -28,15 +23,10 @@ pub fn get_x11_device_ids(window: &W) -> Option<(u16, u16)> { x11rb::xcb_ffi::load_libxcb().ok()?; #[allow(unsafe_code)] - let (conn, screen) = match window - .display_handle() - .map(|handle| handle.as_raw()) - { + let (conn, screen) = match window.display_handle().map(|handle| handle.as_raw()) { #[allow(unsafe_code)] Ok(RawDisplayHandle::Xlib(XlibDisplayHandle { - display, - screen, - .. + display, screen, .. })) => match display { Some(ptr) => unsafe { let xlib_display = Display::from_ptr(ptr.as_ptr()); @@ -52,15 +42,10 @@ pub fn get_x11_device_ids(window: &W) -> Option<(u16, u16)> { None => (XCBConnection::connect(None).ok()?.0, screen), }, Ok(RawDisplayHandle::Xcb(XcbDisplayHandle { - connection, - screen, - .. + connection, screen, .. })) => match connection { Some(ptr) => ( - unsafe { - XCBConnection::from_raw_xcb_connection(ptr.as_ptr(), false) - .ok()? - }, + unsafe { XCBConnection::from_raw_xcb_connection(ptr.as_ptr(), false).ok()? }, screen, ), None => (XCBConnection::connect(None).ok()?.0, screen), @@ -82,9 +67,7 @@ pub fn get_x11_device_ids(window: &W) -> Option<(u16, u16)> { let _ = conn.extension_information(RANDR_NAME).ok()??; // check version, because we need providers to exist let version = conn.randr_query_version(1, 4).ok()?.reply().ok()?; - if version.major_version < 1 - || (version.major_version == 1 && version.minor_version < 4) - { + if version.major_version < 1 || (version.major_version == 1 && version.minor_version < 4) { return None; } @@ -109,19 +92,17 @@ pub fn get_x11_device_ids(window: &W) -> Option<(u16, u16)> { } // if that name is formatted `NVIDIA-x`, then x represents the /dev/nvidiaX number, which we can relate to /dev/dri - if let Some(number) = name.and_then(|name| { - name.trim().strip_prefix("NVIDIA-")?.parse::().ok() - }) { + if let Some(number) = + name.and_then(|name| name.trim().strip_prefix("NVIDIA-")?.parse::().ok()) + { // let it be known, that I hate this "interface"... for busid in fs::read_dir("/proc/driver/nvidia/gpus") .ok()? .map(Result::ok) .flatten() { - for line in BufReader::new( - fs::File::open(busid.path().join("information")).ok()?, - ) - .lines() + for line in + BufReader::new(fs::File::open(busid.path().join("information")).ok()?).lines() { if let Ok(line) = line { if line.starts_with("Device Minor") { @@ -142,8 +123,7 @@ pub fn get_x11_device_ids(window: &W) -> Option<(u16, u16)> { if device.to_string_lossy().starts_with("card") || device.to_string_lossy().starts_with("render") { - let stat = - stat(Path::new("/dev/dri").join(device)).ok()?; + let stat = stat(Path::new("/dev/dri").join(device)).ok()?; let dev = stat.st_rdev; return super::ids_from_dev(dev); } diff --git a/widget/src/action.rs b/widget/src/action.rs index cc31e76a6e..2ee7b6c556 100644 --- a/widget/src/action.rs +++ b/widget/src/action.rs @@ -73,9 +73,7 @@ impl Action { /// /// This method is meant to be used by runtimes, libraries, or internal /// widget implementations. - pub fn into_inner( - self, - ) -> (Option, window::RedrawRequest, event::Status) { + pub fn into_inner(self) -> (Option, window::RedrawRequest, event::Status) { ( self.message_to_publish, self.redraw_request, diff --git a/widget/src/button.rs b/widget/src/button.rs index f137221ed6..0cf71d709e 100644 --- a/widget/src/button.rs +++ b/widget/src/button.rs @@ -34,8 +34,8 @@ use crate::core::widget::Operation; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ - Background, Clipboard, Color, Element, Event, Layout, Length, Padding, - Rectangle, Shadow, Shell, Size, Theme, Vector, Widget, + Background, Clipboard, Color, Element, Event, Layout, Length, Padding, Rectangle, Shadow, + Shell, Size, Theme, Vector, Widget, }; use iced_renderer::core::widget::operation; @@ -119,9 +119,7 @@ where Theme: Catalog, { /// Creates a new [`Button`] with the given content. - pub fn new( - content: impl Into>, - ) -> Self { + pub fn new(content: impl Into>) -> Self { let content = content.into(); let size = content.as_widget().size_hint(); @@ -178,10 +176,7 @@ where /// This closure will only be called when the [`Button`] is actually pressed and, /// therefore, this method is useful to reduce overhead if creating the resulting /// message is slow. - pub fn on_press_with( - mut self, - on_press: impl Fn() -> Message + 'a, - ) -> Self { + pub fn on_press_with(mut self, on_press: impl Fn() -> Message + 'a) -> Self { self.on_press = Some(OnPress::Closure(Box::new(on_press))); self } @@ -235,10 +230,7 @@ where #[cfg(feature = "a11y")] /// Sets the description of the [`Button`]. - pub fn description_widget( - mut self, - description: &T, - ) -> Self { + pub fn description_widget(mut self, description: &T) -> Self { self.description = Some(iced_accessibility::Description::Id( description.description(), )); @@ -248,16 +240,14 @@ where #[cfg(feature = "a11y")] /// Sets the description of the [`Button`]. pub fn description(mut self, description: impl Into>) -> Self { - self.description = - Some(iced_accessibility::Description::Text(description.into())); + self.description = Some(iced_accessibility::Description::Text(description.into())); self } #[cfg(feature = "a11y")] /// Sets the label of the [`Button`]. pub fn label(mut self, label: &dyn iced_accessibility::Labels) -> Self { - self.label = - Some(label.label().into_iter().map(|l| l.into()).collect()); + self.label = Some(label.label().into_iter().map(|l| l.into()).collect()); self } } @@ -305,19 +295,11 @@ where renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { - layout::padded( - limits, - self.width, - self.height, - self.padding, - |limits| { - self.content.as_widget_mut().layout( - &mut tree.children[0], - renderer, - limits, - ) - }, - ) + layout::padded(limits, self.width, self.height, self.padding, |limits| { + self.content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + }) } fn operate( @@ -406,16 +388,10 @@ where } } #[cfg(feature = "a11y")] - Event::A11y( - event_id, - iced_accessibility::accesskit::ActionRequest { action, .. }, - ) => { + Event::A11y(event_id, iced_accessibility::accesskit::ActionRequest { action, .. }) => { let state = tree.state.downcast_mut::(); if let Some(Some(on_press)) = (self.id == *event_id - && matches!( - action, - iced_accessibility::accesskit::Action::Click - )) + && matches!(action, iced_accessibility::accesskit::Action::Click)) .then(|| self.on_press.as_ref()) { state.is_pressed = false; @@ -427,10 +403,7 @@ where if let Some(on_press) = self.on_press.as_ref() { let state = tree.state.downcast_mut::(); if state.is_focused - && matches!( - key, - keyboard::Key::Named(keyboard::key::Named::Enter) - ) + && matches!(key, keyboard::Key::Named(keyboard::key::Named::Enter)) { state.is_pressed = true; shell.publish(on_press.get()); @@ -485,13 +458,9 @@ where .next() .unwrap() .with_virtual_offset(layout.virtual_offset()); - let style = - theme.style(&self.class, self.status.unwrap_or(Status::Disabled)); + let style = theme.style(&self.class, self.status.unwrap_or(Status::Disabled)); - if style.background.is_some() - || style.border.width > 0.0 - || style.shadow.color.a > 0.0 - { + if style.background.is_some() || style.border.width > 0.0 || style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds, @@ -517,9 +486,7 @@ where theme, &renderer::Style { text_color: style.text_color, - icon_color: style - .icon_color - .unwrap_or(renderer_style.icon_color), + icon_color: style.icon_color.unwrap_or(renderer_style.icon_color), scale_factor: renderer_style.scale_factor, }, content_layout, @@ -593,12 +560,7 @@ where width, height, } = layout.bounds(); - let bounds = Rect::new( - x as f64, - y as f64, - (x + width) as f64, - (y + height) as f64, - ); + let bounds = Rect::new(x as f64, y as f64, (x + width) as f64, (y + height) as f64); let is_hovered = state.state.downcast_ref::().is_hovered; let mut node = Node::new(Role::Button); @@ -637,10 +599,7 @@ where // node.set_busy() // } - A11yTree::node_with_child_tree( - A11yNode::new(node, self.id.clone()), - child_tree, - ) + A11yTree::node_with_child_tree(A11yNode::new(node, self.id.clone()), child_tree) } fn id(&self) -> Option { @@ -934,9 +893,7 @@ pub fn background(theme: &Theme, status: Status) -> Style { match status { Status::Active => base, Status::Pressed => Style { - background: Some(Background::Color( - palette.background.strong.color, - )), + background: Some(Background::Color(palette.background.strong.color)), ..base }, Status::Hovered => Style { @@ -955,15 +912,11 @@ pub fn subtle(theme: &Theme, status: Status) -> Style { match status { Status::Active => base, Status::Pressed => Style { - background: Some(Background::Color( - palette.background.strong.color, - )), + background: Some(Background::Color(palette.background.strong.color)), ..base }, Status::Hovered => Style { - background: Some(Background::Color( - palette.background.weaker.color, - )), + background: Some(Background::Color(palette.background.weaker.color)), ..base }, Status::Disabled => disabled(base), diff --git a/widget/src/canvas.rs b/widget/src/canvas.rs index b1b6ac135c..69c7b545e1 100644 --- a/widget/src/canvas.rs +++ b/widget/src/canvas.rs @@ -56,8 +56,8 @@ pub use crate::Action; pub use crate::core::event::Event; pub use crate::graphics::cache::Group; pub use crate::graphics::geometry::{ - Fill, Gradient, Image, LineCap, LineDash, LineJoin, Path, Stroke, Style, - Text, fill, gradient, path, stroke, + Fill, Gradient, Image, LineCap, LineDash, LineJoin, Path, Stroke, Style, Text, fill, gradient, + path, stroke, }; use crate::core::event; @@ -66,9 +66,7 @@ use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::window; -use crate::core::{ - Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget, -}; +use crate::core::{Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget}; use crate::graphics::geometry; use std::marker::PhantomData; @@ -80,8 +78,7 @@ use std::marker::PhantomData; pub type Cache = geometry::Cache; /// The geometry supported by a renderer. -pub type Geometry = - ::Geometry; +pub type Geometry = ::Geometry; /// The frame supported by a renderer. pub type Frame = geometry::Frame; @@ -229,13 +226,10 @@ where let bounds = layout.bounds(); let state = tree.state.downcast_mut::(); - let is_redraw_request = matches!( - event, - Event::Window(window::Event::RedrawRequested(_now)), - ); + let is_redraw_request = + matches!(event, Event::Window(window::Event::RedrawRequested(_now)),); - if let Some(action) = self.program.update(state, event, bounds, cursor) - { + if let Some(action) = self.program.update(state, event, bounds, cursor) { let (message, redraw_request, event_status) = action.into_inner(); shell.request_redraw_at(redraw_request); @@ -250,16 +244,15 @@ where } if shell.redraw_request() != window::RedrawRequest::NextFrame { - let mouse_interaction = self - .mouse_interaction(tree, layout, cursor, viewport, renderer); + let mouse_interaction = + self.mouse_interaction(tree, layout, cursor, viewport, renderer); if is_redraw_request { self.last_mouse_interaction = Some(mouse_interaction); - } else if self.last_mouse_interaction.is_some_and( - |last_mouse_interaction| { - last_mouse_interaction != mouse_interaction - }, - ) { + } else if self + .last_mouse_interaction + .is_some_and(|last_mouse_interaction| last_mouse_interaction != mouse_interaction) + { shell.request_redraw(); } } @@ -297,17 +290,13 @@ where let state = tree.state.downcast_ref::(); - renderer.with_translation( - Vector::new(bounds.x, bounds.y), - |renderer| { - let layers = - self.program.draw(state, renderer, theme, bounds, cursor); - - for layer in layers { - renderer.draw_geometry(layer); - } - }, - ); + renderer.with_translation(Vector::new(bounds.x, bounds.y), |renderer| { + let layers = self.program.draw(state, renderer, theme, bounds, cursor); + + for layer in layers { + renderer.draw_geometry(layer); + } + }); } } @@ -319,9 +308,7 @@ where Renderer: 'a + geometry::Renderer, P: 'a + Program, { - fn from( - canvas: Canvas, - ) -> Element<'a, Message, Theme, Renderer> { + fn from(canvas: Canvas) -> Element<'a, Message, Theme, Renderer> { Element::new(canvas) } } diff --git a/widget/src/checkbox.rs b/widget/src/checkbox.rs index 873a454108..afb739fa4a 100644 --- a/widget/src/checkbox.rs +++ b/widget/src/checkbox.rs @@ -47,8 +47,8 @@ use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ - Background, Border, Clipboard, Color, Element, Event, Layout, Length, - Pixels, Rectangle, Shell, Size, Theme, Widget, id::Internal, + Background, Border, Clipboard, Color, Element, Event, Layout, Length, Pixels, Rectangle, Shell, + Size, Theme, Widget, id::Internal, }; /// A box that can be checked. @@ -84,12 +84,8 @@ use crate::core::{ /// } /// ``` /// ![Checkbox drawn by `iced_wgpu`](https://github.com/iced-rs/iced/blob/7760618fb112074bc40b148944521f312152012a/docs/images/checkbox.png?raw=true) -pub struct Checkbox< - 'a, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> where +pub struct Checkbox<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> +where Renderer: text::Renderer, Theme: Catalog, { @@ -217,10 +213,7 @@ where } /// Sets the text [`text::LineHeight`] of the [`Checkbox`]. - pub fn text_line_height( - mut self, - line_height: impl Into, - ) -> Self { + pub fn text_line_height(mut self, line_height: impl Into) -> Self { self.text_line_height = line_height.into(); self } @@ -278,10 +271,7 @@ where #[cfg(feature = "a11y")] /// Sets the description of the [`Checkbox`]. - pub fn description_widget( - mut self, - description: &T, - ) -> Self { + pub fn description_widget(mut self, description: &T) -> Self { self.description = Some(iced_accessibility::Description::Id( description.description(), )); @@ -291,8 +281,7 @@ where #[cfg(feature = "a11y")] /// Sets the description of the [`Checkbox`]. pub fn description(mut self, description: impl Into>) -> Self { - self.description = - Some(iced_accessibility::Description::Text(description.into())); + self.description = Some(iced_accessibility::Description::Text(description.into())); self } } @@ -335,8 +324,8 @@ where |limits| { if let Some(label) = self.label.as_deref() { let state = tree - .state - .downcast_mut::>(); + .state + .downcast_mut::>(); widget::text::layout( state, @@ -495,8 +484,7 @@ where { let label_layout = children.next().unwrap(); - let state: &widget::text::State = - tree.state.downcast_ref(); + let state: &widget::text::State = tree.state.downcast_ref(); crate::text::draw( renderer, @@ -544,12 +532,7 @@ where height, } = bounds; - let bounds = Rect::new( - x as f64, - y as f64, - (x + width) as f64, - (y + height) as f64, - ); + let bounds = Rect::new(x as f64, y as f64, (x + width) as f64, (y + height) as f64); let mut node = Node::new(Role::CheckBox); node.add_action(Action::Focus); diff --git a/widget/src/column.rs b/widget/src/column.rs index fe890b939e..5ec85df2fb 100644 --- a/widget/src/column.rs +++ b/widget/src/column.rs @@ -6,8 +6,8 @@ use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ - Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, - Shell, Size, Vector, Widget, + Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, + Widget, }; /// A container that distributes its contents vertically. @@ -32,8 +32,7 @@ use crate::core::{ /// ].into() /// } /// ``` -pub struct Column<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> -{ +pub struct Column<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { spacing: f32, padding: Padding, width: Length, @@ -74,9 +73,7 @@ where /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Column::width`] or [`Column::height`] accordingly. - pub fn from_vec( - children: Vec>, - ) -> Self { + pub fn from_vec(children: Vec>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, @@ -137,10 +134,7 @@ where } /// Adds an element to the [`Column`]. - pub fn push( - mut self, - child: impl Into>, - ) -> Self { + pub fn push(mut self, child: impl Into>) -> Self { let child = child.into(); let child_size = child.as_widget().size_hint(); @@ -195,14 +189,9 @@ where } impl<'a, Message, Theme, Renderer: crate::core::Renderer> - FromIterator> - for Column<'a, Message, Theme, Renderer> + FromIterator> for Column<'a, Message, Theme, Renderer> { - fn from_iter< - T: IntoIterator>, - >( - iter: T, - ) -> Self { + fn from_iter>>(iter: T) -> Self { Self::with_children(iter) } } @@ -449,12 +438,7 @@ where /// /// The original alignment of the [`Column`] is preserved per column wrapped. #[allow(missing_debug_implementations)] -pub struct Wrapping< - 'a, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> { +pub struct Wrapping<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { column: Column<'a, Message, Theme, Renderer>, horizontal_spacing: Option, align_y: alignment::Vertical, @@ -527,20 +511,15 @@ where for node in &mut children[column_start] { let width = node.size().width; - node.translate_mut(Vector::new( - (column_width - width) / align_factor, - 0.0, - )); + node.translate_mut(Vector::new((column_width - width) / align_factor, 0.0)); } } }; for (i, child) in self.column.children.iter_mut().enumerate() { - let node = child.as_widget_mut().layout( - &mut tree.children[i], - renderer, - &child_limits, - ); + let node = child + .as_widget_mut() + .layout(&mut tree.children[i], renderer, &child_limits); let child_size = node.size(); @@ -557,10 +536,8 @@ where column_width = column_width.max(child_size.width); - children.push(node.move_to(( - x + self.column.padding.left, - y + self.column.padding.top, - ))); + children + .push(node.move_to((x + self.column.padding.left, y + self.column.padding.top))); y += child_size.height + spacing; } @@ -593,10 +570,8 @@ where .unwrap_or_default(); if next_y == 0.0 { - let translation = Vector::new( - 0.0, - (total_height - column_height) / align_factor, - ); + let translation = + Vector::new(0.0, (total_height - column_height) / align_factor); for node in &mut children[column_start..=i] { node.translate_mut(translation); @@ -607,11 +582,7 @@ where } } - let size = limits.resolve( - self.column.width, - self.column.height, - intrinsic_size, - ); + let size = limits.resolve(self.column.width, self.column.height, intrinsic_size); layout::Node::with_children(size.expand(self.column.padding), children) } diff --git a/widget/src/combo_box.rs b/widget/src/combo_box.rs index a5bf361df2..e762a03154 100644 --- a/widget/src/combo_box.rs +++ b/widget/src/combo_box.rs @@ -64,8 +64,7 @@ use crate::core::text; use crate::core::time::Instant; use crate::core::widget::{self, Widget}; use crate::core::{ - Clipboard, Element, Event, Length, Padding, Pixels, Rectangle, Shell, Size, - Theme, Vector, + Clipboard, Element, Event, Length, Padding, Pixels, Rectangle, Shell, Size, Theme, Vector, }; use crate::overlay::menu; use crate::text::LineHeight; @@ -130,13 +129,8 @@ use std::fmt::Display; /// } /// } /// ``` -pub struct ComboBox< - 'a, - T, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> where +pub struct ComboBox<'a, T, Message, Theme = crate::Theme, Renderer = crate::Renderer> +where Theme: Catalog, Renderer: text::Renderer, { @@ -197,20 +191,14 @@ where /// Sets the message that should be produced when some text is typed into /// the [`TextInput`] of the [`ComboBox`]. - pub fn on_input( - mut self, - on_input: impl Fn(String) -> Message + 'static, - ) -> Self { + pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'static) -> Self { self.on_input = Some(Box::new(on_input)); self } /// Sets the message that will be produced when an option of the /// [`ComboBox`] is hovered using the arrow keys. - pub fn on_option_hovered( - mut self, - on_option_hovered: impl Fn(T) -> Message + 'static, - ) -> Self { + pub fn on_option_hovered(mut self, on_option_hovered: impl Fn(T) -> Message + 'static) -> Self { self.on_option_hovered = Some(Box::new(on_option_hovered)); self } @@ -296,8 +284,7 @@ where style: impl Fn(&Theme, text_input::Status) -> text_input::Style + 'a, ) -> Self where - ::Class<'a>: - From>, + ::Class<'a>: From>, { self.text_input = self.text_input.style(style); self @@ -305,10 +292,7 @@ where /// Sets the style of the menu of the [`ComboBox`]. #[must_use] - pub fn menu_style( - mut self, - style: impl Fn(&Theme) -> menu::Style + 'a, - ) -> Self + pub fn menu_style(mut self, style: impl Fn(&Theme) -> menu::Style + 'a) -> Self where ::Class<'a>: From>, { @@ -330,10 +314,7 @@ where /// Sets the style class of the menu of the [`ComboBox`]. #[cfg(feature = "advanced")] #[must_use] - pub fn menu_class( - mut self, - class: impl Into<::Class<'a>>, - ) -> Self { + pub fn menu_class(mut self, class: impl Into<::Class<'a>>) -> Self { self.menu_class = class.into(); self } @@ -613,13 +594,9 @@ where state.value = new_value; state.filtered_options.update( - search( - &self.state.options, - &state.option_matchers, - &state.value, - ) - .cloned() - .collect(), + search(&self.state.options, &state.option_matchers, &state.value) + .cloned() + .collect(), ); }); shell.invalidate_layout(); @@ -636,14 +613,10 @@ where if is_focused { self.state.with_inner(|state| { - if !started_focused - && let Some(on_option_hovered) = &mut self.on_option_hovered - { + if !started_focused && let Some(on_option_hovered) = &mut self.on_option_hovered { let hovered_option = menu.hovered_option.unwrap_or(0); - if let Some(option) = - state.filtered_options.options.get(hovered_option) - { + if let Some(option) = state.filtered_options.options.get(hovered_option) { shell.publish(on_option_hovered(option.clone())); published_message_to_shell = true; } @@ -659,8 +632,7 @@ where match (named_key, shift_modifier) { (key::Named::Enter, _) => { if let Some(index) = &menu.hovered_option - && let Some(option) = - state.filtered_options.options.get(*index) + && let Some(option) = state.filtered_options.options.get(*index) { menu.new_selection = Some(option.clone()); } @@ -671,11 +643,7 @@ where (key::Named::ArrowUp, _) | (key::Named::Tab, true) => { if let Some(index) = &mut menu.hovered_option { if *index == 0 { - *index = state - .filtered_options - .options - .len() - .saturating_sub(1); + *index = state.filtered_options.options.len().saturating_sub(1); } else { *index = index.saturating_sub(1); } @@ -683,66 +651,42 @@ where menu.hovered_option = Some(0); } - if let Some(on_option_hovered) = - &mut self.on_option_hovered - && let Some(option) = - menu.hovered_option.and_then(|index| { - state - .filtered_options - .options - .get(index) - }) + if let Some(on_option_hovered) = &mut self.on_option_hovered + && let Some(option) = menu + .hovered_option + .and_then(|index| state.filtered_options.options.get(index)) { // Notify the selection - shell.publish((on_option_hovered)( - option.clone(), - )); + shell.publish((on_option_hovered)(option.clone())); published_message_to_shell = true; } shell.capture_event(); shell.request_redraw(); } - (key::Named::ArrowDown, _) - | (key::Named::Tab, false) + (key::Named::ArrowDown, _) | (key::Named::Tab, false) if !modifiers.shift() => { if let Some(index) = &mut menu.hovered_option { - if *index - >= state - .filtered_options - .options - .len() - .saturating_sub(1) + if *index >= state.filtered_options.options.len().saturating_sub(1) { *index = 0; } else { *index = index.saturating_add(1).min( - state - .filtered_options - .options - .len() - .saturating_sub(1), + state.filtered_options.options.len().saturating_sub(1), ); } } else { menu.hovered_option = Some(0); } - if let Some(on_option_hovered) = - &mut self.on_option_hovered - && let Some(option) = - menu.hovered_option.and_then(|index| { - state - .filtered_options - .options - .get(index) - }) + if let Some(on_option_hovered) = &mut self.on_option_hovered + && let Some(option) = menu + .hovered_option + .and_then(|index| state.filtered_options.options.get(index)) { // Notify the selection - shell.publish((on_option_hovered)( - option.clone(), - )); + shell.publish((on_option_hovered)(option.clone())); published_message_to_shell = true; } @@ -772,9 +716,7 @@ where let mut local_shell = Shell::new(&mut local_messages); self.text_input.update( &mut tree.children[0], - &Event::Mouse(mouse::Event::ButtonPressed( - mouse::Button::Left, - )), + &Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)), layout, mouse::Cursor::Unavailable, renderer, @@ -818,13 +760,8 @@ where viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { - self.text_input.mouse_interaction( - &tree.children[0], - layout, - cursor, - viewport, - renderer, - ) + self.text_input + .mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer) } fn draw( @@ -938,8 +875,7 @@ where } } -impl<'a, T, Message, Theme, Renderer> - From> +impl<'a, T, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where T: Display + Clone + 'static, @@ -995,9 +931,7 @@ where }) } -fn build_matchers<'a, T>( - options: impl IntoIterator + 'a, -) -> Vec +fn build_matchers<'a, T>(options: impl IntoIterator + 'a) -> Vec where T: Display + 'a, { diff --git a/widget/src/container.rs b/widget/src/container.rs index c9a300c90f..344c6bd459 100644 --- a/widget/src/container.rs +++ b/widget/src/container.rs @@ -30,9 +30,8 @@ use crate::core::theme; use crate::core::widget::tree::{self, Tree}; use crate::core::widget::{self, Id, Operation}; use crate::core::{ - self, Background, Clipboard, Color, Element, Event, Layout, Length, - Padding, Pixels, Rectangle, Shadow, Shell, Size, Theme, Vector, Widget, - color, + self, Background, Clipboard, Color, Element, Event, Layout, Length, Padding, Pixels, Rectangle, + Shadow, Shell, Size, Theme, Vector, Widget, color, }; use iced_runtime::{Action, Task, task}; @@ -58,12 +57,8 @@ use iced_runtime::{Action, Task, task}; /// .into() /// } /// ``` -pub struct Container< - 'a, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> where +pub struct Container<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> +where Theme: Catalog, Renderer: core::Renderer, { @@ -86,9 +81,7 @@ where Renderer: core::Renderer, { /// Creates a [`Container`] with the given content. - pub fn new( - content: impl Into>, - ) -> Self { + pub fn new(content: impl Into>) -> Self { let content = content.into(); let size = content.as_widget().size_hint(); @@ -187,19 +180,13 @@ where } /// Sets the content alignment for the horizontal axis of the [`Container`]. - pub fn align_x( - mut self, - alignment: impl Into, - ) -> Self { + pub fn align_x(mut self, alignment: impl Into) -> Self { self.horizontal_alignment = alignment.into(); self } /// Sets the content alignment for the vertical axis of the [`Container`]. - pub fn align_y( - mut self, - alignment: impl Into, - ) -> Self { + pub fn align_y(mut self, alignment: impl Into) -> Self { self.vertical_alignment = alignment.into(); self } @@ -273,9 +260,7 @@ where self.padding, self.horizontal_alignment, self.vertical_alignment, - |limits| { - self.content.as_widget_mut().layout(tree, renderer, limits) - }, + |limits| self.content.as_widget_mut().layout(tree, renderer, limits), ) } @@ -370,12 +355,8 @@ where renderer, theme, &renderer::Style { - icon_color: style - .icon_color - .unwrap_or(renderer_style.icon_color), - text_color: style - .text_color - .unwrap_or(renderer_style.text_color), + icon_color: style.icon_color.unwrap_or(renderer_style.icon_color), + text_color: style.text_color.unwrap_or(renderer_style.text_color), scale_factor: renderer_style.scale_factor, }, layout @@ -500,17 +481,11 @@ pub fn layout( } /// Draws the background of a [`Container`] given its [`Style`] and its `bounds`. -pub fn draw_background( - renderer: &mut Renderer, - style: &Style, - bounds: Rectangle, -) where +pub fn draw_background(renderer: &mut Renderer, style: &Style, bounds: Rectangle) +where Renderer: core::Renderer, { - if style.background.is_some() - || style.border.width > 0.0 - || style.shadow.color.a > 0.0 - { + if style.background.is_some() || style.border.width > 0.0 || style.shadow.color.a > 0.0 { renderer.fill_quad( renderer::Quad { bounds, @@ -548,16 +523,10 @@ pub fn visible_bounds(id: Id) -> Task> { Some((last_translation, last_viewport, _depth)) => { let viewport = last_viewport .intersection(&(bounds - *last_translation)) - .unwrap_or(Rectangle::new( - crate::core::Point::ORIGIN, - Size::ZERO, - )); - - self.scrollables.push(( - translation + *last_translation, - viewport, - self.depth, - )); + .unwrap_or(Rectangle::new(crate::core::Point::ORIGIN, Size::ZERO)); + + self.scrollables + .push((translation + *last_translation, viewport, self.depth)); } None => { self.scrollables.push((translation, bounds, self.depth)); @@ -573,8 +542,7 @@ pub fn visible_bounds(id: Id) -> Task> { if id == Some(&self.target) { match self.scrollables.last() { Some((translation, viewport, _)) => { - self.bounds = - viewport.intersection(&(bounds - *translation)); + self.bounds = viewport.intersection(&(bounds - *translation)); } None => { self.bounds = Some(bounds); @@ -596,10 +564,7 @@ pub fn visible_bounds(id: Id) -> Task> { } } - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation>), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation>)) { self.depth += 1; self.traverse(operate); self.depth -= 1; diff --git a/widget/src/float.rs b/widget/src/float.rs index 27bd8aad2e..2ba78c629a 100644 --- a/widget/src/float.rs +++ b/widget/src/float.rs @@ -8,8 +8,8 @@ use crate::core::renderer; use crate::core::widget; use crate::core::widget::tree; use crate::core::{ - Clipboard, Element, Event, Layout, Length, Rectangle, Shadow, Shell, Size, - Transformation, Vector, Widget, + Clipboard, Element, Event, Layout, Length, Rectangle, Shadow, Shell, Size, Transformation, + Vector, Widget, }; /// A widget that can make its contents float over other widgets. @@ -28,9 +28,7 @@ where Theme: Catalog, { /// Creates a new [`Float`] widget with the given content. - pub fn new( - content: impl Into>, - ) -> Self { + pub fn new(content: impl Into>) -> Self { Self { content: content.into(), scale: 1.0, @@ -50,10 +48,7 @@ where /// The logic takes the original (non-scaled) bounds of the contents and the /// viewport bounds. These bounds can be useful to ensure the floating elements /// always stay on screen. - pub fn translate( - mut self, - translate: impl Fn(Rectangle, Rectangle) -> Vector + 'a, - ) -> Self { + pub fn translate(mut self, translate: impl Fn(Rectangle, Rectangle) -> Vector + 'a) -> Self { self.translate = Some(Box::new(translate)); self } @@ -78,9 +73,10 @@ where fn is_floating(&self, bounds: Rectangle, viewport: Rectangle) -> bool { self.scale > 1.0 - || self.translate.as_ref().is_some_and(|translate| { - translate(bounds, viewport) != Vector::ZERO - }) + || self + .translate + .as_ref() + .is_some_and(|translate| translate(bounds, viewport) != Vector::ZERO) } } @@ -346,9 +342,7 @@ where renderer::Quad { bounds: bounds.shrink(1.0), shadow: style.shadow, - border: border::rounded( - style.shadow_border_radius, - ), + border: border::rounded(style.shadow_border_radius), snap: false, }, style.shadow.color, diff --git a/widget/src/grid.rs b/widget/src/grid.rs index a083b6c22d..b0c15ed57c 100644 --- a/widget/src/grid.rs +++ b/widget/src/grid.rs @@ -5,8 +5,7 @@ use crate::core::overlay; use crate::core::renderer; use crate::core::widget::{Operation, Tree}; use crate::core::{ - Clipboard, Element, Event, Length, Pixels, Rectangle, Shell, Size, Vector, - Widget, + Clipboard, Element, Event, Length, Pixels, Rectangle, Shell, Size, Vector, Widget, }; /// A container that distributes its contents on a responsive grid. @@ -47,9 +46,7 @@ where } /// Creates a [`Grid`] from an already allocated [`Vec`]. - pub fn from_vec( - children: Vec>, - ) -> Self { + pub fn from_vec(children: Vec>) -> Self { Self { spacing: 0.0, columns: Constraint::Amount(3), @@ -97,10 +94,7 @@ where } /// Adds an [`Element`] to the [`Grid`]. - pub fn push( - mut self, - child: impl Into>, - ) -> Self { + pub fn push(mut self, child: impl Into>) -> Self { self.children.push(child.into()); self } @@ -136,14 +130,9 @@ where } impl<'a, Message, Theme, Renderer: crate::core::Renderer> - FromIterator> - for Grid<'a, Message, Theme, Renderer> + FromIterator> for Grid<'a, Message, Theme, Renderer> { - fn from_iter< - T: IntoIterator>, - >( - iter: T, - ) -> Self { + fn from_iter>>(iter: T) -> Self { Self::with_children(iter) } } @@ -186,23 +175,18 @@ where let cells_per_row = match self.columns { // width = n * (cell + spacing) - spacing, given n > 0 - Constraint::MaxWidth(pixels) => ((available.width + self.spacing) - / (pixels.0 + self.spacing)) - .ceil() as usize, + Constraint::MaxWidth(pixels) => { + ((available.width + self.spacing) / (pixels.0 + self.spacing)).ceil() as usize + } Constraint::Amount(amount) => amount, }; if self.children.is_empty() || cells_per_row == 0 { - return layout::Node::new(limits.resolve( - size.width, - size.height, - Size::ZERO, - )); + return layout::Node::new(limits.resolve(size.width, size.height, Size::ZERO)); } - let cell_width = (available.width - - self.spacing * (cells_per_row - 1) as f32) - / cells_per_row as f32; + let cell_width = + (available.width - self.spacing * (cells_per_row - 1) as f32) / cells_per_row as f32; let cell_height = match self.height { Sizing::AspectRatio(ratio) => Some(cell_width / ratio), @@ -210,8 +194,7 @@ where Sizing::EvenlyDistribute(_) => { let total_rows = self.children.len().div_ceil(cells_per_row); Some( - (available.height - self.spacing * (total_rows - 1) as f32) - / total_rows as f32, + (available.height - self.spacing * (total_rows - 1) as f32) / total_rows as f32, ) } }; @@ -226,9 +209,7 @@ where let mut y = 0.0; let mut row_height = 0.0f32; - for (i, (child, tree)) in - self.children.iter_mut().zip(&mut tree.children).enumerate() - { + for (i, (child, tree)) in self.children.iter_mut().zip(&mut tree.children).enumerate() { let node = child .as_widget_mut() .layout(tree, renderer, &cell_limits) @@ -296,8 +277,7 @@ where .zip(layout.children()) { child.as_widget_mut().update( - tree, event, layout, cursor, renderer, clipboard, shell, - viewport, + tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); } } @@ -341,9 +321,9 @@ where .zip(layout.children()) .filter(|(_, layout)| layout.bounds().intersects(&viewport)) { - child.as_widget().draw( - tree, renderer, theme, style, layout, cursor, &viewport, - ); + child + .as_widget() + .draw(tree, renderer, theme, style, layout, cursor, &viewport); } } } @@ -407,9 +387,6 @@ impl From for Sizing { } /// Creates a new [`Sizing`] strategy that maintains the given aspect ratio. -pub fn aspect_ratio( - width: impl Into, - height: impl Into, -) -> Sizing { +pub fn aspect_ratio(width: impl Into, height: impl Into) -> Sizing { Sizing::AspectRatio(width.into().0 / height.into().0) } diff --git a/widget/src/helpers.rs b/widget/src/helpers.rs index 1cad36d9e0..5744f6866f 100644 --- a/widget/src/helpers.rs +++ b/widget/src/helpers.rs @@ -24,9 +24,7 @@ use crate::text_input::{self, TextInput}; use crate::toggler::{self, Toggler}; use crate::tooltip::{self, Tooltip}; use crate::vertical_slider::{self, VerticalSlider}; -use crate::{ - Column, Grid, MouseArea, Pin, Responsive, Row, Sensor, Space, Stack, Themer, -}; +use crate::{Column, Grid, MouseArea, Pin, Responsive, Row, Sensor, Space, Stack, Themer}; use std::borrow::Borrow; @@ -670,14 +668,11 @@ where shell: &mut Shell<'_, Message>, viewport: &Rectangle, ) { - let is_mouse_press = matches!( - event, - core::Event::Mouse(mouse::Event::ButtonPressed(_)) - ); + let is_mouse_press = + matches!(event, core::Event::Mouse(mouse::Event::ButtonPressed(_))); self.content.as_widget_mut().update( - tree, event, layout, cursor, renderer, clipboard, shell, - viewport, + tree, event, layout, cursor, renderer, clipboard, shell, viewport, ); if is_mouse_press && cursor.is_over(layout.bounds()) { @@ -698,9 +693,7 @@ where .as_widget() .mouse_interaction(state, layout, cursor, viewport, renderer); - if interaction == mouse::Interaction::None - && cursor.is_over(layout.bounds()) - { + if interaction == mouse::Interaction::None && cursor.is_over(layout.bounds()) { mouse::Interaction::Idle } else { interaction @@ -714,15 +707,10 @@ where renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, - ) -> Option> - { - self.content.as_widget_mut().overlay( - state, - layout, - renderer, - viewport, - translation, - ) + ) -> Option> { + self.content + .as_widget_mut() + .overlay(state, layout, renderer, viewport, translation) } } @@ -792,11 +780,10 @@ where renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { - let base = self.base.as_widget_mut().layout( - &mut tree.children[0], - renderer, - limits, - ); + let base = self + .base + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits); let top = self.top.as_widget_mut().layout( &mut tree.children[1], @@ -840,8 +827,7 @@ where renderer.with_layer(bounds, |renderer| { self.top.as_widget().draw( - top_tree, renderer, theme, style, top_layout, - cursor, viewport, + top_tree, renderer, theme, style, top_layout, cursor, viewport, ); }); } @@ -883,8 +869,7 @@ where let is_hovered = cursor.is_over(layout.bounds()); - if matches!(event, Event::Window(window::Event::RedrawRequested(_))) - { + if matches!(event, Event::Window(window::Event::RedrawRequested(_))) { let mut count_focused = operation::focusable::count(); self.top.as_widget_mut().operate( @@ -904,22 +889,17 @@ where shell.request_redraw(); } - let is_visible = - is_hovered || self.is_top_focused || self.is_top_overlay_active; + let is_visible = is_hovered || self.is_top_focused || self.is_top_overlay_active; if matches!( event, - Event::Mouse( - mouse::Event::CursorMoved { .. } - | mouse::Event::ButtonReleased(_) - ) + Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::ButtonReleased(_)) ) || is_visible { let redraw_request = shell.redraw_request(); self.top.as_widget_mut().update( - top_tree, event, top_layout, cursor, renderer, clipboard, - shell, viewport, + top_tree, event, top_layout, cursor, renderer, clipboard, shell, viewport, ); // Ignore redraw requests of invisible content @@ -957,9 +937,9 @@ where .rev() .zip(layout.children().rev().zip(tree.children.iter().rev())) .map(|(child, (layout, tree))| { - child.as_widget().mouse_interaction( - tree, layout, cursor, viewport, renderer, - ) + child + .as_widget() + .mouse_interaction(tree, layout, cursor, viewport, renderer) }) .find(|&interaction| interaction != mouse::Interaction::None) .unwrap_or_default() @@ -972,19 +952,14 @@ where renderer: &Renderer, viewport: &Rectangle, translation: core::Vector, - ) -> Option> - { + ) -> Option> { let mut overlays = [&mut self.base, &mut self.top] .into_iter() .zip(layout.children().zip(tree.children.iter_mut())) .map(|(child, (layout, tree))| { - child.as_widget_mut().overlay( - tree, - layout, - renderer, - viewport, - translation, - ) + child + .as_widget_mut() + .overlay(tree, layout, renderer, viewport, translation) }); if let Some(base_overlay) = overlays.next()? { @@ -1154,9 +1129,7 @@ where /// .into() /// } /// ``` -pub fn text<'a, Theme, Renderer>( - text: impl text::IntoFragment<'a>, -) -> Text<'a, Theme, Renderer> +pub fn text<'a, Theme, Renderer>(text: impl text::IntoFragment<'a>) -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: core::text::Renderer, @@ -1165,9 +1138,7 @@ where } /// Creates a new [`Text`] widget that displays the provided value. -pub fn value<'a, Theme, Renderer>( - value: impl ToString, -) -> Text<'a, Theme, Renderer> +pub fn value<'a, Theme, Renderer>(value: impl ToString) -> Text<'a, Theme, Renderer> where Theme: text::Catalog + 'a, Renderer: core::text::Renderer, @@ -1249,9 +1220,7 @@ where /// .into() /// } /// ``` -pub fn span<'a, Link, Font>( - text: impl text::IntoFragment<'a>, -) -> text::Span<'a, Link, Font> { +pub fn span<'a, Link, Font>(text: impl text::IntoFragment<'a>) -> text::Span<'a, Link, Font> { text::Span::new(text) } @@ -1790,10 +1759,7 @@ pub fn space() -> Space { /// progress_bar(0.0..=100.0, state.progress).into() /// } /// ``` -pub fn progress_bar<'a, Theme>( - range: RangeInclusive, - value: f32, -) -> ProgressBar<'a, Theme> +pub fn progress_bar<'a, Theme>(range: RangeInclusive, value: f32) -> ProgressBar<'a, Theme> where Theme: progress_bar::Catalog + 'a, { @@ -1824,9 +1790,7 @@ where /// #[cfg(feature = "image")] #[cfg_attr(docsrs, doc(cfg(feature = "image")))] -pub fn image<'a, Handle>( - handle: impl Into, -) -> crate::Image<'a, Handle> { +pub fn image<'a, Handle>(handle: impl Into) -> crate::Image<'a, Handle> { crate::Image::new(handle.into()) } @@ -1853,9 +1817,7 @@ pub fn image<'a, Handle>( /// } /// ``` #[cfg(feature = "svg")] -pub fn svg<'a, Theme>( - handle: impl Into, -) -> crate::Svg<'a, Theme> +pub fn svg<'a, Theme>(handle: impl Into) -> crate::Svg<'a, Theme> where Theme: crate::svg::Catalog, { @@ -1873,8 +1835,7 @@ where Message: 'a, Renderer: core::Renderer + core::text::Renderer + 'a, Theme: text::Catalog + container::Catalog + 'a, - ::Class<'a>: - From>, + ::Class<'a>: From>, ::Class<'a>: From>, { use crate::core::border; @@ -1965,9 +1926,7 @@ where /// } /// ``` #[cfg(feature = "canvas")] -pub fn canvas( - program: P, -) -> crate::Canvas +pub fn canvas(program: P) -> crate::Canvas where Renderer: crate::graphics::geometry::Renderer, P: crate::canvas::Program, @@ -2003,9 +1962,7 @@ where /// } /// ``` #[cfg(feature = "qr_code")] -pub fn qr_code<'a, Theme>( - data: &'a crate::qr_code::Data, -) -> crate::QRCode<'a, Theme> +pub fn qr_code<'a, Theme>(data: &'a crate::qr_code::Data) -> crate::QRCode<'a, Theme> where Theme: crate::qr_code::Catalog + 'a, { @@ -2084,11 +2041,7 @@ where /// ``` pub fn pane_grid<'a, T, Message, Theme, Renderer>( state: &'a pane_grid::State, - view: impl Fn( - pane_grid::Pane, - &'a T, - bool, - ) -> pane_grid::Content<'a, Message, Theme, Renderer>, + view: impl Fn(pane_grid::Pane, &'a T, bool) -> pane_grid::Content<'a, Message, Theme, Renderer>, ) -> PaneGrid<'a, Message, Theme, Renderer> where Theme: pane_grid::Catalog, diff --git a/widget/src/image.rs b/widget/src/image.rs index 4315709a8e..99f831e958 100644 --- a/widget/src/image.rs +++ b/widget/src/image.rs @@ -27,8 +27,7 @@ use crate::core::mouse; use crate::core::renderer; use crate::core::widget::Tree; use crate::core::{ - ContentFit, Element, Layout, Length, Point, Rectangle, Rotation, Size, - Vector, Widget, + ContentFit, Element, Layout, Length, Point, Rectangle, Rotation, Size, Vector, Widget, }; pub use image::{FilterMethod, Handle}; @@ -193,10 +192,7 @@ impl<'a, Handle> Image<'a, Handle> { /// /// Currently, it will only be applied around the rectangular bounding box /// of the [`Image`]. - pub fn border_radius( - mut self, - border_radius: impl Into, - ) -> Self { + pub fn border_radius(mut self, border_radius: impl Into) -> Self { self.border_radius = border_radius.into(); self } @@ -210,10 +206,7 @@ impl<'a, Handle> Image<'a, Handle> { #[cfg(feature = "a11y")] /// Sets the description of the [`Image`]. - pub fn description_widget( - mut self, - description: &T, - ) -> Self { + pub fn description_widget(mut self, description: &T) -> Self { self.description = Some(iced_accessibility::Description::Id( description.description(), )); @@ -223,16 +216,14 @@ impl<'a, Handle> Image<'a, Handle> { #[cfg(feature = "a11y")] /// Sets the description of the [`Image`]. pub fn description(mut self, description: impl Into>) -> Self { - self.description = - Some(iced_accessibility::Description::Text(description.into())); + self.description = Some(iced_accessibility::Description::Text(description.into())); self } #[cfg(feature = "a11y")] /// Sets the label of the [`Image`]. pub fn label(mut self, label: &dyn iced_accessibility::Labels) -> Self { - self.label = - Some(label.label().into_iter().map(|l| l.into()).collect()); + self.label = Some(label.label().into_iter().map(|l| l.into()).collect()); self } } @@ -254,8 +245,7 @@ where Renderer: image::Renderer, { // The raw w/h of the underlying image - let image_size = - crop(renderer.measure_image(handle).unwrap_or_default(), region); + let image_size = crop(renderer.measure_image(handle).unwrap_or_default(), region); // The rotated size of the image let rotated_size = rotation.apply(image_size); @@ -410,8 +400,7 @@ pub fn draw( ); } -impl<'a, Message, Theme, Renderer, Handle> Widget - for Image<'a, Handle> +impl<'a, Message, Theme, Renderer, Handle> Widget for Image<'a, Handle> where Renderer: image::Renderer, Handle: Clone, @@ -486,12 +475,7 @@ where width, height, } = bounds; - let bounds = Rect::new( - x as f64, - y as f64, - (x + width) as f64, - (y + height) as f64, - ); + let bounds = Rect::new(x as f64, y as f64, (x + width) as f64, (y + height) as f64); let mut node = Node::new(Role::Image); node.set_bounds(bounds); if let Some(name) = self.name.as_ref() { diff --git a/widget/src/image/viewer.rs b/widget/src/image/viewer.rs index 514cd8b65f..cfa3bd68da 100644 --- a/widget/src/image/viewer.rs +++ b/widget/src/image/viewer.rs @@ -6,8 +6,8 @@ use crate::core::mouse; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::{ - Clipboard, ContentFit, Element, Event, Image, Layout, Length, Pixels, - Point, Radians, Rectangle, Shell, Size, Vector, Widget, + Clipboard, ContentFit, Element, Event, Image, Layout, Length, Pixels, Point, Radians, + Rectangle, Shell, Size, Vector, Widget, }; /// A frame that displays an image with the ability to zoom in/out and pan. @@ -95,8 +95,7 @@ impl Viewer { } } -impl Widget - for Viewer +impl Widget for Viewer where Renderer: image::Renderer, Handle: Clone, @@ -123,11 +122,9 @@ where limits: &layout::Limits, ) -> layout::Node { // The raw w/h of the underlying image - let image_size = - renderer.measure_image(&self.handle).unwrap_or_default(); + let image_size = renderer.measure_image(&self.handle).unwrap_or_default(); - let image_size = - Size::new(image_size.width as f32, image_size.height as f32); + let image_size = Size::new(image_size.width as f32, image_size.height as f32); // The size to be available to the widget prior to `Shrink`ing let raw_size = limits.resolve(self.width, self.height, image_size); @@ -170,8 +167,7 @@ where }; match *delta { - mouse::ScrollDelta::Lines { y, .. } - | mouse::ScrollDelta::Pixels { y, .. } => { + mouse::ScrollDelta::Lines { y, .. } | mouse::ScrollDelta::Pixels { y, .. } => { let state = tree.state.downcast_mut::(); let previous_scale = state.scale; @@ -195,11 +191,10 @@ where let factor = state.scale / previous_scale - 1.0; - let cursor_to_center = - cursor_position - bounds.center(); + let cursor_to_center = cursor_position - bounds.center(); - let adjustment = cursor_to_center * factor - + state.current_offset * factor; + let adjustment = + cursor_to_center * factor + state.current_offset * factor; state.current_offset = Vector::new( if scaled_size.width > bounds.width { @@ -248,27 +243,20 @@ where bounds.size(), self.content_fit, ); - let hidden_width = (scaled_size.width - bounds.width / 2.0) - .max(0.0) - .round(); + let hidden_width = (scaled_size.width - bounds.width / 2.0).max(0.0).round(); - let hidden_height = (scaled_size.height - - bounds.height / 2.0) - .max(0.0) - .round(); + let hidden_height = (scaled_size.height - bounds.height / 2.0).max(0.0).round(); let delta = *position - origin; let x = if bounds.width < scaled_size.width { - (state.starting_offset.x - delta.x) - .clamp(-hidden_width, hidden_width) + (state.starting_offset.x - delta.x).clamp(-hidden_width, hidden_width) } else { 0.0 }; let y = if bounds.height < scaled_size.height { - (state.starting_offset.y - delta.y) - .clamp(-hidden_height, hidden_height) + (state.starting_offset.y - delta.y).clamp(-hidden_height, hidden_height) } else { 0.0 }; @@ -329,9 +317,7 @@ where let diff_h = bounds.height - final_size.height; let image_top_left = match self.content_fit { - ContentFit::None => { - Vector::new(diff_w.max(0.0) / 2.0, diff_h.max(0.0) / 2.0) - } + ContentFit::None => Vector::new(diff_w.max(0.0) / 2.0, diff_h.max(0.0) / 2.0), _ => Vector::new(diff_w / 2.0, diff_h / 2.0), }; @@ -390,11 +376,9 @@ impl State { /// Returns the current offset of the [`State`], given the bounds /// of the [`Viewer`] and its image. fn offset(&self, bounds: Rectangle, image_size: Size) -> Vector { - let hidden_width = - (image_size.width - bounds.width / 2.0).max(0.0).round(); + let hidden_width = (image_size.width - bounds.width / 2.0).max(0.0).round(); - let hidden_height = - (image_size.height - bounds.height / 2.0).max(0.0).round(); + let hidden_height = (image_size.height - bounds.height / 2.0).max(0.0).round(); Vector::new( self.current_offset.x.clamp(-hidden_width, hidden_width), @@ -433,8 +417,7 @@ pub fn scaled_image_size( where Renderer: image::Renderer, { - let Size { width, height } = - renderer.measure_image(handle).unwrap_or_default(); + let Size { width, height } = renderer.measure_image(handle).unwrap_or_default(); let image_size = Size::new(width as f32, height as f32); diff --git a/widget/src/keyed/column.rs b/widget/src/keyed/column.rs index baaee5c987..c1f13ff5a4 100644 --- a/widget/src/keyed/column.rs +++ b/widget/src/keyed/column.rs @@ -9,8 +9,8 @@ use crate::core::renderer; use crate::core::widget::Operation; use crate::core::widget::tree::{self, Tree}; use crate::core::{ - Alignment, Clipboard, Element, Event, Layout, Length, Padding, Pixels, - Rectangle, Shell, Size, Vector, Widget, + Alignment, Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, + Vector, Widget, }; /// A container that distributes its contents vertically while keeping continuity. @@ -32,13 +32,8 @@ use crate::core::{ /// })).into() /// } /// ``` -pub struct Column< - 'a, - Key, - Message, - Theme = crate::Theme, - Renderer = crate::Renderer, -> where +pub struct Column<'a, Key, Message, Theme = crate::Theme, Renderer = crate::Renderer> +where Key: Copy + PartialEq, { spacing: f32, @@ -51,8 +46,7 @@ pub struct Column< children: Vec>, } -impl<'a, Key, Message, Theme, Renderer> - Column<'a, Key, Message, Theme, Renderer> +impl<'a, Key, Message, Theme, Renderer> Column<'a, Key, Message, Theme, Renderer> where Key: Copy + PartialEq, Renderer: crate::core::Renderer, @@ -69,10 +63,7 @@ where /// /// If any of the children have a [`Length::Fill`] strategy, you will need to /// call [`Column::width`] or [`Column::height`] accordingly. - pub fn from_vecs( - keys: Vec, - children: Vec>, - ) -> Self { + pub fn from_vecs(keys: Vec, children: Vec>) -> Self { Self { spacing: 0.0, padding: Padding::ZERO, @@ -87,17 +78,12 @@ where /// Creates a [`Column`] with the given capacity. pub fn with_capacity(capacity: usize) -> Self { - Self::from_vecs( - Vec::with_capacity(capacity), - Vec::with_capacity(capacity), - ) + Self::from_vecs(Vec::with_capacity(capacity), Vec::with_capacity(capacity)) } /// Creates a [`Column`] with the given elements. pub fn with_children( - children: impl IntoIterator< - Item = (Key, Element<'a, Message, Theme, Renderer>), - >, + children: impl IntoIterator)>, ) -> Self { let iterator = children.into_iter(); @@ -177,9 +163,7 @@ where /// Extends the [`Column`] with the given children. pub fn extend( self, - children: impl IntoIterator< - Item = (Key, Element<'a, Message, Theme, Renderer>), - >, + children: impl IntoIterator)>, ) -> Self { children .into_iter() @@ -293,9 +277,12 @@ where .zip(&mut tree.children) .zip(layout.children()) .for_each(|((child, state), c_layout)| { - child - .as_widget_mut() - .operate(state, c_layout.with_virtual_offset(layout.virtual_offset()), renderer, operation); + child.as_widget_mut().operate( + state, + c_layout.with_virtual_offset(layout.virtual_offset()), + renderer, + operation, + ); }); }); } @@ -318,7 +305,13 @@ where .zip(layout.children()) { child.as_widget_mut().update( - tree, event, c_layout.with_virtual_offset(layout.virtual_offset()), cursor, renderer, clipboard, shell, + tree, + event, + c_layout.with_virtual_offset(layout.virtual_offset()), + cursor, + renderer, + clipboard, + shell, viewport, ); } @@ -337,9 +330,13 @@ where .zip(&tree.children) .zip(layout.children()) .map(|((child, tree), c_layout)| { - child - .as_widget() - .mouse_interaction(tree, c_layout.with_virtual_offset(layout.virtual_offset()), cursor, viewport, renderer) + child.as_widget().mouse_interaction( + tree, + c_layout.with_virtual_offset(layout.virtual_offset()), + cursor, + viewport, + renderer, + ) }) .max() .unwrap_or_default() @@ -392,8 +389,7 @@ where } } -impl<'a, Key, Message, Theme, Renderer> - From> +impl<'a, Key, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where Key: Copy + PartialEq + 'static, diff --git a/widget/src/lazy.rs b/widget/src/lazy.rs index 7a1f85065c..cf5d4e3094 100644 --- a/widget/src/lazy.rs +++ b/widget/src/lazy.rs @@ -16,9 +16,7 @@ use crate::core::overlay; use crate::core::renderer; use crate::core::widget::tree::{self, Tree}; use crate::core::widget::{self, Widget}; -use crate::core::{ - self, Clipboard, Event, Length, Rectangle, Shell, Size, Vector, -}; +use crate::core::{self, Clipboard, Event, Length, Rectangle, Shell, Size, Vector}; use ouroboros::self_referencing; use rustc_hash::FxHasher; @@ -31,9 +29,7 @@ use std::rc::Rc; pub struct Lazy<'a, Message, Theme, Renderer, Dependency, View> { dependency: Dependency, view: Box View + 'a>, - element: RefCell< - Option>>>>, - >, + element: RefCell>>>>>, } impl<'a, Message, Theme, Renderer, Dependency, View> @@ -44,10 +40,7 @@ where { /// Creates a new [`Lazy`] widget with the given data `Dependency` and a /// closure that can turn this data into a widget tree. - pub fn new( - dependency: Dependency, - view: impl Fn(&Dependency) -> View + 'a, - ) -> Self { + pub fn new(dependency: Dependency, view: impl Fn(&Dependency) -> View + 'a) -> Self { Self { dependency, view: Box::new(view), @@ -55,10 +48,7 @@ where } } - fn with_element( - &self, - f: impl FnOnce(&Element<'_, Message, Theme, Renderer>) -> T, - ) -> T { + fn with_element(&self, f: impl FnOnce(&Element<'_, Message, Theme, Renderer>) -> T) -> T { f(self .element .borrow() @@ -89,8 +79,7 @@ struct Internal { hash: u64, } -impl<'a, Message, Theme, Renderer, Dependency, View> - Widget +impl<'a, Message, Theme, Renderer, Dependency, View> Widget for Lazy<'a, Message, Theme, Renderer, Dependency, View> where View: Into> + 'static, @@ -112,8 +101,7 @@ where hasher.finish() }; - let element = - Rc::new(RefCell::new(Some((self.view)(&self.dependency).into()))); + let element = Rc::new(RefCell::new(Some((self.view)(&self.dependency).into()))); (*self.element.borrow_mut()) = Some(element.clone()); @@ -144,9 +132,7 @@ where (*self.element.borrow_mut()) = Some(current.element.clone()); self.with_element_mut(|element| { - tree.diff_children(std::slice::from_mut( - &mut element.as_widget_mut(), - )) + tree.diff_children(std::slice::from_mut(&mut element.as_widget_mut())) }); } else { (*self.element.borrow_mut()) = Some(current.element.clone()); @@ -171,11 +157,9 @@ where limits: &layout::Limits, ) -> layout::Node { self.with_element_mut(|element| { - element.as_widget_mut().layout( - &mut tree.children[0], - renderer, - limits, - ) + element + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) }) } @@ -187,12 +171,9 @@ where operation: &mut dyn crate::core::widget::Operation, ) { self.with_element_mut(|element| { - element.as_widget_mut().operate( - &mut tree.children[0], - layout, - renderer, - operation, - ); + element + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); }); } @@ -301,8 +282,7 @@ where // - You may not like it, but this is what peak performance looks like // - TODO: Get rid of ouroboros, for good // - What?! - *self.element.borrow().as_ref().unwrap().borrow_mut() = - Some(heads.element); + *self.element.borrow().as_ref().unwrap().borrow_mut() = Some(heads.element); None } @@ -355,9 +335,7 @@ struct Inner<'a, Message: 'a, Theme: 'a, Renderer: 'a> { overlay: Option>>, } -struct Overlay<'a, Message, Theme, Renderer>( - Option>, -); +struct Overlay<'a, Message, Theme, Renderer>(Option>); impl Drop for Overlay<'_, Message, Theme, Renderer> { fn drop(&mut self) { @@ -371,18 +349,20 @@ impl Overlay<'_, Message, Theme, Renderer> { &self, f: impl FnOnce(&mut overlay::Nested<'_, Message, Theme, Renderer>) -> T, ) -> Option { - self.0.as_ref().unwrap().with_overlay(|overlay| { - overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut())) - }) + self.0 + .as_ref() + .unwrap() + .with_overlay(|overlay| overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut()))) } fn with_overlay_mut_maybe( &mut self, f: impl FnOnce(&mut overlay::Nested<'_, Message, Theme, Renderer>) -> T, ) -> Option { - self.0.as_mut().unwrap().with_overlay_mut(|overlay| { - overlay.as_mut().map(|nested| (f)(nested.get_mut())) - }) + self.0 + .as_mut() + .unwrap() + .with_overlay_mut(|overlay| overlay.as_mut().map(|nested| (f)(nested.get_mut()))) } } @@ -415,10 +395,8 @@ where cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { - self.with_overlay_maybe(|overlay| { - overlay.mouse_interaction(layout, cursor, renderer) - }) - .unwrap_or_default() + self.with_overlay_maybe(|overlay| overlay.mouse_interaction(layout, cursor, renderer)) + .unwrap_or_default() } fn update( @@ -446,9 +424,7 @@ where Theme: 'static, Dependency: Hash + 'a, { - fn from( - lazy: Lazy<'a, Message, Theme, Renderer, Dependency, View>, - ) -> Self { + fn from(lazy: Lazy<'a, Message, Theme, Renderer, Dependency, View>) -> Self { Self::new(lazy) } } diff --git a/widget/src/lazy/component.rs b/widget/src/lazy/component.rs index a810e11723..226434f501 100644 --- a/widget/src/lazy/component.rs +++ b/widget/src/lazy/component.rs @@ -6,9 +6,7 @@ use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::widget::tree::{self, Tree}; -use crate::core::{ - self, Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget, -}; +use crate::core::{self, Clipboard, Element, Length, Rectangle, Shell, Size, Vector, Widget}; use iced_renderer::core::widget::Operation; use ouroboros::self_referencing; @@ -58,18 +56,11 @@ pub trait Component { /// Processes an [`Event`](Component::Event) and updates the [`Component`] state accordingly. /// /// It can produce a `Message` for the parent application. - fn update( - &mut self, - state: &mut Self::State, - event: Self::Event, - ) -> Option; + fn update(&mut self, state: &mut Self::State, event: Self::Event) -> Option; /// Produces the widgets of the [`Component`], which may trigger an [`Event`](Component::Event) /// on user interaction. - fn view( - &self, - state: &Self::State, - ) -> Element<'_, Self::Event, Theme, Renderer>; + fn view(&self, state: &Self::State) -> Element<'_, Self::Event, Theme, Renderer>; /// Update the [`Component`] state based on the provided [`Operation`](widget::Operation) /// @@ -98,9 +89,7 @@ struct Tag(T); /// Turns an implementor of [`Component`] into an [`Element`] that can be /// embedded in any application. -pub fn view<'a, C, Message, Theme, Renderer>( - component: C, -) -> Element<'a, Message, Theme, Renderer> +pub fn view<'a, C, Message, Theme, Renderer>(component: C) -> Element<'a, Message, Theme, Renderer> where C: Component + 'a, C::State: 'static, @@ -129,9 +118,7 @@ struct Instance<'a, Message, Theme, Renderer, Event, S> { #[self_referencing] struct State<'a, Message: 'a, Theme: 'a, Renderer: 'a, Event: 'a, S: 'a> { - component: Box< - dyn Component + 'a, - >, + component: Box + 'a>, message: PhantomData, state: PhantomData, @@ -140,8 +127,7 @@ struct State<'a, Message: 'a, Theme: 'a, Renderer: 'a, Event: 'a, S: 'a> { element: Option>, } -impl - Instance<'_, Message, Theme, Renderer, Event, S> +impl Instance<'_, Message, Theme, Renderer, Event, S> where S: Default + 'static, Renderer: renderer::Renderer, @@ -232,10 +218,7 @@ where self.diff_self(); } - fn with_element( - &self, - f: impl FnOnce(&Element<'_, Event, Theme, Renderer>) -> T, - ) -> T { + fn with_element(&self, f: impl FnOnce(&Element<'_, Event, Theme, Renderer>) -> T) -> T { self.with_element_mut(|element| f(element)) } @@ -460,8 +443,12 @@ where tree, types: PhantomData, overlay_builder: |instance, tree| { - instance.state.get_mut().as_mut().unwrap().with_element_mut( - move |element| { + instance + .state + .get_mut() + .as_mut() + .unwrap() + .with_element_mut(move |element| { element .as_mut() .unwrap() @@ -473,11 +460,8 @@ where viewport, translation, ) - .map(|overlay| { - RefCell::new(overlay::Nested::new(overlay)) - }) - }, - ) + .map(|overlay| RefCell::new(overlay::Nested::new(overlay))) + }) }, } .build(); @@ -509,11 +493,9 @@ where let tree = tree.state.downcast_ref::>>>(); self.with_element(|element| { if let Some(tree) = tree.borrow().as_ref() { - element.as_widget().a11y_nodes( - layout, - &tree.children[0], - cursor, - ) + element + .as_widget() + .a11y_nodes(layout, &tree.children[0], cursor) } else { iced_accessibility::A11yTree::default() } @@ -585,9 +567,7 @@ impl .0 .as_ref() .unwrap() - .with_overlay(|overlay| { - overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut())) - }) + .with_overlay(|overlay| overlay.as_ref().map(|nested| (f)(&mut nested.borrow_mut()))) } fn with_overlay_mut_maybe( @@ -600,14 +580,11 @@ impl .0 .as_mut() .unwrap() - .with_overlay_mut(|overlay| { - overlay.as_mut().map(|nested| (f)(nested.get_mut())) - }) + .with_overlay_mut(|overlay| overlay.as_mut().map(|nested| (f)(nested.get_mut()))) } } -impl - overlay::Overlay +impl overlay::Overlay for OverlayInstance<'_, '_, Message, Theme, Renderer, Event, S> where Renderer: core::Renderer, @@ -637,10 +614,8 @@ where cursor: mouse::Cursor, renderer: &Renderer, ) -> mouse::Interaction { - self.with_overlay_maybe(|overlay| { - overlay.mouse_interaction(layout, cursor, renderer) - }) - .unwrap_or_default() + self.with_overlay_maybe(|overlay| overlay.mouse_interaction(layout, cursor, renderer)) + .unwrap_or_default() } fn update( @@ -656,14 +631,7 @@ where let mut local_shell = Shell::new(&mut local_messages); let _ = self.with_overlay_mut_maybe(|overlay| { - overlay.update( - event, - layout, - cursor, - renderer, - clipboard, - &mut local_shell, - ); + overlay.update(event, layout, cursor, renderer, clipboard, &mut local_shell); }); if local_shell.is_event_captured() { @@ -675,8 +643,7 @@ where shell.request_input_method(local_shell.input_method()); if !local_messages.is_empty() { - let mut inner = - self.overlay.take().unwrap().0.take().unwrap().into_heads(); + let mut inner = self.overlay.take().unwrap().0.take().unwrap().into_heads(); let mut heads = inner.instance.state.take().unwrap().into_heads(); for message in local_messages.into_iter().filter_map(|message| { diff --git a/widget/src/list.rs b/widget/src/list.rs index de9fe9b8f7..f1ceb0345a 100644 --- a/widget/src/list.rs +++ b/widget/src/list.rs @@ -8,8 +8,7 @@ use crate::core::widget; use crate::core::widget::tree::{self, Tree}; use crate::core::window; use crate::core::{ - self, Clipboard, Element, Layout, Length, Pixels, Point, Rectangle, Shell, - Size, Vector, Widget, + self, Clipboard, Element, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Vector, Widget, }; use std::cell::RefCell; @@ -20,16 +19,14 @@ use std::collections::VecDeque; pub struct List<'a, T, Message, Theme, Renderer> { content: &'a Content, spacing: f32, - view_item: - Box Element<'a, Message, Theme, Renderer> + 'a>, + view_item: Box Element<'a, Message, Theme, Renderer> + 'a>, visible_elements: Vec>, } impl<'a, T, Message, Theme, Renderer> List<'a, T, Message, Theme, Renderer> { pub fn new( content: &'a Content, - view_item: impl Fn(usize, &'a T) -> Element<'a, Message, Theme, Renderer> - + 'a, + view_item: impl Fn(usize, &'a T) -> Element<'a, Message, Theme, Renderer> + 'a, ) -> Self { Self { content, @@ -134,10 +131,8 @@ where while let Some(change) = changes.pop_front() { match change { Change::Updated { original, current } => { - let mut new_element = (self.view_item)( - current, - &self.content.items[current], - ); + let mut new_element = + (self.view_item)(current, &self.content.items[current]); let visible_index = state .visible_layouts @@ -147,30 +142,29 @@ where let mut new_tree; // Update if visible - let tree = - if let Some(visible_index) = visible_index { - let (_i, _layout, tree) = &mut state - .visible_layouts[visible_index]; + let tree = if let Some(visible_index) = visible_index { + let (_i, _layout, tree) = &mut state.visible_layouts[visible_index]; - tree.diff(&mut new_element); - state.visible_outdated = true; + tree.diff(&mut new_element); + state.visible_outdated = true; - tree - } else { - new_tree = Tree::new(&new_element); + tree + } else { + new_tree = Tree::new(&new_element); - &mut new_tree - }; + &mut new_tree + }; - let new_layout = new_element - .as_widget_mut() - .layout(tree, renderer, &state.last_limits); + let new_layout = new_element.as_widget_mut().layout( + tree, + renderer, + &state.last_limits, + ); let new_size = new_layout.size(); let height_difference = new_size.height - - (state.offsets[original + 1] - - state.offsets[original]); + - (state.offsets[original + 1] - state.offsets[original]); for offset in &mut state.offsets[original + 1..] { *offset += height_difference; @@ -180,27 +174,16 @@ where state.widths[original] = new_size.width; if let Some(visible_index) = visible_index { - state.visible_layouts[visible_index].1 = - new_layout; - - for (i, layout, _) in - &mut state.visible_layouts[visible_index..] - { - layout - .move_to_mut((0.0, state.offsets[*i])); + state.visible_layouts[visible_index].1 = new_layout; + + for (i, layout, _) in &mut state.visible_layouts[visible_index..] { + layout.move_to_mut((0.0, state.offsets[*i])); } - } else if let Some(first_visible) = - state.visible_layouts.first() - { + } else if let Some(first_visible) = state.visible_layouts.first() { let first_visible_index = first_visible.0; if original < first_visible_index { - for (i, layout, _) in - &mut state.visible_layouts[..] - { - layout.move_to_mut(( - 0.0, - state.offsets[*i], - )); + for (i, layout, _) in &mut state.visible_layouts[..] { + layout.move_to_mut((0.0, state.offsets[*i])); } } } @@ -208,17 +191,14 @@ where state.size.height += height_difference; if original_width == state.size.width { - state.size.width = state.widths.iter().fold( - 0.0, - |current, candidate| { - current.max(*candidate) - }, - ); + state.size.width = state + .widths + .iter() + .fold(0.0, |current, candidate| current.max(*candidate)); } } Change::Removed { original, .. } => { - let height = state.offsets[original + 1] - - state.offsets[original]; + let height = state.offsets[original + 1] - state.offsets[original]; let original_width = state.widths.remove(original); let _ = state.offsets.remove(original + 1); @@ -233,19 +213,15 @@ where state.size.height -= height; if original_width == state.size.width { - state.size.width = state.widths.iter().fold( - 0.0, - |current, candidate| { - current.max(*candidate) - }, - ); + state.size.width = state + .widths + .iter() + .fold(0.0, |current, candidate| current.max(*candidate)); } } Change::Pushed { current, .. } => { - let mut new_element = (self.view_item)( - current, - &self.content.items[current], - ); + let mut new_element = + (self.view_item)(current, &self.content.items[current]); let mut tree = Tree::new(&new_element); @@ -258,9 +234,9 @@ where let size = layout.size(); state.widths.push(size.width); - state.offsets.push( - state.offsets.last().unwrap() + size.height, - ); + state + .offsets + .push(state.offsets.last().unwrap() + size.height); state.size.width = state.size.width.max(size.width); state.size.height += size.height; @@ -303,8 +279,7 @@ where let batch = &self.content.items[*current..end]; let mut max_width = size.width; - let mut accumulated_height = - offsets.last().copied().unwrap_or(0.0); + let mut accumulated_height = offsets.last().copied().unwrap_or(0.0); for (i, item) in batch.iter().enumerate() { let mut element = (self.view_item)(*current + i, item); @@ -339,12 +314,10 @@ where let intrinsic_size = Size::new( state.size.width, - state.size.height - + self.content.len().saturating_sub(1) as f32 * self.spacing, + state.size.height + self.content.len().saturating_sub(1) as f32 * self.spacing, ); - let size = - limits.resolve(Length::Shrink, Length::Shrink, intrinsic_size); + let size = limits.resolve(Length::Shrink, Length::Shrink, intrinsic_size); layout::Node::new(size) } @@ -393,16 +366,15 @@ where let offsets = &state.offsets; - let start = - match binary_search_with_index_by(offsets, |i, height| { - (*height + i.saturating_sub(1) as f32 * self.spacing) - .partial_cmp(&(viewport.y - offset.y)) - .unwrap_or(Ordering::Equal) - }) { - Ok(i) => i, - Err(i) => i.saturating_sub(1), - } - .min(self.content.len()); + let start = match binary_search_with_index_by(offsets, |i, height| { + (*height + i.saturating_sub(1) as f32 * self.spacing) + .partial_cmp(&(viewport.y - offset.y)) + .unwrap_or(Ordering::Equal) + }) { + Ok(i) => i, + Err(i) => i.saturating_sub(1), + } + .min(self.content.len()); let end = match binary_search_with_index_by(offsets, |i, height| { (*height + i.saturating_sub(1) as f32 * self.spacing) @@ -414,8 +386,7 @@ where } .min(self.content.len()); - if state.visible_outdated - || state.visible_layouts.len() != self.visible_elements.len() + if state.visible_outdated || state.visible_layouts.len() != self.visible_elements.len() { self.visible_elements.clear(); state.visible_outdated = false; @@ -427,9 +398,7 @@ where self.visible_elements = state .visible_layouts .iter() - .map(|(i, _, _)| { - (self.view_item)(*i, &self.content.items[*i]) - }) + .map(|(i, _, _)| (self.view_item)(*i, &self.content.items[*i])) .collect(); } @@ -458,29 +427,18 @@ where .splice(state.visible_layouts.len() - bottom.., []); // Prepend new visible elements - if let Some(first_visible) = - state.visible_layouts.first().map(|(i, _, _)| *i) - { + if let Some(first_visible) = state.visible_layouts.first().map(|(i, _, _)| *i) { if start < first_visible { - for (i, item) in self.content.items[start..first_visible] - .iter() - .enumerate() - { + for (i, item) in self.content.items[start..first_visible].iter().enumerate() { let mut element = (self.view_item)(start + i, item); let mut tree = Tree::new(&element); let layout = element .as_widget_mut() .layout(&mut tree, renderer, &state.last_limits) - .move_to(( - 0.0, - offsets[start + i] - + (start + i) as f32 * self.spacing, - )); - - state - .visible_layouts - .insert(i, (start + i, layout, tree)); + .move_to((0.0, offsets[start + i] + (start + i) as f32 * self.spacing)); + + state.visible_layouts.insert(i, (start + i, layout, tree)); self.visible_elements.insert(i, element); } } @@ -494,9 +452,7 @@ where .unwrap_or(start); if last_visible < end { - for (i, item) in - self.content.items[last_visible..end].iter().enumerate() - { + for (i, item) in self.content.items[last_visible..end].iter().enumerate() { let mut element = (self.view_item)(last_visible + i, item); let mut tree = Tree::new(&element); @@ -505,15 +461,10 @@ where .layout(&mut tree, renderer, &state.last_limits) .move_to(( 0.0, - offsets[last_visible + i] - + (last_visible + i) as f32 * self.spacing, + offsets[last_visible + i] + (last_visible + i) as f32 * self.spacing, )); - state.visible_layouts.push(( - last_visible + i, - layout, - tree, - )); + state.visible_layouts.push((last_visible + i, layout, tree)); self.visible_elements.push(element); } } @@ -625,13 +576,11 @@ where }) .collect::>(); - (!children.is_empty()) - .then(|| overlay::Group::with_children(children).overlay()) + (!children.is_empty()).then(|| overlay::Group::with_children(children).overlay()) } } -impl<'a, T, Message, Theme, Renderer> - From> +impl<'a, T, Message, Theme, Renderer> From> for Element<'a, Message, Theme, Renderer> where Message: 'a, @@ -750,10 +699,7 @@ impl FromIterator for Content { /// SAFETY: Copied from the `std` library. #[allow(unsafe_code)] -fn binary_search_with_index_by<'a, T, F>( - slice: &'a [T], - mut f: F, -) -> Result +fn binary_search_with_index_by<'a, T, F>(slice: &'a [T], mut f: F) -> Result where F: FnMut(usize, &'a T) -> Ordering, { diff --git a/widget/src/markdown.rs b/widget/src/markdown.rs index e483bbd612..069a86bdab 100644 --- a/widget/src/markdown.rs +++ b/widget/src/markdown.rs @@ -48,12 +48,8 @@ use crate::core::border; use crate::core::font::{self, Font}; use crate::core::padding; use crate::core::theme; -use crate::core::{ - self, Color, Element, Length, Padding, Pixels, Theme, color, -}; -use crate::{ - checkbox, column, container, rich_text, row, rule, scrollable, span, text, -}; +use crate::core::{self, Color, Element, Length, Padding, Pixels, Theme, color}; +use crate::{checkbox, column, container, rich_text, row, rule, scrollable, span, text}; use std::borrow::BorrowMut; use std::cell::{Cell, RefCell}; @@ -424,8 +420,7 @@ impl Bullet { /// } /// ``` pub fn parse(markdown: &str) -> impl Iterator + '_ { - parse_with(State::default(), markdown) - .map(|(item, _source, _broken_links)| item) + parse_with(State::default(), markdown).map(|(item, _source, _broken_links)| item) } #[derive(Debug, Default)] @@ -451,12 +446,10 @@ impl Highlighter { pub fn new(language: &str) -> Self { Self { lines: Vec::new(), - parser: iced_highlighter::Stream::new( - &iced_highlighter::Settings { - theme: iced_highlighter::Theme::Base16Ocean, - token: language.to_owned(), - }, - ), + parser: iced_highlighter::Stream::new(&iced_highlighter::Settings { + theme: iced_highlighter::Theme::Base16Ocean, + token: language.to_owned(), + }), language: language.to_owned(), current: 0, } @@ -476,10 +469,7 @@ impl Highlighter { self.lines.truncate(self.current); for line in &self.lines { - log::debug!( - "Refeeding {n} lines", - n = self.lines.len() - ); + log::debug!("Refeeding {n} lines", n = self.lines.len()); let _ = self.parser.highlight_line(&line.0); } @@ -569,9 +559,7 @@ fn parse_with<'a>( let broken_links = broken_links.clone(); Some(move |broken_link: pulldown_cmark::BrokenLink<'_>| { - if let Some(reference) = - references.get(broken_link.reference.as_ref()) - { + if let Some(reference) = references.get(broken_link.reference.as_ref()) { Some(( pulldown_cmark::CowStr::from(reference.to_owned()), broken_link.reference.into_static(), @@ -589,14 +577,10 @@ fn parse_with<'a>( let references = &mut state.borrow_mut().references; for reference in parser.reference_definitions().iter() { - let _ = references - .insert(reference.0.to_owned(), reference.1.dest.to_string()); + let _ = references.insert(reference.0.to_owned(), reference.1.dest.to_string()); } - let produce = move |state: &mut State, - stack: &mut Vec, - item, - source: Range| { + let produce = move |state: &mut State, stack: &mut Vec, item, source: Range| { if let Some(scope) = stack.last_mut() { match scope { Scope::List(list) => { @@ -692,9 +676,9 @@ fn parse_with<'a>( prev } - pulldown_cmark::Tag::CodeBlock( - pulldown_cmark::CodeBlockKind::Fenced(language), - ) if !metadata => { + pulldown_cmark::Tag::CodeBlock(pulldown_cmark::CodeBlockKind::Fenced(language)) + if !metadata => + { #[cfg(feature = "highlighter")] { highlighter = Some({ @@ -702,16 +686,9 @@ fn parse_with<'a>( .borrow_mut() .highlighter .take() - .filter(|highlighter| { - highlighter.language == language.as_ref() - }) + .filter(|highlighter| highlighter.language == language.as_ref()) .unwrap_or_else(|| { - Highlighter::new( - language - .split(',') - .next() - .unwrap_or_default(), - ) + Highlighter::new(language.split(',').next().unwrap_or_default()) }); highlighter.prepare(); @@ -721,8 +698,7 @@ fn parse_with<'a>( } code_block = true; - code_language = - (!language.is_empty()).then(|| language.into_string()); + code_language = (!language.is_empty()).then(|| language.into_string()); if spans.is_empty() { None @@ -834,12 +810,7 @@ fn parse_with<'a>( return None; }; - produce( - state.borrow_mut(), - &mut stack, - Item::Quote(quote), - source, - ) + produce(state.borrow_mut(), &mut stack, Item::Quote(quote), source) } pulldown_cmark::TagEnd::Image if !metadata => { let (url, title) = image.take()?; @@ -848,12 +819,7 @@ fn parse_with<'a>( let state = state.borrow_mut(); let _ = state.images.insert(url.clone()); - produce( - state, - &mut stack, - Item::Image { url, title, alt }, - source, - ) + produce(state, &mut stack, Item::Image { url, title, alt }, source) } pulldown_cmark::TagEnd::CodeBlock if !metadata => { code_block = false; @@ -939,9 +905,7 @@ fn parse_with<'a>( #[cfg(feature = "highlighter")] if let Some(highlighter) = &mut highlighter { for line in text.lines() { - code_lines.push(Text::new( - highlighter.highlight_line(line).to_vec(), - )); + code_lines.push(Text::new(highlighter.highlight_line(line).to_vec())); } } @@ -1008,9 +972,7 @@ fn parse_with<'a>( }); None } - pulldown_cmark::Event::InlineHtml(h) - if !metadata && h.eq_ignore_ascii_case("
") => - { + pulldown_cmark::Event::InlineHtml(h) if !metadata && h.eq_ignore_ascii_case("
") => { spans.push(Span::Standard { text: String::from("\n"), strikethrough, @@ -1021,9 +983,7 @@ fn parse_with<'a>( }); None } - pulldown_cmark::Event::Rule => { - produce(state.borrow_mut(), &mut stack, Item::Rule, source) - } + pulldown_cmark::Event::Rule => produce(state.borrow_mut(), &mut stack, Item::Rule, source), pulldown_cmark::Event::TaskListMarker(done) => { if let Some(Scope::List(list)) = stack.last_mut() && let Some(item) = list.bullets.last_mut() @@ -1077,10 +1037,7 @@ impl Settings { /// Heading levels will be adjusted automatically. Specifically, /// the first level will be twice the base size, and then every level /// after that will be 25% smaller. - pub fn with_text_size( - text_size: impl Into, - style: impl Into

{ } /// Produces the current widget tree of the [`Instance`]. - pub fn view( - &self, - window: window::Id, - ) -> Element<'_, P::Message, P::Theme, P::Renderer> { + pub fn view(&self, window: window::Id) -> Element<'_, P::Message, P::Theme, P::Renderer> { self.program.view(&self.state, window) } diff --git a/renderer/src/fallback.rs b/renderer/src/fallback.rs index 2a0bdea7f0..3d18172dcb 100644 --- a/renderer/src/fallback.rs +++ b/renderer/src/fallback.rs @@ -3,8 +3,7 @@ use crate::core::image; use crate::core::renderer; use crate::core::svg; use crate::core::{ - self, Background, Color, Font, Image, Pixels, Point, Rectangle, Size, Svg, - Transformation, + self, Background, Color, Font, Image, Pixels, Point, Rectangle, Size, Svg, Transformation, }; use crate::graphics::compositor; use crate::graphics::mesh; @@ -39,11 +38,7 @@ where A: core::Renderer, B: core::Renderer, { - fn fill_quad( - &mut self, - quad: renderer::Quad, - background: impl Into, - ) { + fn fill_quad(&mut self, quad: renderer::Quad, background: impl Into) { delegate!(self, renderer, renderer.fill_quad(quad, background.into())); } @@ -74,9 +69,7 @@ where fn allocate_image( &mut self, handle: &image::Handle, - callback: impl FnOnce(Result) - + Send - + 'static, + callback: impl FnOnce(Result) + Send + 'static, ) { delegate!(self, renderer, renderer.allocate_image(handle, callback)); } @@ -178,10 +171,7 @@ where { type Handle = A::Handle; - fn load_image( - &self, - handle: &Self::Handle, - ) -> Result { + fn load_image(&self, handle: &Self::Handle) -> Result { delegate!(self, renderer, renderer.load_image(handle)) } @@ -189,12 +179,7 @@ where delegate!(self, renderer, renderer.measure_image(handle)) } - fn draw_image( - &mut self, - image: Image, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_image(&mut self, image: Image, bounds: Rectangle, clip_bounds: Rectangle) { delegate!( self, renderer, @@ -212,12 +197,7 @@ where delegate!(self, renderer, renderer.measure_svg(handle)) } - fn draw_svg( - &mut self, - svg: Svg, - bounds: Rectangle, - clip_bounds: Rectangle, - ) { + fn draw_svg(&mut self, svg: Svg, bounds: Rectangle, clip_bounds: Rectangle) { delegate!(self, renderer, renderer.draw_svg(svg, bounds, clip_bounds)); } } @@ -337,12 +317,8 @@ where fn create_renderer(&self) -> Self::Renderer { match self { - Self::Primary(compositor) => { - Renderer::Primary(compositor.create_renderer()) - } - Self::Secondary(compositor) => { - Renderer::Secondary(compositor.create_renderer()) - } + Self::Primary(compositor) => Renderer::Primary(compositor.create_renderer()), + Self::Secondary(compositor) => Renderer::Secondary(compositor.create_renderer()), } } @@ -353,21 +329,16 @@ where height: u32, ) -> Self::Surface { match self { - Self::Primary(compositor) => Surface::Primary( - compositor.create_surface(window, width, height), - ), - Self::Secondary(compositor) => Surface::Secondary( - compositor.create_surface(window, width, height), - ), + Self::Primary(compositor) => { + Surface::Primary(compositor.create_surface(window, width, height)) + } + Self::Secondary(compositor) => { + Surface::Secondary(compositor.create_surface(window, width, height)) + } } } - fn configure_surface( - &mut self, - surface: &mut Self::Surface, - width: u32, - height: u32, - ) { + fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { match (self, surface) { (Self::Primary(compositor), Surface::Primary(surface)) => { compositor.configure_surface(surface, width, height); @@ -396,17 +367,15 @@ where on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { match (self, renderer, surface) { - ( - Self::Primary(compositor), - Renderer::Primary(renderer), - Surface::Primary(surface), - ) => compositor.present( - renderer, - surface, - viewport, - background_color, - on_pre_present, - ), + (Self::Primary(compositor), Renderer::Primary(renderer), Surface::Primary(surface)) => { + compositor.present( + renderer, + surface, + viewport, + background_color, + on_pre_present, + ) + } ( Self::Secondary(compositor), Renderer::Secondary(renderer), @@ -446,19 +415,13 @@ where A: iced_wgpu::primitive::Renderer, B: core::Renderer, { - fn draw_primitive( - &mut self, - bounds: Rectangle, - primitive: impl iced_wgpu::Primitive, - ) { + fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl iced_wgpu::Primitive) { match self { Self::Primary(renderer) => { renderer.draw_primitive(bounds, primitive); } Self::Secondary(_) => { - log::warn!( - "Custom shader primitive is not supported with this renderer." - ); + log::warn!("Custom shader primitive is not supported with this renderer."); } } } @@ -481,12 +444,8 @@ mod geometry { fn new_frame(&self, bounds: Rectangle) -> Self::Frame { match self { - Self::Primary(renderer) => { - Frame::Primary(renderer.new_frame(bounds)) - } - Self::Secondary(renderer) => { - Frame::Secondary(renderer.new_frame(bounds)) - } + Self::Primary(renderer) => Frame::Primary(renderer.new_frame(bounds)), + Self::Secondary(renderer) => Frame::Secondary(renderer.new_frame(bounds)), } } @@ -523,23 +482,15 @@ mod geometry { } } - fn cache( - self, - group: cache::Group, - previous: Option, - ) -> Self::Cache { + fn cache(self, group: cache::Group, previous: Option) -> Self::Cache { match (self, previous) { - ( - Self::Primary(geometry), - Some(Geometry::Primary(previous)), - ) => Geometry::Primary(geometry.cache(group, Some(previous))), - (Self::Primary(geometry), None) => { - Geometry::Primary(geometry.cache(group, None)) + (Self::Primary(geometry), Some(Geometry::Primary(previous))) => { + Geometry::Primary(geometry.cache(group, Some(previous))) + } + (Self::Primary(geometry), None) => Geometry::Primary(geometry.cache(group, None)), + (Self::Secondary(geometry), Some(Geometry::Secondary(previous))) => { + Geometry::Secondary(geometry.cache(group, Some(previous))) } - ( - Self::Secondary(geometry), - Some(Geometry::Secondary(previous)), - ) => Geometry::Secondary(geometry.cache(group, Some(previous))), (Self::Secondary(geometry), None) => { Geometry::Secondary(geometry.cache(group, None)) } @@ -581,12 +532,7 @@ mod geometry { delegate!(self, frame, frame.fill(path, fill)); } - fn fill_rectangle( - &mut self, - top_left: Point, - size: Size, - fill: impl Into, - ) { + fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into) { delegate!(self, frame, frame.fill_rectangle(top_left, size, fill)); } @@ -600,18 +546,10 @@ mod geometry { size: Size, stroke: impl Into>, ) { - delegate!( - self, - frame, - frame.stroke_rectangle(top_left, size, stroke) - ); + delegate!(self, frame, frame.stroke_rectangle(top_left, size, stroke)); } - fn stroke_text<'a>( - &mut self, - text: impl Into, - stroke: impl Into>, - ) { + fn stroke_text<'a>(&mut self, text: impl Into, stroke: impl Into>) { delegate!(self, frame, frame.stroke_text(text, stroke)); } @@ -672,12 +610,8 @@ mod geometry { fn into_geometry(self) -> Self::Geometry { match self { - Frame::Primary(frame) => { - Geometry::Primary(frame.into_geometry()) - } - Frame::Secondary(frame) => { - Geometry::Secondary(frame.into_geometry()) - } + Frame::Primary(frame) => Geometry::Primary(frame.into_geometry()), + Frame::Secondary(frame) => Geometry::Secondary(frame.into_geometry()), } } } @@ -693,9 +627,7 @@ where default_text_size: Pixels, backend: Option<&str>, ) -> Option { - if let Some(renderer) = - A::new(default_font, default_text_size, backend).await - { + if let Some(renderer) = A::new(default_font, default_text_size, backend).await { return Some(Self::Primary(renderer)); } diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs index 0336f3dd7b..d430ccb73b 100644 --- a/renderer/src/lib.rs +++ b/renderer/src/lib.rs @@ -24,10 +24,7 @@ pub type Compositor = renderer::Compositor; #[cfg(all(feature = "wgpu-bare", feature = "tiny-skia"))] mod renderer { - pub type Renderer = crate::fallback::Renderer< - iced_wgpu::Renderer, - iced_tiny_skia::Renderer, - >; + pub type Renderer = crate::fallback::Renderer; pub type Compositor = crate::fallback::Compositor< iced_wgpu::window::Compositor, diff --git a/runtime/src/clipboard.rs b/runtime/src/clipboard.rs index 6c0c92db88..e6f99ceabb 100644 --- a/runtime/src/clipboard.rs +++ b/runtime/src/clipboard.rs @@ -98,11 +98,7 @@ pub fn write_primary(contents: String) -> Task { /// Read the current contents of the clipboard. pub fn read_data() -> Task> { task::oneshot(|tx| { - crate::Action::Clipboard(Action::ReadData( - T::allowed().into(), - tx, - Kind::Standard, - )) + crate::Action::Clipboard(Action::ReadData(T::allowed().into(), tx, Kind::Standard)) }) .map(|d| d.and_then(|d| T::try_from(d).ok())) } diff --git a/runtime/src/dnd.rs b/runtime/src/dnd.rs index e6f2b2678a..d71fb20aa6 100644 --- a/runtime/src/dnd.rs +++ b/runtime/src/dnd.rs @@ -6,7 +6,7 @@ use dnd::{DndDestinationRectangle, DndSurface}; use iced_core::clipboard::DndSource; use window_clipboard::mime::{AllowedMimeTypes, AsMimeTypes}; -use crate::{oneshot, task, Action, Task}; +use crate::{Action, Task, oneshot, task}; /// An action to be performed on the system. pub enum DndAction { @@ -41,9 +41,7 @@ impl std::fmt::Debug for DndAction { .field("rectangles", rectangles) .finish(), Self::EndDnd => f.write_str("EndDnd"), - Self::PeekDnd(mime, _) => { - f.debug_struct("PeekDnd").field("mime", mime).finish() - } + Self::PeekDnd(mime, _) => f.debug_struct("PeekDnd").field("mime", mime).finish(), Self::SetAction(a) => f.debug_tuple("SetAction").field(a).finish(), } } diff --git a/runtime/src/image.rs b/runtime/src/image.rs index 53b736ccf6..be22e1a599 100644 --- a/runtime/src/image.rs +++ b/runtime/src/image.rs @@ -18,7 +18,5 @@ pub enum Action { /// that using a [`Handle`] will draw the corresponding image immediately /// in the next frame. pub fn allocate(handle: impl Into) -> Task> { - task::oneshot(|sender| { - crate::Action::Image(Action::Allocate(handle.into(), sender)) - }) + task::oneshot(|sender| crate::Action::Image(Action::Allocate(handle.into(), sender))) } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 22da3d6623..1efb9de786 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -87,9 +87,7 @@ impl Action { fn output(self) -> Result> { match self { Action::Output(output) => Ok(output), - Action::LoadFont { bytes, channel } => { - Err(Action::LoadFont { bytes, channel }) - } + Action::LoadFont { bytes, channel } => Err(Action::LoadFont { bytes, channel }), Action::Widget(operation) => Err(Action::Widget(operation)), Action::Clipboard(action) => Err(Action::Clipboard(action)), Action::Window(action) => Err(Action::Window(action)), diff --git a/runtime/src/platform_specific/wayland/activation.rs b/runtime/src/platform_specific/wayland/activation.rs index 64d4dc4dc4..3f48f01ccc 100644 --- a/runtime/src/platform_specific/wayland/activation.rs +++ b/runtime/src/platform_specific/wayland/activation.rs @@ -36,7 +36,7 @@ impl fmt::Debug for Action { f, "Action::ActivationAction::Activate {{ window: {:?}, token: {:?} }}", window, token, - ) + ), } } } diff --git a/runtime/src/platform_specific/wayland/layer_surface.rs b/runtime/src/platform_specific/wayland/layer_surface.rs index 4745ef6715..9f883daeed 100644 --- a/runtime/src/platform_specific/wayland/layer_surface.rs +++ b/runtime/src/platform_specific/wayland/layer_surface.rs @@ -6,8 +6,8 @@ use cctk::sctk::{ }; use iced_core::layout::Limits; -use iced_core::window::Id; use iced_core::Rectangle; +use iced_core::window::Id; /// output for layer surface #[derive(Debug, Clone)] @@ -162,35 +162,44 @@ impl fmt::Debug for Action { ), Action::Size { id, width, height } => write!( f, - "Action::LayerSurfaceAction::Size {{ id: {:#?}, width: {:?}, height: {:?} }}", id, width, height - ), - Action::Destroy(id) => write!( - f, - "Action::LayerSurfaceAction::Destroy {{ id: {:#?} }}", id + "Action::LayerSurfaceAction::Size {{ id: {:#?}, width: {:?}, height: {:?} }}", + id, width, height ), + Action::Destroy(id) => { + write!(f, "Action::LayerSurfaceAction::Destroy {{ id: {:#?} }}", id) + } Action::Anchor { id, anchor } => write!( f, - "Action::LayerSurfaceAction::Anchor {{ id: {:#?}, anchor: {:?} }}", id, anchor + "Action::LayerSurfaceAction::Anchor {{ id: {:#?}, anchor: {:?} }}", + id, anchor ), Action::ExclusiveZone { id, exclusive_zone } => write!( f, - "Action::LayerSurfaceAction::ExclusiveZone {{ id: {:#?}, exclusive_zone: {exclusive_zone} }}", id + "Action::LayerSurfaceAction::ExclusiveZone {{ id: {:#?}, exclusive_zone: {exclusive_zone} }}", + id ), Action::Margin { id, margin } => write!( f, - "Action::LayerSurfaceAction::Margin {{ id: {:#?}, margin: {:?} }}", id, margin + "Action::LayerSurfaceAction::Margin {{ id: {:#?}, margin: {:?} }}", + id, margin ), - Action::KeyboardInteractivity { id, keyboard_interactivity } => write!( + Action::KeyboardInteractivity { + id, + keyboard_interactivity, + } => write!( f, - "Action::LayerSurfaceAction::KeyboardInteractivity {{ id: {:#?}, keyboard_interactivity: {:?} }}", id, keyboard_interactivity + "Action::LayerSurfaceAction::KeyboardInteractivity {{ id: {:#?}, keyboard_interactivity: {:?} }}", + id, keyboard_interactivity ), Action::InputZone { id, zone } => write!( f, - "Action::LayerSurfaceAction::InputZone {{ id: {:#?}, zone: {:?} }}", id, zone + "Action::LayerSurfaceAction::InputZone {{ id: {:#?}, zone: {:?} }}", + id, zone ), Action::Layer { id, layer } => write!( f, - "Action::LayerSurfaceAction::Layer {{ id: {:#?}, layer: {:?} }}", id, layer + "Action::LayerSurfaceAction::Layer {{ id: {:#?}, layer: {:?} }}", + id, layer ), } } diff --git a/runtime/src/platform_specific/wayland/mod.rs b/runtime/src/platform_specific/wayland/mod.rs index 3c2ac977d1..84a6b7426f 100644 --- a/runtime/src/platform_specific/wayland/mod.rs +++ b/runtime/src/platform_specific/wayland/mod.rs @@ -50,25 +50,13 @@ pub struct CornerRadius { impl Debug for Action { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Action::LayerSurface(arg0) => { - f.debug_tuple("LayerSurface").field(arg0).finish() - } + Action::LayerSurface(arg0) => f.debug_tuple("LayerSurface").field(arg0).finish(), Action::Popup(arg0) => f.debug_tuple("Popup").field(arg0).finish(), - Action::Activation(arg0) => { - f.debug_tuple("Activation").field(arg0).finish() - } - Action::SessionLock(arg0) => { - f.debug_tuple("SessionLock").field(arg0).finish() - } - Action::OverlapNotify(id, _) => { - f.debug_tuple("OverlapNotify").field(id).finish() - } - Action::Subsurface(action) => { - f.debug_tuple("Subsurface").field(action).finish() - } - Action::InhibitShortcuts(v) => { - f.debug_tuple("InhibitShortcuts").field(v).finish() - } + Action::Activation(arg0) => f.debug_tuple("Activation").field(arg0).finish(), + Action::SessionLock(arg0) => f.debug_tuple("SessionLock").field(arg0).finish(), + Action::OverlapNotify(id, _) => f.debug_tuple("OverlapNotify").field(id).finish(), + Action::Subsurface(action) => f.debug_tuple("Subsurface").field(action).finish(), + Action::InhibitShortcuts(v) => f.debug_tuple("InhibitShortcuts").field(v).finish(), Action::RoundedCorners(id, v) => { f.debug_tuple("RoundedCorners").field(id).field(v).finish() } diff --git a/runtime/src/platform_specific/wayland/popup.rs b/runtime/src/platform_specific/wayland/popup.rs index e0475eb826..8e52360e5e 100644 --- a/runtime/src/platform_specific/wayland/popup.rs +++ b/runtime/src/platform_specific/wayland/popup.rs @@ -3,9 +3,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use cctk::sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{ - Anchor, Gravity, -}; +use cctk::sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{Anchor, Gravity}; use iced_core::layout::Limits; use iced_core::window::Id; use iced_core::{Element, Rectangle}; @@ -129,16 +127,10 @@ pub enum Action { impl fmt::Debug for Action { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Action::Popup { popup, .. } => write!( - f, - "Action::PopupAction::Popup {{ popup: {:?} }}", - popup - ), - Action::Destroy { id } => write!( - f, - "Action::PopupAction::Destroy {{ id: {:?} }}", - id - ), + Action::Popup { popup, .. } => { + write!(f, "Action::PopupAction::Popup {{ popup: {:?} }}", popup) + } + Action::Destroy { id } => write!(f, "Action::PopupAction::Destroy {{ id: {:?} }}", id), Action::Size { id, width, height } => write!( f, "Action::PopupAction::Size {{ id: {:?}, width: {:?}, height: {:?} }}", diff --git a/runtime/src/platform_specific/wayland/subsurface.rs b/runtime/src/platform_specific/wayland/subsurface.rs index f174b0a5a5..51d4d2765d 100644 --- a/runtime/src/platform_specific/wayland/subsurface.rs +++ b/runtime/src/platform_specific/wayland/subsurface.rs @@ -3,9 +3,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use cctk::sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{ - Anchor, Gravity, -}; +use cctk::sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{Anchor, Gravity}; use iced_core::layout::Limits; use iced_core::window::Id; use iced_core::{Element, Point, Rectangle, Size}; @@ -74,11 +72,9 @@ impl fmt::Debug for Action { "Action::SubsurfaceAction::Subsurface {{ subsurface: {:?} }}", subsurface ), - Action::Destroy { id } => write!( - f, - "Action::SubsurfaceAction::Destroy {{ id: {:?} }}", - id - ), + Action::Destroy { id } => { + write!(f, "Action::SubsurfaceAction::Destroy {{ id: {:?} }}", id) + } Action::Reposition { id, x, y } => write!( f, "Action::SubsurfaceAction::Reposition {{ id: {:?}, x: {:?}, y: {:?} }}", diff --git a/runtime/src/system.rs b/runtime/src/system.rs index 09f112f5e1..609bcaa407 100644 --- a/runtime/src/system.rs +++ b/runtime/src/system.rs @@ -49,9 +49,7 @@ pub struct Information { /// Returns available system information. pub fn information() -> Task { - task::oneshot(|channel| { - crate::Action::System(Action::GetInformation(channel)) - }) + task::oneshot(|channel| crate::Action::System(Action::GetInformation(channel))) } /// Returns the current system theme. diff --git a/runtime/src/task.rs b/runtime/src/task.rs index 209c117674..e9ee051aca 100644 --- a/runtime/src/task.rs +++ b/runtime/src/task.rs @@ -109,10 +109,7 @@ impl Task { } /// Maps the output of a [`Task`] with the given closure. - pub fn map( - self, - mut f: impl FnMut(T) -> O + MaybeSend + 'static, - ) -> Task + pub fn map(self, mut f: impl FnMut(T) -> O + MaybeSend + 'static) -> Task where T: MaybeSend + 'static, O: MaybeSend + 'static, @@ -125,10 +122,7 @@ impl Task { /// /// This is the monadic interface of [`Task`]—analogous to [`Future`] and /// [`Stream`]. - pub fn then( - self, - mut f: impl FnMut(T) -> Task + MaybeSend + 'static, - ) -> Task + pub fn then(self, mut f: impl FnMut(T) -> Task + MaybeSend + 'static) -> Task where T: MaybeSend + 'static, O: MaybeSend + 'static, @@ -136,20 +130,14 @@ impl Task { Task { stream: match self.stream { None => None, - Some(stream) => { - Some(boxed_stream(stream.flat_map(move |action| { - match action.output() { - Ok(output) => { - f(output).stream.unwrap_or_else(|| { - boxed_stream(stream::empty()) - }) - } - Err(action) => boxed_stream(stream::once( - async move { action }, - )), - } - }))) - } + Some(stream) => Some(boxed_stream(stream.flat_map(move |action| { + match action.output() { + Ok(output) => f(output) + .stream + .unwrap_or_else(|| boxed_stream(stream::empty())), + Err(action) => boxed_stream(stream::once(async move { action })), + } + }))), }, units: self.units, } @@ -190,10 +178,7 @@ impl Task { let mut outputs = outputs?; let Some(action) = stream.next().await else { - return Some(( - Some(Action::Output(outputs)), - (stream, None), - )); + return Some((Some(Action::Output(outputs)), (stream, None))); }; match action.output() { @@ -202,10 +187,7 @@ impl Task { Some((None, (stream, Some(outputs)))) } - Err(action) => Some(( - Some(action), - (stream, Some(outputs)), - )), + Err(action) => Some((Some(action), (stream, Some(outputs)))), } }, ) @@ -345,10 +327,7 @@ impl Handle { impl Drop for Handle { fn drop(&mut self) { if let InternalHandle::AbortOnDrop(handle) = &mut self.internal { - let handle = std::mem::replace( - handle, - Arc::new(stream::AbortHandle::new_pair().0), - ); + let handle = std::mem::replace(handle, Arc::new(stream::AbortHandle::new_pair().0)); if let Some(handle) = Arc::into_inner(handle) { handle.abort(); @@ -361,10 +340,7 @@ impl Task> { /// Executes a new [`Task`] after this one, only when it produces `Some` value. /// /// The value is provided to the closure to create the subsequent [`Task`]. - pub fn and_then( - self, - f: impl Fn(T) -> Task + MaybeSend + 'static, - ) -> Task + pub fn and_then(self, f: impl Fn(T) -> Task + MaybeSend + 'static) -> Task where T: MaybeSend + 'static, A: MaybeSend + 'static, @@ -386,17 +362,12 @@ impl Task> { E: MaybeSend + 'static, A: MaybeSend + 'static, { - self.then(move |result| { - result.map_or_else(|error| Task::done(Err(error)), &f) - }) + self.then(move |result| result.map_or_else(|error| Task::done(Err(error)), &f)) } /// Maps the error type of this [`Task`] to a different one using the given /// function. - pub fn map_err( - self, - f: impl Fn(E) -> E2 + MaybeSend + 'static, - ) -> Task> + pub fn map_err(self, f: impl Fn(E) -> E2 + MaybeSend + 'static) -> Task> where T: MaybeSend + 'static, E: MaybeSend + 'static, @@ -425,10 +396,9 @@ where T: Send + 'static, { channel(move |sender| { - let operation = - widget::operation::map(Box::new(operation), move |value| { - let _ = sender.clone().try_send(value); - }); + let operation = widget::operation::map(Box::new(operation), move |value| { + let _ = sender.clone().try_send(value); + }); Action::Widget(Box::new(operation)) }) @@ -445,11 +415,13 @@ where let action = f(sender); Task { - stream: Some(boxed_stream(stream::once(async move { action }).chain( - receiver.into_stream().filter_map(|result| async move { - Some(Action::Output(result.ok()?)) - }), - ))), + stream: Some(boxed_stream( + stream::once(async move { action }).chain( + receiver + .into_stream() + .filter_map(|result| async move { Some(Action::Output(result.ok()?)) }), + ), + )), units: 1, } } @@ -542,10 +514,7 @@ async fn yield_now() { impl Future for YieldNow { type Output = (); - fn poll( - mut self: Pin<&mut Self>, - cx: &mut task::Context<'_>, - ) -> task::Poll<()> { + fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<()> { if self.yielded { return task::Poll::Ready(()); } diff --git a/runtime/src/user_interface.rs b/runtime/src/user_interface.rs index 32430e361e..ac31ad99b1 100644 --- a/runtime/src/user_interface.rs +++ b/runtime/src/user_interface.rs @@ -10,9 +10,7 @@ use crate::core::overlay; use crate::core::renderer; use crate::core::widget; use crate::core::window; -use crate::core::{ - Clipboard, Element, InputMethod, Layout, Rectangle, Shell, Size, Vector, -}; +use crate::core::{Clipboard, Element, InputMethod, Layout, Rectangle, Shell, Size, Vector}; /// A set of interactive graphical elements with a specific [`Layout`]. /// @@ -220,104 +218,102 @@ where ) .map(overlay::Nested::new); - let (base_cursor, overlay_statuses, overlay_interaction) = - if maybe_overlay.is_some() { - let bounds = self.bounds; + let (base_cursor, overlay_statuses, overlay_interaction) = if maybe_overlay.is_some() { + let bounds = self.bounds; - let mut overlay = maybe_overlay.as_mut().unwrap(); - let mut layout = overlay.layout(renderer, bounds); - let mut event_statuses = Vec::new(); + let mut overlay = maybe_overlay.as_mut().unwrap(); + let mut layout = overlay.layout(renderer, bounds); + let mut event_statuses = Vec::new(); - for event in events { - let mut shell = Shell::new(messages); + for event in events { + let mut shell = Shell::new(messages); - overlay.update( - event, - Layout::new(&layout), - cursor, - renderer, - clipboard, - &mut shell, - ); + overlay.update( + event, + Layout::new(&layout), + cursor, + renderer, + clipboard, + &mut shell, + ); + + event_statuses.push(shell.event_status()); + redraw_request = redraw_request.min(shell.redraw_request()); + input_method.merge(shell.input_method()); - event_statuses.push(shell.event_status()); - redraw_request = redraw_request.min(shell.redraw_request()); - input_method.merge(shell.input_method()); + if shell.is_layout_invalid() { + drop(maybe_overlay); - if shell.is_layout_invalid() { - drop(maybe_overlay); + self.base = self.root.as_widget_mut().layout( + &mut self.state, + renderer, + &layout::Limits::new(Size::ZERO, self.bounds), + ); - self.base = self.root.as_widget_mut().layout( + maybe_overlay = self + .root + .as_widget_mut() + .overlay( &mut self.state, + Layout::new(&self.base), renderer, - &layout::Limits::new(Size::ZERO, self.bounds), - ); - - maybe_overlay = self - .root - .as_widget_mut() - .overlay( - &mut self.state, - Layout::new(&self.base), - renderer, - &viewport, - Vector::ZERO, - ) - .map(overlay::Nested::new); - - if maybe_overlay.is_none() { - break; - } - - overlay = maybe_overlay.as_mut().unwrap(); - - shell.revalidate_layout(|| { - layout = overlay.layout(renderer, bounds); - has_layout_changed = true; - }); - } + &viewport, + Vector::ZERO, + ) + .map(overlay::Nested::new); - if shell.are_widgets_invalid() { - outdated = true; + if maybe_overlay.is_none() { + break; } + + overlay = maybe_overlay.as_mut().unwrap(); + + shell.revalidate_layout(|| { + layout = overlay.layout(renderer, bounds); + has_layout_changed = true; + }); } - let (base_cursor, interaction) = - if let Some(overlay) = maybe_overlay.as_mut() { - let interaction = cursor - .position() - .map(|cursor_position| { - overlay.mouse_interaction( - Layout::new(&layout), - mouse::Cursor::Available(cursor_position), - renderer, - ) - }) - .unwrap_or_default(); - - if interaction == mouse::Interaction::None { - (cursor, mouse::Interaction::None) - } else { - (mouse::Cursor::Unavailable, interaction) - } - } else { - (cursor, mouse::Interaction::None) - }; + if shell.are_widgets_invalid() { + outdated = true; + } + } - self.overlay = Some(Overlay { - layout, - interaction, - }); + let (base_cursor, interaction) = if let Some(overlay) = maybe_overlay.as_mut() { + let interaction = cursor + .position() + .map(|cursor_position| { + overlay.mouse_interaction( + Layout::new(&layout), + mouse::Cursor::Available(cursor_position), + renderer, + ) + }) + .unwrap_or_default(); - (base_cursor, event_statuses, interaction) + if interaction == mouse::Interaction::None { + (cursor, mouse::Interaction::None) + } else { + (mouse::Cursor::Unavailable, interaction) + } } else { - ( - cursor, - vec![event::Status::Ignored; events.len()], - mouse::Interaction::None, - ) + (cursor, mouse::Interaction::None) }; + self.overlay = Some(Overlay { + layout, + interaction, + }); + + (base_cursor, event_statuses, interaction) + } else { + ( + cursor, + vec![event::Status::Ignored; events.len()], + mouse::Interaction::None, + ) + }; + drop(maybe_overlay); let event_statuses = events @@ -370,11 +366,8 @@ where .map(overlay::Nested::new) { let layout = overlay.layout(renderer, self.bounds); - let interaction = overlay.mouse_interaction( - Layout::new(&layout), - cursor, - renderer, - ); + let interaction = + overlay.mouse_interaction(Layout::new(&layout), cursor, renderer); self.overlay = Some(Overlay { layout, @@ -391,18 +384,17 @@ where }) .collect(); - let mouse_interaction = - if overlay_interaction == mouse::Interaction::None { - self.root.as_widget().mouse_interaction( - &self.state, - Layout::new(&self.base), - base_cursor, - &viewport, - renderer, - ) - } else { - overlay_interaction - }; + let mouse_interaction = if overlay_interaction == mouse::Interaction::None { + self.root.as_widget().mouse_interaction( + &self.state, + Layout::new(&self.base), + base_cursor, + &viewport, + renderer, + ) + } else { + overlay_interaction + }; ( if outdated { @@ -549,11 +541,7 @@ where } /// Applies a [`widget::Operation`] to the [`UserInterface`]. - pub fn operate( - &mut self, - renderer: &Renderer, - operation: &mut dyn widget::Operation, - ) { + pub fn operate(&mut self, renderer: &Renderer, operation: &mut dyn widget::Operation) { let viewport = Rectangle::with_size(self.bounds); self.root.as_widget_mut().operate( @@ -604,15 +592,10 @@ where /// get a11y nodes #[cfg(feature = "a11y")] - pub fn a11y_nodes( - &self, - cursor: mouse::Cursor, - ) -> iced_accessibility::A11yTree { - self.root.as_widget().a11y_nodes( - Layout::new(&self.base), - &self.state, - cursor, - ) + pub fn a11y_nodes(&self, cursor: mouse::Cursor) -> iced_accessibility::A11yTree { + self.root + .as_widget() + .a11y_nodes(Layout::new(&self.base), &self.state, cursor) } /// Find widget with given id diff --git a/runtime/src/widget/operation.rs b/runtime/src/widget/operation.rs index 3aa1f9d4db..4cc5702c1d 100644 --- a/runtime/src/widget/operation.rs +++ b/runtime/src/widget/operation.rs @@ -4,15 +4,10 @@ use crate::core::widget::operation; use crate::task; use crate::{Action, Task}; -pub use crate::core::widget::operation::scrollable::{ - AbsoluteOffset, RelativeOffset, -}; +pub use crate::core::widget::operation::scrollable::{AbsoluteOffset, RelativeOffset}; /// Snaps the scrollable with the given [`Id`] to the provided [`RelativeOffset`]. -pub fn snap_to( - id: impl Into, - offset: impl Into>>, -) -> Task { +pub fn snap_to(id: impl Into, offset: impl Into>>) -> Task { task::effect(Action::widget(operation::scrollable::snap_to( id.into(), offset.into(), @@ -28,10 +23,7 @@ pub fn snap_to_end(id: impl Into) -> Task { } /// Scrolls the scrollable with the given [`Id`] to the provided [`AbsoluteOffset`]. -pub fn scroll_to( - id: impl Into, - offset: impl Into>>, -) -> Task { +pub fn scroll_to(id: impl Into, offset: impl Into>>) -> Task { task::effect(Action::widget(operation::scrollable::scroll_to( id.into(), offset.into(), diff --git a/runtime/src/widget/selector.rs b/runtime/src/widget/selector.rs index 77d4eb2d30..9597db3271 100644 --- a/runtime/src/widget/selector.rs +++ b/runtime/src/widget/selector.rs @@ -1,7 +1,5 @@ //! Find and query widgets in your applications. -pub use iced_selector::{ - Bounded, Candidate, Selector, Target, Text, id, is_focused, -}; +pub use iced_selector::{Bounded, Candidate, Selector, Target, Text, id, is_focused}; use crate::Task; use crate::task; diff --git a/runtime/src/window.rs b/runtime/src/window.rs index 4d2f5650de..f3627608bb 100644 --- a/runtime/src/window.rs +++ b/runtime/src/window.rs @@ -1,8 +1,7 @@ //! Build window-based GUI applications. use crate::core::time::Instant; use crate::core::window::{ - Direction, Event, Icon, Id, Level, Mode, Screenshot, Settings, - UserAttention, + Direction, Event, Icon, Id, Level, Mode, Screenshot, Settings, UserAttention, }; use crate::core::{Point, Size}; use crate::futures::Subscription; @@ -216,9 +215,7 @@ impl Window for T where T: HasWindowHandle + HasDisplayHandle {} /// animations without missing any frames. pub fn frames() -> Subscription<(Id, Instant)> { event::listen_raw(|event, _status, window| match event { - crate::core::Event::Window(Event::RedrawRequested(at)) => { - Some((window, at)) - } + crate::core::Event::Window(Event::RedrawRequested(at)) => Some((window, at)), _ => None, }) } @@ -234,11 +231,9 @@ pub fn frames() -> Subscription<(Id, Instant)> { pub fn wayland_frames() -> Subscription { event::listen_raw(|event, _status, _window| match event { iced_core::Event::Window(Event::RedrawRequested(at)) - | iced_core::Event::PlatformSpecific( - iced_core::event::PlatformSpecific::Wayland( - iced_core::event::wayland::Event::Frame(at, _, _), - ), - ) => Some(at), + | iced_core::Event::PlatformSpecific(iced_core::event::PlatformSpecific::Wayland( + iced_core::event::wayland::Event::Frame(at, _, _), + )) => Some(at), _ => None, }) } @@ -305,9 +300,7 @@ pub fn open(settings: Settings) -> (Id, Task) { ( id, - task::oneshot(|channel| { - crate::Action::Window(Action::Open(id, settings, channel)) - }), + task::oneshot(|channel| crate::Action::Window(Action::Open(id, settings, channel))), ) } @@ -367,16 +360,12 @@ pub fn set_resize_increments(id: Id, increments: Option) -> Task { /// Gets the window size in logical dimensions. pub fn size(id: Id) -> Task { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetSize(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetSize(id, channel))) } /// Gets the maximized state of the window with the given [`Id`]. pub fn is_maximized(id: Id) -> Task { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetMaximized(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetMaximized(id, channel))) } /// Maximizes the window. @@ -386,9 +375,7 @@ pub fn maximize(id: Id, maximized: bool) -> Task { /// Gets the minimized state of the window with the given [`Id`]. pub fn is_minimized(id: Id) -> Task> { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetMinimized(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetMinimized(id, channel))) } /// Minimizes the window. @@ -398,16 +385,12 @@ pub fn minimize(id: Id, minimized: bool) -> Task { /// Gets the position in logical coordinates of the window with the given [`Id`]. pub fn position(id: Id) -> Task> { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetPosition(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetPosition(id, channel))) } /// Gets the scale factor of the window with the given [`Id`]. pub fn scale_factor(id: Id) -> Task { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetScaleFactor(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetScaleFactor(id, channel))) } /// Moves the window to the given logical coordinates. @@ -417,9 +400,7 @@ pub fn move_to(id: Id, position: Point) -> Task { /// Gets the current [`Mode`] of the window. pub fn mode(id: Id) -> Task { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetMode(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetMode(id, channel))) } /// Changes the [`Mode`] of the window. @@ -443,10 +424,7 @@ pub fn toggle_decorations(id: Id) -> Task { /// /// Providing `None` will unset the request for user attention. Unsetting the request for /// user attention might not be done automatically by the WM when the window receives input. -pub fn request_user_attention( - id: Id, - user_attention: Option, -) -> Task { +pub fn request_user_attention(id: Id, user_attention: Option) -> Task { task::effect(crate::Action::Window(Action::RequestUserAttention( id, user_attention, @@ -478,9 +456,7 @@ pub fn show_system_menu(id: Id) -> Task { /// Gets an identifier unique to the window, provided by the underlying windowing system. This is /// not to be confused with [`Id`]. pub fn raw_id(id: Id) -> Task { - task::oneshot(|channel| { - crate::Action::Window(Action::GetRawId(id, channel)) - }) + task::oneshot(|channel| crate::Action::Window(Action::GetRawId(id, channel))) } /// Changes the [`Icon`] of the window. @@ -491,10 +467,7 @@ pub fn set_icon(id: Id, icon: Icon) -> Task { /// Runs the given callback with a reference to the [`Window`] with the given [`Id`]. /// /// Note that if the window closes before this call is processed the callback will not be run. -pub fn run( - id: Id, - f: impl FnOnce(&dyn Window) -> T + Send + 'static, -) -> Task +pub fn run(id: Id, f: impl FnOnce(&dyn Window) -> T + Send + 'static) -> Task where T: Send + 'static, { @@ -511,10 +484,7 @@ where /// Runs the given callback with the native window handle for the window with the given id. /// /// Note that if the window closes before this call is processed the callback will not be run. -pub fn run_with_handle( - id: Id, - f: impl FnOnce(WindowHandle<'_>) -> T + Send + 'static, -) -> Task +pub fn run_with_handle(id: Id, f: impl FnOnce(WindowHandle<'_>) -> T + Send + 'static) -> Task where T: Send + 'static, { @@ -530,9 +500,7 @@ where /// Captures a [`Screenshot`] from the window. pub fn screenshot(id: Id) -> Task { - task::oneshot(move |channel| { - crate::Action::Window(Action::Screenshot(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::Screenshot(id, channel))) } /// Enables mouse passthrough for the given window. @@ -553,9 +521,7 @@ pub fn disable_mouse_passthrough(id: Id) -> Task { /// Gets the logical dimensions of the monitor containing the window with the given [`Id`]. pub fn monitor_size(id: Id) -> Task> { - task::oneshot(move |channel| { - crate::Action::Window(Action::GetMonitorSize(id, channel)) - }) + task::oneshot(move |channel| crate::Action::Window(Action::GetMonitorSize(id, channel))) } /// Sets whether the system can automatically organize windows into tabs. diff --git a/rustfmt.toml b/rustfmt.toml deleted file mode 100644 index dccc2a062e..0000000000 --- a/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -max_width=80 -edition="2024" diff --git a/selector/src/find.rs b/selector/src/find.rs index cfdba7b38a..55b2780522 100644 --- a/selector/src/find.rs +++ b/selector/src/find.rs @@ -1,7 +1,5 @@ use crate::Selector; -use crate::core::widget::operation::{ - Focusable, Outcome, Scrollable, TextInput, -}; +use crate::core::widget::operation::{Focusable, Outcome, Scrollable, TextInput}; use crate::core::widget::{Id, Operation}; use crate::core::{Rectangle, Vector}; use crate::target::Candidate; @@ -136,10 +134,7 @@ where S: Strategy + Send, S::Output: Send, { - fn traverse( - &mut self, - operate: &mut dyn FnMut(&mut dyn Operation), - ) { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { if self.strategy.is_done() { return; } @@ -161,18 +156,11 @@ where self.strategy.feed(Candidate::Container { id, bounds, - visible_bounds: self - .viewport - .intersection(&(bounds + self.translation)), + visible_bounds: self.viewport.intersection(&(bounds + self.translation)), }); } - fn focusable( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Focusable, - ) { + fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { if self.strategy.is_done() { return; } @@ -180,9 +168,7 @@ where self.strategy.feed(Candidate::Focusable { id, bounds, - visible_bounds: self - .viewport - .intersection(&(bounds + self.translation)), + visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } @@ -199,8 +185,7 @@ where return; } - let visible_bounds = - self.viewport.intersection(&(bounds + self.translation)); + let visible_bounds = self.viewport.intersection(&(bounds + self.translation)); self.strategy.feed(Candidate::Scrollable { id, @@ -215,12 +200,7 @@ where self.viewport = visible_bounds.unwrap_or_default(); } - fn text_input( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn TextInput, - ) { + fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) { if self.strategy.is_done() { return; } @@ -228,9 +208,7 @@ where self.strategy.feed(Candidate::TextInput { id, bounds, - visible_bounds: self - .viewport - .intersection(&(bounds + self.translation)), + visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } @@ -243,19 +221,12 @@ where self.strategy.feed(Candidate::Text { id, bounds, - visible_bounds: self - .viewport - .intersection(&(bounds + self.translation)), + visible_bounds: self.viewport.intersection(&(bounds + self.translation)), content: text, }); } - fn custom( - &mut self, - id: Option<&Id>, - bounds: Rectangle, - state: &mut dyn Any, - ) { + fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) { if self.strategy.is_done() { return; } @@ -263,9 +234,7 @@ where self.strategy.feed(Candidate::Custom { id, bounds, - visible_bounds: self - .viewport - .intersection(&(bounds + self.translation)), + visible_bounds: self.viewport.intersection(&(bounds + self.translation)), state, }); } diff --git a/selector/src/target.rs b/selector/src/target.rs index d2d2065176..97d8d628c0 100644 --- a/selector/src/target.rs +++ b/selector/src/target.rs @@ -274,8 +274,9 @@ impl Text { /// Returns the visible bounds of the [`Text`], in screen coordinates. pub fn visible_bounds(&self) -> Option { match self { - Text::Raw { visible_bounds, .. } - | Text::Input { visible_bounds, .. } => *visible_bounds, + Text::Raw { visible_bounds, .. } | Text::Input { visible_bounds, .. } => { + *visible_bounds + } } } } diff --git a/src/application.rs b/src/application.rs index cefea7b351..3081c0429b 100644 --- a/src/application.rs +++ b/src/application.rs @@ -37,8 +37,7 @@ use crate::theme; use crate::shell; use crate::window; use crate::{ - Element, Executor, Font, Never, Preset, Result, Settings, Size, - Subscription, Theme, message, + Element, Executor, Font, Never, Preset, Result, Settings, Size, Subscription, Theme, message, program::{self, Program}, task::Task, }; @@ -355,13 +354,9 @@ impl Application