Merge branch 'iced-rs-master' into viewer_content_fit

This commit is contained in:
gigas002 2024-05-08 19:16:20 +09:00
commit ff26fb7df4
120 changed files with 4104 additions and 2129 deletions

View file

@ -17,8 +17,6 @@ jobs:
run: cargo build --package tour --target wasm32-unknown-unknown run: cargo build --package tour --target wasm32-unknown-unknown
- name: Check compilation of `todos` example - name: Check compilation of `todos` example
run: cargo build --package todos --target wasm32-unknown-unknown run: cargo build --package todos --target wasm32-unknown-unknown
- name: Check compilation of `integration` example
run: cargo build --package integration --target wasm32-unknown-unknown
widget: widget:
runs-on: ubuntu-latest runs-on: ubuntu-latest

View file

@ -27,6 +27,8 @@ jobs:
-p iced -p iced
- name: Write CNAME file - name: Write CNAME file
run: echo 'docs.iced.rs' > ./target/doc/CNAME run: echo 'docs.iced.rs' > ./target/doc/CNAME
- name: Copy redirect file as index.html
run: cp docs/redirect.html target/doc/index.html
- name: Publish documentation - name: Publish documentation
if: github.ref == 'refs/heads/master' if: github.ref == 'refs/heads/master'
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v3

View file

@ -137,6 +137,7 @@ iced_winit = { version = "0.13.0-dev", path = "winit" }
async-std = "1.0" async-std = "1.0"
bitflags = "2.0" bitflags = "2.0"
bytemuck = { version = "1.0", features = ["derive"] } bytemuck = { version = "1.0", features = ["derive"] }
bytes = "1.6"
cosmic-text = "0.10" cosmic-text = "0.10"
dark-light = "1.0" dark-light = "1.0"
futures = "0.3" futures = "0.3"
@ -171,11 +172,11 @@ unicode-segmentation = "1.0"
wasm-bindgen-futures = "0.4" wasm-bindgen-futures = "0.4"
wasm-timer = "0.2" wasm-timer = "0.2"
web-sys = "=0.3.67" web-sys = "=0.3.67"
web-time = "0.2" web-time = "1.1"
wgpu = "0.19" wgpu = "0.19"
winapi = "0.3" winapi = "0.3"
window_clipboard = "0.4.1" window_clipboard = "0.4.1"
winit = { git = "https://github.com/iced-rs/winit.git", rev = "592bd152f6d5786fae7d918532d7db752c0d164f" } winit = { git = "https://github.com/iced-rs/winit.git", rev = "8affa522bc6dcc497d332a28c03491d22a22f5a7" }
[workspace.lints.rust] [workspace.lints.rust]
rust_2018_idioms = "forbid" rust_2018_idioms = "forbid"

View file

@ -3,7 +3,7 @@ use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use iced::alignment; use iced::alignment;
use iced::mouse; use iced::mouse;
use iced::widget::{canvas, text}; use iced::widget::{canvas, stack, text};
use iced::{ use iced::{
Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Theme, Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Theme,
}; };
@ -16,6 +16,13 @@ criterion_group!(benches, wgpu_benchmark);
pub fn wgpu_benchmark(c: &mut Criterion) { pub fn wgpu_benchmark(c: &mut Criterion) {
c.bench_function("wgpu — canvas (light)", |b| benchmark(b, scene(10))); c.bench_function("wgpu — canvas (light)", |b| benchmark(b, scene(10)));
c.bench_function("wgpu — canvas (heavy)", |b| benchmark(b, scene(1_000))); c.bench_function("wgpu — canvas (heavy)", |b| benchmark(b, scene(1_000)));
c.bench_function("wgpu - layered text (light)", |b| {
benchmark(b, layered_text(10));
});
c.bench_function("wgpu - layered text (heavy)", |b| {
benchmark(b, layered_text(1_000));
});
} }
fn benchmark( fn benchmark(
@ -63,7 +70,8 @@ fn benchmark(
Some(Antialiasing::MSAAx4), Some(Antialiasing::MSAAx4),
); );
let mut renderer = Renderer::new(&engine, Font::DEFAULT, Pixels::from(16)); let mut renderer =
Renderer::new(&device, &engine, Font::DEFAULT, Pixels::from(16));
let viewport = let viewport =
graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0); graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0);
@ -125,52 +133,59 @@ fn benchmark(
}); });
} }
fn scene<'a, Message: 'a, Theme: 'a>( fn scene<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> {
n: usize, struct Scene {
) -> Element<'a, Message, Theme, Renderer> { n: usize,
}
impl<Message, Theme> canvas::Program<Message, Theme, Renderer> for Scene {
type State = canvas::Cache<Renderer>;
fn draw(
&self,
cache: &Self::State,
renderer: &Renderer,
_theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry<Renderer>> {
vec![cache.draw(renderer, bounds.size(), |frame| {
for i in 0..self.n {
frame.fill_rectangle(
Point::new(0.0, i as f32),
Size::new(10.0, 10.0),
Color::WHITE,
);
}
for i in 0..self.n {
frame.fill_text(canvas::Text {
content: i.to_string(),
position: Point::new(0.0, i as f32),
color: Color::BLACK,
size: Pixels::from(16),
line_height: text::LineHeight::default(),
font: Font::DEFAULT,
horizontal_alignment: alignment::Horizontal::Left,
vertical_alignment: alignment::Vertical::Top,
shaping: text::Shaping::Basic,
});
}
})]
}
}
canvas(Scene { n }) canvas(Scene { n })
.width(Length::Fill) .width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.into() .into()
} }
struct Scene { fn layered_text<'a, Message: 'a>(
n: usize, n: usize,
} ) -> Element<'a, Message, Theme, Renderer> {
stack((0..n).map(|i| text(format!("I am paragraph {i}!")).into()))
impl<Message, Theme> canvas::Program<Message, Theme, Renderer> for Scene { .width(Length::Fill)
type State = canvas::Cache<Renderer>; .height(Length::Fill)
.into()
fn draw(
&self,
cache: &Self::State,
renderer: &Renderer,
_theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry<Renderer>> {
vec![cache.draw(renderer, bounds.size(), |frame| {
for i in 0..self.n {
frame.fill_rectangle(
Point::new(0.0, i as f32),
Size::new(10.0, 10.0),
Color::WHITE,
);
}
for i in 0..self.n {
frame.fill_text(canvas::Text {
content: i.to_string(),
position: Point::new(0.0, i as f32),
color: Color::BLACK,
size: Pixels::from(16),
line_height: text::LineHeight::default(),
font: Font::DEFAULT,
horizontal_alignment: alignment::Horizontal::Left,
vertical_alignment: alignment::Vertical::Top,
shaping: text::Shaping::Basic,
});
}
})]
}
} }

View file

@ -19,6 +19,7 @@ advanced = []
[dependencies] [dependencies]
bitflags.workspace = true bitflags.workspace = true
bytes.workspace = true
glam.workspace = true glam.workspace = true
log.workspace = true log.workspace = true
num-traits.workspace = true num-traits.workspace = true

View file

@ -1,12 +1,17 @@
use crate::{Point, Rectangle, Vector}; use crate::{Point, Rectangle, Vector};
use std::f32::consts::{FRAC_PI_2, PI}; use std::f32::consts::{FRAC_PI_2, PI};
use std::ops::{Add, AddAssign, Div, Mul, RangeInclusive, Sub, SubAssign}; use std::ops::{Add, AddAssign, Div, Mul, RangeInclusive, Rem, Sub, SubAssign};
/// Degrees /// Degrees
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Degrees(pub f32); pub struct Degrees(pub f32);
impl Degrees {
/// The range of degrees of a circle.
pub const RANGE: RangeInclusive<Self> = Self(0.0)..=Self(360.0);
}
impl PartialEq<f32> for Degrees { impl PartialEq<f32> for Degrees {
fn eq(&self, other: &f32) -> bool { fn eq(&self, other: &f32) -> bool {
self.0.eq(other) self.0.eq(other)
@ -19,6 +24,52 @@ impl PartialOrd<f32> for Degrees {
} }
} }
impl From<f32> for Degrees {
fn from(degrees: f32) -> Self {
Self(degrees)
}
}
impl From<u8> for Degrees {
fn from(degrees: u8) -> Self {
Self(f32::from(degrees))
}
}
impl From<Degrees> for f32 {
fn from(degrees: Degrees) -> Self {
degrees.0
}
}
impl From<Degrees> for f64 {
fn from(degrees: Degrees) -> Self {
Self::from(degrees.0)
}
}
impl Mul<f32> for Degrees {
type Output = Degrees;
fn mul(self, rhs: f32) -> Self::Output {
Self(self.0 * rhs)
}
}
impl num_traits::FromPrimitive for Degrees {
fn from_i64(n: i64) -> Option<Self> {
Some(Self(n as f32))
}
fn from_u64(n: u64) -> Option<Self> {
Some(Self(n as f32))
}
fn from_f64(n: f64) -> Option<Self> {
Some(Self(n as f32))
}
}
/// Radians /// Radians
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Radians(pub f32); pub struct Radians(pub f32);
@ -65,6 +116,12 @@ impl From<u8> for Radians {
} }
} }
impl From<Radians> for f32 {
fn from(radians: Radians) -> Self {
radians.0
}
}
impl From<Radians> for f64 { impl From<Radians> for f64 {
fn from(radians: Radians) -> Self { fn from(radians: Radians) -> Self {
Self::from(radians.0) Self::from(radians.0)
@ -107,6 +164,14 @@ impl Add for Radians {
} }
} }
impl Add<Degrees> for Radians {
type Output = Self;
fn add(self, rhs: Degrees) -> Self::Output {
Self(self.0 + rhs.0.to_radians())
}
}
impl AddAssign for Radians { impl AddAssign for Radians {
fn add_assign(&mut self, rhs: Radians) { fn add_assign(&mut self, rhs: Radians) {
self.0 = self.0 + rhs.0; self.0 = self.0 + rhs.0;
@ -153,6 +218,14 @@ impl Div for Radians {
} }
} }
impl Rem for Radians {
type Output = Self;
fn rem(self, rhs: Self) -> Self::Output {
Self(self.0 % rhs.0)
}
}
impl PartialEq<f32> for Radians { impl PartialEq<f32> for Radians {
fn eq(&self, other: &f32) -> bool { fn eq(&self, other: &f32) -> bool {
self.0.eq(other) self.0.eq(other)

View file

@ -1,6 +1,8 @@
//! Control the fit of some content (like an image) within a space. //! Control the fit of some content (like an image) within a space.
use crate::Size; use crate::Size;
use std::fmt;
/// The strategy used to fit the contents of a widget to its bounding box. /// The strategy used to fit the contents of a widget to its bounding box.
/// ///
/// Each variant of this enum is a strategy that can be applied for resolving /// Each variant of this enum is a strategy that can be applied for resolving
@ -11,7 +13,7 @@ use crate::Size;
/// in CSS, see [Mozilla's docs][1], or run the `tour` example /// in CSS, see [Mozilla's docs][1], or run the `tour` example
/// ///
/// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit /// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContentFit { pub enum ContentFit {
/// Scale as big as it can be without needing to crop or hide parts. /// Scale as big as it can be without needing to crop or hide parts.
/// ///
@ -23,6 +25,7 @@ pub enum ContentFit {
/// This is a great fit for when you need to display an image without losing /// This is a great fit for when you need to display an image without losing
/// any part of it, particularly when the image itself is the focus of the /// any part of it, particularly when the image itself is the focus of the
/// screen. /// screen.
#[default]
Contain, Contain,
/// Scale the image to cover all of the bounding box, cropping if needed. /// Scale the image to cover all of the bounding box, cropping if needed.
@ -117,3 +120,15 @@ impl ContentFit {
} }
} }
} }
impl fmt::Display for ContentFit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
ContentFit::Contain => "Contain",
ContentFit::Cover => "Cover",
ContentFit::Fill => "Fill",
ContentFit::None => "None",
ContentFit::ScaleDown => "Scale Down",
})
}
}

View file

@ -1,16 +1,45 @@
//! Load and draw raster graphics. //! Load and draw raster graphics.
use crate::{Rectangle, Size}; pub use bytes::Bytes;
use crate::{Radians, Rectangle, Size};
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
use std::hash::{Hash, Hasher as _}; use std::hash::{Hash, Hasher};
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::Arc;
/// A handle of some image data. /// A handle of some image data.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Clone, PartialEq, Eq)]
pub struct Handle { pub enum Handle {
id: u64, /// A file handle. The image data will be read
data: Data, /// from the file path.
///
/// Use [`from_path`] to create this variant.
///
/// [`from_path`]: Self::from_path
Path(Id, PathBuf),
/// A handle pointing to some encoded image bytes in-memory.
///
/// Use [`from_bytes`] to create this variant.
///
/// [`from_bytes`]: Self::from_bytes
Bytes(Id, Bytes),
/// A handle pointing to decoded image pixels in RGBA format.
///
/// Use [`from_rgba`] to create this variant.
///
/// [`from_rgba`]: Self::from_rgba
Rgba {
/// The id of this handle.
id: Id,
/// The width of the image.
width: u32,
/// The height of the image.
height: u32,
/// The pixels.
pixels: Bytes,
},
} }
impl Handle { impl Handle {
@ -18,56 +47,48 @@ impl Handle {
/// ///
/// Makes an educated guess about the image format by examining the data in the file. /// Makes an educated guess about the image format by examining the data in the file.
pub fn from_path<T: Into<PathBuf>>(path: T) -> Handle { pub fn from_path<T: Into<PathBuf>>(path: T) -> Handle {
Self::from_data(Data::Path(path.into())) let path = path.into();
Self::Path(Id::path(&path), path)
} }
/// Creates an image [`Handle`] containing the image pixels directly. This /// Creates an image [`Handle`] containing the encoded image data directly.
/// function expects the input data to be provided as a `Vec<u8>` of RGBA
/// pixels.
///
/// This is useful if you have already decoded your image.
pub fn from_pixels(
width: u32,
height: u32,
pixels: impl AsRef<[u8]> + Send + Sync + 'static,
) -> Handle {
Self::from_data(Data::Rgba {
width,
height,
pixels: Bytes::new(pixels),
})
}
/// Creates an image [`Handle`] containing the image data directly.
/// ///
/// Makes an educated guess about the image format by examining the given data. /// Makes an educated guess about the image format by examining the given data.
/// ///
/// This is useful if you already have your image loaded in-memory, maybe /// This is useful if you already have your image loaded in-memory, maybe
/// because you downloaded or generated it procedurally. /// because you downloaded or generated it procedurally.
pub fn from_memory( pub fn from_bytes(bytes: impl Into<Bytes>) -> Handle {
bytes: impl AsRef<[u8]> + Send + Sync + 'static, Self::Bytes(Id::unique(), bytes.into())
) -> Handle {
Self::from_data(Data::Bytes(Bytes::new(bytes)))
} }
fn from_data(data: Data) -> Handle { /// Creates an image [`Handle`] containing the decoded image pixels directly.
let mut hasher = FxHasher::default(); ///
data.hash(&mut hasher); /// This function expects the pixel data to be provided as a collection of [`Bytes`]
/// of RGBA pixels. Therefore, the length of the pixel data should always be
Handle { /// `width * height * 4`.
id: hasher.finish(), ///
data, /// This is useful if you have already decoded your image.
pub fn from_rgba(
width: u32,
height: u32,
pixels: impl Into<Bytes>,
) -> Handle {
Self::Rgba {
id: Id::unique(),
width,
height,
pixels: pixels.into(),
} }
} }
/// Returns the unique identifier of the [`Handle`]. /// Returns the unique identifier of the [`Handle`].
pub fn id(&self) -> u64 { pub fn id(&self) -> Id {
self.id match self {
} Handle::Path(id, _)
| Handle::Bytes(id, _)
/// Returns a reference to the image [`Data`]. | Handle::Rgba { id, .. } => *id,
pub fn data(&self) -> &Data { }
&self.data
} }
} }
@ -80,93 +101,49 @@ where
} }
} }
impl Hash for Handle { impl std::fmt::Debug for Handle {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
/// A wrapper around raw image data.
///
/// It behaves like a `&[u8]`.
#[derive(Clone)]
pub struct Bytes(Arc<dyn AsRef<[u8]> + Send + Sync + 'static>);
impl Bytes {
/// Creates new [`Bytes`] around `data`.
pub fn new(data: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
Self(Arc::new(data))
}
}
impl std::fmt::Debug for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.as_ref().as_ref().fmt(f)
}
}
impl std::hash::Hash for Bytes {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.as_ref().as_ref().hash(state);
}
}
impl PartialEq for Bytes {
fn eq(&self, other: &Self) -> bool {
let a = self.as_ref();
let b = other.as_ref();
core::ptr::eq(a, b) || a == b
}
}
impl Eq for Bytes {}
impl AsRef<[u8]> for Bytes {
fn as_ref(&self) -> &[u8] {
self.0.as_ref().as_ref()
}
}
impl std::ops::Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0.as_ref().as_ref()
}
}
/// The data of a raster image.
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Data {
/// File data
Path(PathBuf),
/// In-memory data
Bytes(Bytes),
/// Decoded image pixels in RGBA format.
Rgba {
/// The width of the image.
width: u32,
/// The height of the image.
height: u32,
/// The pixels.
pixels: Bytes,
},
}
impl std::fmt::Debug for Data {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Data::Path(path) => write!(f, "Path({path:?})"), Self::Path(_, path) => write!(f, "Path({path:?})"),
Data::Bytes(_) => write!(f, "Bytes(...)"), Self::Bytes(_, _) => write!(f, "Bytes(...)"),
Data::Rgba { width, height, .. } => { Self::Rgba { width, height, .. } => {
write!(f, "Pixels({width} * {height})") write!(f, "Pixels({width} * {height})")
} }
} }
} }
} }
/// The unique identifier of some [`Handle`] data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id(_Id);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum _Id {
Unique(u64),
Hash(u64),
}
impl Id {
fn unique() -> Self {
use std::sync::atomic::{self, AtomicU64};
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
Self(_Id::Unique(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)))
}
fn path(path: impl AsRef<Path>) -> Self {
let hash = {
let mut hasher = FxHasher::default();
path.as_ref().hash(&mut hasher);
hasher.finish()
};
Self(_Id::Hash(hash))
}
}
/// Image filtering strategy. /// Image filtering strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FilterMethod { pub enum FilterMethod {
@ -184,7 +161,7 @@ pub trait Renderer: crate::Renderer {
/// The image Handle to be displayed. Iced exposes its own default implementation of a [`Handle`] /// The image Handle to be displayed. Iced exposes its own default implementation of a [`Handle`]
/// ///
/// [`Handle`]: Self::Handle /// [`Handle`]: Self::Handle
type Handle: Clone + Hash; type Handle: Clone;
/// Returns the dimensions of an image for the given [`Handle`]. /// Returns the dimensions of an image for the given [`Handle`].
fn measure_image(&self, handle: &Self::Handle) -> Size<u32>; fn measure_image(&self, handle: &Self::Handle) -> Size<u32>;
@ -196,5 +173,7 @@ pub trait Renderer: crate::Renderer {
handle: Self::Handle, handle: Self::Handle,
filter_method: FilterMethod, filter_method: FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians,
opacity: f32,
); );
} }

View file

@ -54,7 +54,7 @@ impl<'a> Layout<'a> {
} }
/// Returns an iterator over the [`Layout`] of the children of a [`Node`]. /// Returns an iterator over the [`Layout`] of the children of a [`Node`].
pub fn children(self) -> impl Iterator<Item = Layout<'a>> { pub fn children(self) -> impl DoubleEndedIterator<Item = Layout<'a>> {
self.node.children().iter().map(move |node| { self.node.children().iter().map(move |node| {
Layout::with_offset( Layout::with_offset(
Vector::new(self.position.x, self.position.y), Vector::new(self.position.x, self.position.y),

View file

@ -39,6 +39,7 @@ mod padding;
mod pixels; mod pixels;
mod point; mod point;
mod rectangle; mod rectangle;
mod rotation;
mod shadow; mod shadow;
mod shell; mod shell;
mod size; mod size;
@ -64,6 +65,7 @@ pub use pixels::Pixels;
pub use point::Point; pub use point::Point;
pub use rectangle::Rectangle; pub use rectangle::Rectangle;
pub use renderer::Renderer; pub use renderer::Renderer;
pub use rotation::Rotation;
pub use shadow::Shadow; pub use shadow::Shadow;
pub use shell::Shell; pub use shell::Shell;
pub use size::Size; pub use size::Size;

View file

@ -3,6 +3,7 @@
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum Interaction { pub enum Interaction {
#[default] #[default]
None,
Idle, Idle,
Pointer, Pointer,
Grab, Grab,

View file

@ -79,7 +79,7 @@ where
_viewport: &Rectangle, _viewport: &Rectangle,
_renderer: &Renderer, _renderer: &Renderer,
) -> mouse::Interaction { ) -> mouse::Interaction {
mouse::Interaction::Idle mouse::Interaction::None
} }
/// Returns true if the cursor is over the [`Overlay`]. /// Returns true if the cursor is over the [`Overlay`].

View file

@ -1,6 +1,6 @@
use crate::{Point, Size, Vector}; use crate::{Point, Radians, Size, Vector};
/// A rectangle. /// An axis-aligned rectangle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Rectangle<T = f32> { pub struct Rectangle<T = f32> {
/// X coordinate of the top-left corner. /// X coordinate of the top-left corner.
@ -172,6 +172,18 @@ impl Rectangle<f32> {
height: self.height + amount * 2.0, height: self.height + amount * 2.0,
} }
} }
/// Rotates the [`Rectangle`] and returns the smallest [`Rectangle`]
/// containing it.
pub fn rotate(self, rotation: Radians) -> Self {
let size = self.size().rotate(rotation);
let position = Point::new(
self.center_x() - size.width / 2.0,
self.center_y() - size.height / 2.0,
);
Self::new(position, size)
}
} }
impl std::ops::Mul<f32> for Rectangle<f32> { impl std::ops::Mul<f32> for Rectangle<f32> {
@ -227,3 +239,19 @@ where
} }
} }
} }
impl<T> std::ops::Mul<Vector<T>> for Rectangle<T>
where
T: std::ops::Mul<Output = T> + Copy,
{
type Output = Rectangle<T>;
fn mul(self, scale: Vector<T>) -> Self {
Rectangle {
x: self.x * scale.x,
y: self.y * scale.y,
width: self.width * scale.x,
height: self.height * scale.y,
}
}
}

View file

@ -4,7 +4,8 @@ use crate::renderer::{self, Renderer};
use crate::svg; use crate::svg;
use crate::text::{self, Text}; use crate::text::{self, Text};
use crate::{ use crate::{
Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, Background, Color, Font, Pixels, Point, Radians, Rectangle, Size,
Transformation,
}; };
impl Renderer for () { impl Renderer for () {
@ -171,6 +172,8 @@ impl image::Renderer for () {
_handle: Self::Handle, _handle: Self::Handle,
_filter_method: image::FilterMethod, _filter_method: image::FilterMethod,
_bounds: Rectangle, _bounds: Rectangle,
_rotation: Radians,
_opacity: f32,
) { ) {
} }
} }
@ -185,6 +188,8 @@ impl svg::Renderer for () {
_handle: svg::Handle, _handle: svg::Handle,
_color: Option<Color>, _color: Option<Color>,
_bounds: Rectangle, _bounds: Rectangle,
_rotation: Radians,
_opacity: f32,
) { ) {
} }
} }

72
core/src/rotation.rs Normal file
View file

@ -0,0 +1,72 @@
//! Control the rotation of some content (like an image) within a space.
use crate::{Degrees, Radians, Size};
/// The strategy used to rotate the content.
///
/// This is used to control the behavior of the layout when the content is rotated
/// by a certain angle.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Rotation {
/// The element will float while rotating. The layout will be kept exactly as it was
/// before the rotation.
///
/// This is especially useful when used for animations, as it will avoid the
/// layout being shifted or resized when smoothly i.e. an icon.
///
/// This is the default.
Floating(Radians),
/// The element will be solid while rotating. The layout will be adjusted to fit
/// the rotated content.
///
/// This allows you to rotate an image and have the layout adjust to fit the new
/// size of the image.
Solid(Radians),
}
impl Rotation {
/// Returns the angle of the [`Rotation`] in [`Radians`].
pub fn radians(self) -> Radians {
match self {
Rotation::Floating(radians) | Rotation::Solid(radians) => radians,
}
}
/// Returns a mutable reference to the angle of the [`Rotation`] in [`Radians`].
pub fn radians_mut(&mut self) -> &mut Radians {
match self {
Rotation::Floating(radians) | Rotation::Solid(radians) => radians,
}
}
/// Returns the angle of the [`Rotation`] in [`Degrees`].
pub fn degrees(self) -> Degrees {
Degrees(self.radians().0.to_degrees())
}
/// Applies the [`Rotation`] to the given [`Size`], returning
/// the minimum [`Size`] containing the rotated one.
pub fn apply(self, size: Size) -> Size {
match self {
Self::Floating(_) => size,
Self::Solid(rotation) => size.rotate(rotation),
}
}
}
impl Default for Rotation {
fn default() -> Self {
Self::Floating(Radians(0.0))
}
}
impl From<Radians> for Rotation {
fn from(radians: Radians) -> Self {
Self::Floating(radians)
}
}
impl From<f32> for Rotation {
fn from(radians: f32) -> Self {
Self::Floating(Radians(radians))
}
}

View file

@ -1,4 +1,4 @@
use crate::Vector; use crate::{Radians, Vector};
/// An amount of space in 2 dimensions. /// An amount of space in 2 dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
@ -51,6 +51,19 @@ impl Size {
height: self.height + other.height, height: self.height + other.height,
} }
} }
/// Rotates the given [`Size`] and returns the minimum [`Size`]
/// containing it.
pub fn rotate(self, rotation: Radians) -> Size {
let radians = f32::from(rotation);
Size {
width: (self.width * radians.cos()).abs()
+ (self.height * radians.sin()).abs(),
height: (self.width * radians.sin()).abs()
+ (self.height * radians.cos()).abs(),
}
}
} }
impl<T> From<[T; 2]> for Size<T> { impl<T> From<[T; 2]> for Size<T> {
@ -113,3 +126,17 @@ where
} }
} }
} }
impl<T> std::ops::Mul<Vector<T>> for Size<T>
where
T: std::ops::Mul<Output = T> + Copy,
{
type Output = Size<T>;
fn mul(self, scale: Vector<T>) -> Self::Output {
Size {
width: self.width * scale.x,
height: self.height * scale.y,
}
}
}

View file

@ -1,5 +1,5 @@
//! Load and draw vector graphics. //! Load and draw vector graphics.
use crate::{Color, Rectangle, Size}; use crate::{Color, Radians, Rectangle, Size};
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
use std::borrow::Cow; use std::borrow::Cow;
@ -100,5 +100,7 @@ pub trait Renderer: crate::Renderer {
handle: Handle, handle: Handle,
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians,
opacity: f32,
); );
} }

View file

@ -18,6 +18,9 @@ impl<T> Vector<T> {
impl Vector { impl Vector {
/// The zero [`Vector`]. /// The zero [`Vector`].
pub const ZERO: Self = Self::new(0.0, 0.0); pub const ZERO: Self = Self::new(0.0, 0.0);
/// The unit [`Vector`].
pub const UNIT: Self = Self::new(0.0, 0.0);
} }
impl<T> std::ops::Add for Vector<T> impl<T> std::ops::Add for Vector<T>

View file

@ -137,7 +137,7 @@ where
_viewport: &Rectangle, _viewport: &Rectangle,
_renderer: &Renderer, _renderer: &Renderer,
) -> mouse::Interaction { ) -> mouse::Interaction {
mouse::Interaction::Idle mouse::Interaction::None
} }
/// Returns the overlay of the [`Widget`], if there is any. /// Returns the overlay of the [`Widget`], if there is any.

13
docs/redirect.html Normal file
View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redirecting...</title>
<meta http-equiv="refresh" content="0; URL='/iced/'" />
</head>
<body>
<p>If you are not redirected automatically, follow this <a href="/iced/">link</a>.</p>
</body>
</html>

View file

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

View file

@ -1,5 +1,5 @@
use iced::widget::{checkbox, column, container, row, text}; use iced::widget::{center, checkbox, column, row, text};
use iced::{Element, Font, Length}; use iced::{Element, Font};
const ICON_FONT: Font = Font::with_name("icons"); const ICON_FONT: Font = Font::with_name("icons");
@ -68,11 +68,6 @@ impl Example {
let content = let content =
column![default_checkbox, checkboxes, custom_checkbox].spacing(20); column![default_checkbox, checkboxes, custom_checkbox].spacing(20);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

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

View file

@ -8,6 +8,8 @@ use iced::{
}; };
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
tracing_subscriber::fmt::init();
iced::program("Clock - Iced", Clock::update, Clock::view) iced::program("Clock - Iced", Clock::update, Clock::view)
.subscription(Clock::subscription) .subscription(Clock::subscription)
.theme(Clock::theme) .theme(Clock::theme)

View file

@ -1,5 +1,5 @@
use iced::widget::{ use iced::widget::{
column, combo_box, container, scrollable, text, vertical_space, center, column, combo_box, scrollable, text, vertical_space,
}; };
use iced::{Alignment, Element, Length}; use iced::{Alignment, Element, Length};
@ -68,12 +68,7 @@ impl Example {
.align_items(Alignment::Center) .align_items(Alignment::Center)
.spacing(10); .spacing(10);
container(scrollable(content)) center(scrollable(content)).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -1,5 +1,5 @@
use iced::widget::container; use iced::widget::center;
use iced::{Element, Length}; use iced::Element;
use numeric_input::numeric_input; use numeric_input::numeric_input;
@ -27,10 +27,8 @@ impl Component {
} }
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {
container(numeric_input(self.value, Message::NumericInputChanged)) center(numeric_input(self.value, Message::NumericInputChanged))
.padding(20) .padding(20)
.height(Length::Fill)
.center_y()
.into() .into()
} }
} }

View file

@ -81,8 +81,8 @@ mod quad {
} }
} }
use iced::widget::{column, container, slider, text}; use iced::widget::{center, column, slider, text};
use iced::{Alignment, Color, Element, Length, Shadow, Vector}; use iced::{Alignment, Color, Element, Shadow, Vector};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::run("Custom Quad - Iced", Example::update, Example::view) iced::run("Custom Quad - Iced", Example::update, Example::view)
@ -187,12 +187,7 @@ impl Example {
.max_width(500) .max_width(500)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -4,7 +4,7 @@ use scene::Scene;
use iced::time::Instant; use iced::time::Instant;
use iced::widget::shader::wgpu; use iced::widget::shader::wgpu;
use iced::widget::{checkbox, column, container, row, shader, slider, text}; use iced::widget::{center, checkbox, column, row, shader, slider, text};
use iced::window; use iced::window;
use iced::{Alignment, Color, Element, Length, Subscription}; use iced::{Alignment, Color, Element, Length, Subscription};
@ -123,12 +123,7 @@ impl IcedCubes {
let shader = let shader =
shader(&self.scene).width(Length::Fill).height(Length::Fill); shader(&self.scene).width(Length::Fill).height(Length::Fill);
container(column![shader, controls].align_items(Alignment::Center)) center(column![shader, controls].align_items(Alignment::Center)).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {

View file

@ -82,8 +82,8 @@ mod circle {
} }
use circle::circle; use circle::circle;
use iced::widget::{column, container, slider, text}; use iced::widget::{center, column, slider, text};
use iced::{Alignment, Element, Length}; use iced::{Alignment, Element};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::run("Custom Widget - Iced", Example::update, Example::view) iced::run("Custom Widget - Iced", Example::update, Example::view)
@ -122,12 +122,7 @@ impl Example {
.max_width(500) .max_width(500)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -1,7 +1,7 @@
mod download; mod download;
use iced::widget::{button, column, container, progress_bar, text, Column}; use iced::widget::{button, center, column, progress_bar, text, Column};
use iced::{Alignment, Element, Length, Subscription}; use iced::{Alignment, Element, Subscription};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("Download Progress - Iced", Example::update, Example::view) iced::program("Download Progress - Iced", Example::update, Example::view)
@ -67,13 +67,7 @@ impl Example {
.spacing(20) .spacing(20)
.align_items(Alignment::End); .align_items(Alignment::End);
container(downloads) center(downloads).padding(20).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.padding(20)
.into()
} }
} }

View file

@ -277,7 +277,7 @@ fn action<'a, Message: Clone + 'a>(
label: &'a str, label: &'a str,
on_press: Option<Message>, on_press: Option<Message>,
) -> Element<'a, Message> { ) -> Element<'a, Message> {
let action = button(container(content).width(30).center_x()); let action = button(container(content).center_x().width(30));
if let Some(on_press) = on_press { if let Some(on_press) = on_press {
tooltip( tooltip(

View file

@ -1,6 +1,6 @@
use iced::alignment; use iced::alignment;
use iced::event::{self, Event}; use iced::event::{self, Event};
use iced::widget::{button, checkbox, container, text, Column}; use iced::widget::{button, center, checkbox, text, Column};
use iced::window; use iced::window;
use iced::{Alignment, Command, Element, Length, Subscription}; use iced::{Alignment, Command, Element, Length, Subscription};
@ -84,11 +84,6 @@ impl Events {
.push(toggle) .push(toggle)
.push(exit); .push(exit);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -1,6 +1,6 @@
use iced::widget::{button, column, container}; use iced::widget::{button, center, column};
use iced::window; use iced::window;
use iced::{Alignment, Command, Element, Length}; use iced::{Alignment, Command, Element};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("Exit - Iced", Exit::update, Exit::view).run() iced::program("Exit - Iced", Exit::update, Exit::view).run()
@ -46,12 +46,6 @@ impl Exit {
.spacing(10) .spacing(10)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(content) center(content).padding(20).into()
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
} }
} }

View file

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

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

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

View file

@ -153,7 +153,7 @@ mod rainbow {
} }
use iced::widget::{column, container, scrollable}; use iced::widget::{column, container, scrollable};
use iced::{Element, Length}; use iced::Element;
use rainbow::rainbow; use rainbow::rainbow;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -176,12 +176,7 @@ fn view(_state: &()) -> Element<'_, ()> {
.spacing(20) .spacing(20)
.max_width(500); .max_width(500);
let scrollable = let scrollable = scrollable(container(content).center_x());
scrollable(container(content).width(Length::Fill).center_x());
container(scrollable) container(scrollable).center_y().into()
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.into()
} }

View file

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

View file

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

View file

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

View file

@ -1,8 +1,8 @@
use iced::keyboard; use iced::keyboard;
use iced::mouse; use iced::mouse;
use iced::widget::{ use iced::widget::{
button, canvas, checkbox, column, container, horizontal_space, pick_list, button, canvas, center, checkbox, column, container, horizontal_space,
row, scrollable, text, pick_list, row, scrollable, text,
}; };
use iced::{ use iced::{
color, Alignment, Element, Font, Length, Point, Rectangle, Renderer, color, Alignment, Element, Font, Length, Point, Rectangle, Renderer,
@ -76,7 +76,7 @@ impl Layout {
.spacing(20) .spacing(20)
.align_items(Alignment::Center); .align_items(Alignment::Center);
let example = container(if self.explain { let example = center(if self.explain {
self.example.view().explain(color!(0x0000ff)) self.example.view().explain(color!(0x0000ff))
} else { } else {
self.example.view() self.example.view()
@ -87,11 +87,7 @@ impl Layout {
container::Style::default() container::Style::default()
.with_border(palette.background.strong.color, 4.0) .with_border(palette.background.strong.color, 4.0)
}) })
.padding(4) .padding(4);
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y();
let controls = row([ let controls = row([
(!self.example.is_first()).then_some( (!self.example.is_first()).then_some(
@ -195,12 +191,7 @@ impl Default for Example {
} }
fn centered<'a>() -> Element<'a, Message> { fn centered<'a>() -> Element<'a, Message> {
container(text("I am centered!").size(50)) center(text("I am centered!").size(50)).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
fn column_<'a>() -> Element<'a, Message> { fn column_<'a>() -> Element<'a, Message> {
@ -260,7 +251,6 @@ fn application<'a>() -> Element<'a, Message> {
.align_items(Alignment::Center), .align_items(Alignment::Center),
) )
.style(container::rounded_box) .style(container::rounded_box)
.height(Length::Fill)
.center_y(); .center_y();
let content = container( let content = container(

View file

@ -1,5 +1,5 @@
use iced::widget::{column, container, row, slider, text}; use iced::widget::{center, column, row, slider, text};
use iced::{Element, Length}; use iced::Element;
use std::time::Duration; use std::time::Duration;
@ -73,7 +73,7 @@ impl LoadingSpinners {
}) })
.spacing(20); .spacing(20);
container( center(
column.push( column.push(
row![ row![
text("Cycle duration:"), text("Cycle duration:"),
@ -87,10 +87,6 @@ impl LoadingSpinners {
.spacing(20.0), .spacing(20.0),
), ),
) )
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into() .into()
} }
} }

View file

@ -1,5 +1,5 @@
use iced::widget::{button, column, container, text}; use iced::widget::{button, center, column, text};
use iced::{Alignment, Element, Length}; use iced::{Alignment, Element};
use loupe::loupe; use loupe::loupe;
@ -31,7 +31,7 @@ impl Loupe {
} }
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {
container(loupe( center(loupe(
3.0, 3.0,
column![ column![
button("Increment").on_press(Message::Increment), button("Increment").on_press(Message::Increment),
@ -41,10 +41,6 @@ impl Loupe {
.padding(20) .padding(20)
.align_items(Alignment::Center), .align_items(Alignment::Center),
)) ))
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into() .into()
} }
} }
@ -159,7 +155,7 @@ mod loupe {
if cursor.is_over(layout.bounds()) { if cursor.is_over(layout.bounds()) {
mouse::Interaction::ZoomIn mouse::Interaction::ZoomIn
} else { } else {
mouse::Interaction::Idle mouse::Interaction::None
} }
} }
} }

View file

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

View file

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

View file

@ -291,12 +291,7 @@ fn view_content<'a>(
.spacing(10) .spacing(10)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(scrollable(content)) container(scrollable(content)).center_y().padding(5).into()
.width(Length::Fill)
.height(Length::Fill)
.padding(5)
.center_y()
.into()
} }
fn view_controls<'a>( fn view_controls<'a>(

View file

@ -1,5 +1,5 @@
use iced::futures; use iced::futures;
use iced::widget::{self, column, container, image, row, text}; use iced::widget::{self, center, column, image, row, text};
use iced::{Alignment, Command, Element, Length}; use iced::{Alignment, Command, Element, Length};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -83,12 +83,7 @@ impl Pokedex {
.align_items(Alignment::End), .align_items(Alignment::End),
}; };
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }
@ -188,7 +183,7 @@ impl Pokemon {
{ {
let bytes = reqwest::get(&url).await?.bytes().await?; let bytes = reqwest::get(&url).await?.bytes().await?;
Ok(image::Handle::from_memory(bytes)) Ok(image::Handle::from_bytes(bytes))
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]

View file

@ -1,7 +1,5 @@
use iced::widget::{ use iced::widget::{center, column, pick_list, qr_code, row, text, text_input};
column, container, pick_list, qr_code, row, text, text_input, use iced::{Alignment, Element, Theme};
};
use iced::{Alignment, Element, Length, Theme};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program( iced::program(
@ -72,13 +70,7 @@ impl QRGenerator {
.spacing(20) .spacing(20)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(content) center(content).padding(20).into()
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
} }
fn theme(&self) -> Theme { fn theme(&self) -> Theme {

View file

@ -109,7 +109,7 @@ impl Example {
fn view(&self) -> Element<'_, Message> { fn view(&self) -> Element<'_, Message> {
let image: Element<Message> = if let Some(screenshot) = &self.screenshot let image: Element<Message> = if let Some(screenshot) = &self.screenshot
{ {
image(image::Handle::from_pixels( image(image::Handle::from_rgba(
screenshot.size.width, screenshot.size.width,
screenshot.size.height, screenshot.size.height,
screenshot.clone(), screenshot.clone(),
@ -123,12 +123,10 @@ impl Example {
}; };
let image = container(image) let image = container(image)
.center_y()
.padding(10) .padding(10)
.style(container::rounded_box) .style(container::rounded_box)
.width(Length::FillPortion(2)) .width(Length::FillPortion(2));
.height(Length::Fill)
.center_x()
.center_y();
let crop_origin_controls = row![ let crop_origin_controls = row![
text("X:") text("X:")
@ -213,12 +211,7 @@ impl Example {
.spacing(40) .spacing(40)
}; };
let side_content = container(controls) let side_content = container(controls).center_y();
.align_x(alignment::Horizontal::Center)
.width(Length::FillPortion(1))
.height(Length::Fill)
.center_y()
.center_x();
let content = row![side_content, image] let content = row![side_content, image]
.spacing(10) .spacing(10)
@ -226,13 +219,7 @@ impl Example {
.height(Length::Fill) .height(Length::Fill)
.align_items(Alignment::Center); .align_items(Alignment::Center);
container(content) container(content).padding(10).into()
.width(Length::Fill)
.height(Length::Fill)
.padding(10)
.center_x()
.center_y()
.into()
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {

View file

@ -327,7 +327,7 @@ impl ScrollableDemo {
.spacing(10) .spacing(10)
.into(); .into();
container(content).padding(20).center_x().center_y().into() container(content).padding(20).into()
} }
fn theme(&self) -> Theme { fn theme(&self) -> Theme {

View file

@ -1,5 +1,5 @@
use iced::widget::{column, container, slider, text, vertical_slider}; use iced::widget::{center, column, container, slider, text, vertical_slider};
use iced::{Element, Length}; use iced::Element;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::run("Slider - Iced", Slider::update, Slider::view) iced::run("Slider - Iced", Slider::update, Slider::view)
@ -54,18 +54,14 @@ impl Slider {
let text = text(self.value); let text = text(self.value);
container( center(
column![ column![
container(v_slider).width(Length::Fill).center_x(), container(v_slider).center_x(),
container(h_slider).width(Length::Fill).center_x(), container(h_slider).center_x(),
container(text).width(Length::Fill).center_x(), container(text).center_x()
] ]
.spacing(25), .spacing(25),
) )
.height(Length::Fill)
.width(Length::Fill)
.center_x()
.center_y()
.into() .into()
} }
} }

View file

@ -1,8 +1,8 @@
use iced::alignment; use iced::alignment;
use iced::keyboard; use iced::keyboard;
use iced::time; use iced::time;
use iced::widget::{button, column, container, row, text}; use iced::widget::{button, center, column, row, text};
use iced::{Alignment, Element, Length, Subscription, Theme}; use iced::{Alignment, Element, Subscription, Theme};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -128,12 +128,7 @@ impl Stopwatch {
.align_items(Alignment::Center) .align_items(Alignment::Center)
.spacing(20); .spacing(20);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
fn theme(&self) -> Theme { fn theme(&self) -> Theme {

View file

@ -1,7 +1,7 @@
use iced::widget::{ use iced::widget::{
button, checkbox, column, container, horizontal_rule, pick_list, button, center, checkbox, column, horizontal_rule, pick_list, progress_bar,
progress_bar, row, scrollable, slider, text, text_input, toggler, row, scrollable, slider, text, text_input, toggler, vertical_rule,
vertical_rule, vertical_space, vertical_space,
}; };
use iced::{Alignment, Element, Length, Theme}; use iced::{Alignment, Element, Length, Theme};
@ -106,12 +106,7 @@ impl Styling {
.padding(20) .padding(20)
.max_width(600); .max_width(600);
container(content) center(content).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
fn theme(&self) -> Theme { fn theme(&self) -> Theme {

View file

@ -1,4 +1,4 @@
use iced::widget::{checkbox, column, container, svg}; use iced::widget::{center, checkbox, column, container, svg};
use iced::{color, Element, Length}; use iced::{color, Element, Length};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -44,19 +44,12 @@ impl Tiger {
checkbox("Apply a color filter", self.apply_color_filter) checkbox("Apply a color filter", self.apply_color_filter)
.on_toggle(Message::ToggleColorFilter); .on_toggle(Message::ToggleColorFilter);
container( center(
column![ column![svg, container(apply_color_filter).center_x()]
svg, .spacing(20)
container(apply_color_filter).width(Length::Fill).center_x() .height(Length::Fill),
]
.spacing(20)
.height(Length::Fill),
) )
.width(Length::Fill)
.height(Length::Fill)
.padding(20) .padding(20)
.center_x()
.center_y()
.into() .into()
} }
} }

View file

@ -1,5 +1,5 @@
use iced::widget::{button, column, container, text}; use iced::widget::{button, column, container, text};
use iced::{system, Command, Element, Length}; use iced::{system, Command, Element};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("System Information - Iced", Example::update, Example::view) iced::program("System Information - Iced", Example::update, Example::view)
@ -136,11 +136,6 @@ impl Example {
} }
}; };
container(content) container(content).center().into()
.center_x()
.center_y()
.width(Length::Fill)
.height(Length::Fill)
.into()
} }
} }

View file

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

View file

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

View file

@ -2,7 +2,7 @@ use iced::event::{self, Event};
use iced::keyboard; use iced::keyboard;
use iced::keyboard::key; use iced::keyboard::key;
use iced::widget::{ use iced::widget::{
self, button, column, container, pick_list, row, slider, text, text_input, self, button, center, column, pick_list, row, slider, text, text_input,
}; };
use iced::{Alignment, Command, Element, Length, Subscription}; use iced::{Alignment, Command, Element, Length, Subscription};
@ -102,7 +102,7 @@ impl App {
.then_some(Message::Add), .then_some(Message::Add),
); );
let content = container( let content = center(
column![ column![
subtitle( subtitle(
"Title", "Title",
@ -146,11 +146,7 @@ impl App {
] ]
.spacing(10) .spacing(10)
.max_width(200), .max_width(200),
) );
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y();
toast::Manager::new(content, &self.toasts, Message::Close) toast::Manager::new(content, &self.toasts, Message::Close)
.timeout(self.timeout_secs) .timeout(self.timeout_secs)

View file

@ -1,8 +1,8 @@
use iced::alignment::{self, Alignment}; use iced::alignment::{self, Alignment};
use iced::keyboard; use iced::keyboard;
use iced::widget::{ use iced::widget::{
self, button, checkbox, column, container, keyed_column, row, scrollable, self, button, center, checkbox, column, container, keyed_column, row,
text, text_input, Text, scrollable, text, text_input, Text,
}; };
use iced::window; use iced::window;
use iced::{Command, Element, Font, Length, Subscription}; use iced::{Command, Element, Font, Length, Subscription};
@ -238,7 +238,7 @@ impl Todos {
.spacing(20) .spacing(20)
.max_width(800); .max_width(800);
scrollable(container(content).padding(40).center_x()).into() scrollable(container(content).center_x().padding(40)).into()
} }
} }
} }
@ -435,19 +435,16 @@ impl Filter {
} }
fn loading_message<'a>() -> Element<'a, Message> { fn loading_message<'a>() -> Element<'a, Message> {
container( center(
text("Loading...") text("Loading...")
.horizontal_alignment(alignment::Horizontal::Center) .horizontal_alignment(alignment::Horizontal::Center)
.size(50), .size(50),
) )
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.into() .into()
} }
fn empty_message(message: &str) -> Element<'_, Message> { fn empty_message(message: &str) -> Element<'_, Message> {
container( center(
text(message) text(message)
.width(Length::Fill) .width(Length::Fill)
.size(25) .size(25)
@ -455,7 +452,6 @@ fn empty_message(message: &str) -> Element<'_, Message> {
.color([0.7, 0.7, 0.7]), .color([0.7, 0.7, 0.7]),
) )
.height(200) .height(200)
.center_y()
.into() .into()
} }

View file

@ -1,6 +1,6 @@
use iced::widget::tooltip::Position; use iced::widget::tooltip::Position;
use iced::widget::{button, container, tooltip}; use iced::widget::{button, center, container, tooltip};
use iced::{Element, Length}; use iced::Element;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::run("Tooltip - Iced", Tooltip::update, Tooltip::view) iced::run("Tooltip - Iced", Tooltip::update, Tooltip::view)
@ -43,12 +43,7 @@ impl Tooltip {
.gap(10) .gap(10)
.style(container::rounded_box); .style(container::rounded_box);
container(tooltip) center(tooltip).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -76,11 +76,10 @@ impl Tour {
} else { } else {
content content
}) })
.width(Length::Fill)
.center_x(), .center_x(),
); );
container(scrollable).height(Length::Fill).center_y().into() container(scrollable).center_y().into()
} }
} }
@ -670,7 +669,6 @@ fn ferris<'a>(
.filter_method(filter_method) .filter_method(filter_method)
.width(width), .width(width),
) )
.width(Length::Fill)
.center_x() .center_x()
} }

View file

@ -1,6 +1,6 @@
use iced::event::{self, Event}; use iced::event::{self, Event};
use iced::widget::{container, text}; use iced::widget::{center, text};
use iced::{Element, Length, Subscription}; use iced::{Element, Subscription};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("URL Handler - Iced", App::update, App::view) iced::program("URL Handler - Iced", App::update, App::view)
@ -44,11 +44,6 @@ impl App {
None => text("No URL received yet!"), None => text("No URL received yet!"),
}; };
container(content.size(48)) center(content.size(48)).into()
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
} }
} }

View file

@ -2,7 +2,7 @@ mod echo;
use iced::alignment::{self, Alignment}; use iced::alignment::{self, Alignment};
use iced::widget::{ use iced::widget::{
button, column, container, row, scrollable, text, text_input, self, button, center, column, row, scrollable, text, text_input,
}; };
use iced::{color, Command, Element, Length, Subscription}; use iced::{color, Command, Element, Length, Subscription};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -31,7 +31,10 @@ enum Message {
impl WebSocket { impl WebSocket {
fn load() -> Command<Message> { fn load() -> Command<Message> {
Command::perform(echo::server::run(), |_| Message::Server) Command::batch([
Command::perform(echo::server::run(), |_| Message::Server),
widget::focus_next(),
])
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Command<Message> {
@ -85,14 +88,10 @@ impl WebSocket {
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {
let message_log: Element<_> = if self.messages.is_empty() { let message_log: Element<_> = if self.messages.is_empty() {
container( center(
text("Your messages will appear here...") text("Your messages will appear here...")
.color(color!(0x888888)), .color(color!(0x888888)),
) )
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into() .into()
} else { } else {
scrollable( scrollable(

View file

@ -55,13 +55,15 @@ pub mod time {
let start = tokio::time::Instant::now() + self.0; let start = tokio::time::Instant::now() + self.0;
let mut interval = tokio::time::interval_at(start, self.0);
interval.set_missed_tick_behavior(
tokio::time::MissedTickBehavior::Skip,
);
let stream = { let stream = {
futures::stream::unfold( futures::stream::unfold(interval, |mut interval| async move {
tokio::time::interval_at(start, self.0), Some((interval.tick().await, interval))
|mut interval| async move { })
Some((interval.tick().await, interval))
},
)
}; };
stream.map(tokio::time::Instant::into_std).boxed() stream.map(tokio::time::Instant::into_std).boxed()

189
graphics/src/cache.rs Normal file
View file

@ -0,0 +1,189 @@
//! Cache computations and efficiently reuse them.
use std::cell::RefCell;
use std::fmt;
use std::sync::atomic::{self, AtomicU64};
/// A simple cache that stores generated values to avoid recomputation.
///
/// Keeps track of the last generated value after clearing.
pub struct Cache<T> {
group: Group,
state: RefCell<State<T>>,
}
impl<T> Cache<T> {
/// Creates a new empty [`Cache`].
pub fn new() -> Self {
Cache {
group: Group::singleton(),
state: RefCell::new(State::Empty { previous: None }),
}
}
/// Creates a new empty [`Cache`] with the given [`Group`].
///
/// Caches within the same group may reuse internal rendering storage.
///
/// You should generally group caches that are likely to change
/// together.
pub fn with_group(group: Group) -> Self {
assert!(
!group.is_singleton(),
"The group {group:?} cannot be shared!"
);
Cache {
group,
state: RefCell::new(State::Empty { previous: None }),
}
}
/// Returns the [`Group`] of the [`Cache`].
pub fn group(&self) -> Group {
self.group
}
/// Puts the given value in the [`Cache`].
///
/// Notice that, given this is a cache, a mutable reference is not
/// necessary to call this method. You can safely update the cache in
/// rendering code.
pub fn put(&self, value: T) {
*self.state.borrow_mut() = State::Filled { current: value };
}
/// Returns a reference cell to the internal [`State`] of the [`Cache`].
pub fn state(&self) -> &RefCell<State<T>> {
&self.state
}
/// Clears the [`Cache`].
pub fn clear(&self)
where
T: Clone,
{
use std::ops::Deref;
let previous = match self.state.borrow().deref() {
State::Empty { previous } => previous.clone(),
State::Filled { current } => Some(current.clone()),
};
*self.state.borrow_mut() = State::Empty { previous };
}
}
/// A cache group.
///
/// Caches that share the same group generally change together.
///
/// A cache group can be used to implement certain performance
/// optimizations during rendering, like batching or sharing atlases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Group {
id: u64,
is_singleton: bool,
}
impl Group {
/// Generates a new unique cache [`Group`].
pub fn unique() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
Self {
id: NEXT.fetch_add(1, atomic::Ordering::Relaxed),
is_singleton: false,
}
}
/// Returns `true` if the [`Group`] can only ever have a
/// single [`Cache`] in it.
///
/// This is the default kind of [`Group`] assigned when using
/// [`Cache::new`].
///
/// Knowing that a [`Group`] will never be shared may be
/// useful for rendering backends to perform additional
/// optimizations.
pub fn is_singleton(self) -> bool {
self.is_singleton
}
fn singleton() -> Self {
Self {
is_singleton: true,
..Self::unique()
}
}
}
impl<T> fmt::Debug for Cache<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::ops::Deref;
let state = self.state.borrow();
match state.deref() {
State::Empty { previous } => {
write!(f, "Cache::Empty {{ previous: {previous:?} }}")
}
State::Filled { current } => {
write!(f, "Cache::Filled {{ current: {current:?} }}")
}
}
}
}
impl<T> Default for Cache<T> {
fn default() -> Self {
Self::new()
}
}
/// The state of a [`Cache`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State<T> {
/// The [`Cache`] is empty.
Empty {
/// The previous value of the [`Cache`].
previous: Option<T>,
},
/// The [`Cache`] is filled.
Filled {
/// The current value of the [`Cache`]
current: T,
},
}
/// A piece of data that can be cached.
pub trait Cached: Sized {
/// The type of cache produced.
type Cache: Clone;
/// Loads the [`Cache`] into a proper instance.
///
/// [`Cache`]: Self::Cache
fn load(cache: &Self::Cache) -> Self;
/// Caches this value, producing its corresponding [`Cache`].
///
/// [`Cache`]: Self::Cache
fn cache(self, group: Group, previous: Option<Self::Cache>) -> Self::Cache;
}
#[cfg(debug_assertions)]
impl Cached for () {
type Cache = ();
fn load(_cache: &Self::Cache) -> Self {}
fn cache(
self,
_group: Group,
_previous: Option<Self::Cache>,
) -> Self::Cache {
}
}

View file

@ -1,24 +0,0 @@
/// A piece of data that can be cached.
pub trait Cached: Sized {
/// The type of cache produced.
type Cache: Clone;
/// Loads the [`Cache`] into a proper instance.
///
/// [`Cache`]: Self::Cache
fn load(cache: &Self::Cache) -> Self;
/// Caches this value, producing its corresponding [`Cache`].
///
/// [`Cache`]: Self::Cache
fn cache(self, previous: Option<Self::Cache>) -> Self::Cache;
}
#[cfg(debug_assertions)]
impl Cached for () {
type Cache = ();
fn load(_cache: &Self::Cache) -> Self {}
fn cache(self, _previous: Option<Self::Cache>) -> Self::Cache {}
}

View file

@ -18,8 +18,8 @@ pub use text::Text;
pub use crate::gradient::{self, Gradient}; pub use crate::gradient::{self, Gradient};
use crate::cache::Cached;
use crate::core::{self, Size}; use crate::core::{self, Size};
use crate::Cached;
/// A renderer capable of drawing some [`Self::Geometry`]. /// A renderer capable of drawing some [`Self::Geometry`].
pub trait Renderer: core::Renderer { pub trait Renderer: core::Renderer {

View file

@ -1,8 +1,8 @@
use crate::cache::{self, Cached};
use crate::core::Size; use crate::core::Size;
use crate::geometry::{self, Frame}; use crate::geometry::{self, Frame};
use crate::Cached;
use std::cell::RefCell; pub use cache::Group;
/// A simple cache that stores generated geometry to avoid recomputation. /// A simple cache that stores generated geometry to avoid recomputation.
/// ///
@ -12,7 +12,13 @@ pub struct Cache<Renderer>
where where
Renderer: geometry::Renderer, Renderer: geometry::Renderer,
{ {
state: RefCell<State<Renderer::Geometry>>, raw: crate::Cache<Data<<Renderer::Geometry as Cached>::Cache>>,
}
#[derive(Debug, Clone)]
struct Data<T> {
bounds: Size,
geometry: T,
} }
impl<Renderer> Cache<Renderer> impl<Renderer> Cache<Renderer>
@ -22,20 +28,25 @@ where
/// Creates a new empty [`Cache`]. /// Creates a new empty [`Cache`].
pub fn new() -> Self { pub fn new() -> Self {
Cache { Cache {
state: RefCell::new(State::Empty { previous: None }), raw: cache::Cache::new(),
}
}
/// Creates a new empty [`Cache`] with the given [`Group`].
///
/// Caches within the same group may reuse internal rendering storage.
///
/// You should generally group caches that are likely to change
/// together.
pub fn with_group(group: Group) -> Self {
Cache {
raw: crate::Cache::with_group(group),
} }
} }
/// Clears the [`Cache`], forcing a redraw the next time it is used. /// Clears the [`Cache`], forcing a redraw the next time it is used.
pub fn clear(&self) { pub fn clear(&self) {
use std::ops::Deref; self.raw.clear();
let previous = match self.state.borrow().deref() {
State::Empty { previous } => previous.clone(),
State::Filled { geometry, .. } => Some(geometry.clone()),
};
*self.state.borrow_mut() = State::Empty { previous };
} }
/// Draws geometry using the provided closure and stores it in the /// Draws geometry using the provided closure and stores it in the
@ -56,27 +67,30 @@ where
) -> Renderer::Geometry { ) -> Renderer::Geometry {
use std::ops::Deref; use std::ops::Deref;
let previous = match self.state.borrow().deref() { let state = self.raw.state();
State::Empty { previous } => previous.clone(),
State::Filled { let previous = match state.borrow().deref() {
bounds: cached_bounds, cache::State::Empty { previous } => {
geometry, previous.as_ref().map(|data| data.geometry.clone())
} => { }
if *cached_bounds == bounds { cache::State::Filled { current } => {
return Cached::load(geometry); if current.bounds == bounds {
return Cached::load(&current.geometry);
} }
Some(geometry.clone()) Some(current.geometry.clone())
} }
}; };
let mut frame = Frame::new(renderer, bounds); let mut frame = Frame::new(renderer, bounds);
draw_fn(&mut frame); draw_fn(&mut frame);
let geometry = frame.into_geometry().cache(previous); let geometry = frame.into_geometry().cache(self.raw.group(), previous);
let result = Cached::load(&geometry); let result = Cached::load(&geometry);
*self.state.borrow_mut() = State::Filled { bounds, geometry }; *state.borrow_mut() = cache::State::Filled {
current: Data { bounds, geometry },
};
result result
} }
@ -85,16 +99,10 @@ where
impl<Renderer> std::fmt::Debug for Cache<Renderer> impl<Renderer> std::fmt::Debug for Cache<Renderer>
where where
Renderer: geometry::Renderer, Renderer: geometry::Renderer,
<Renderer::Geometry as Cached>::Cache: std::fmt::Debug,
{ {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = self.state.borrow(); write!(f, "{:?}", &self.raw)
match *state {
State::Empty { .. } => write!(f, "Cache::Empty"),
State::Filled { bounds, .. } => {
write!(f, "Cache::Filled {{ bounds: {bounds:?} }}")
}
}
} }
} }
@ -106,16 +114,3 @@ where
Self::new() Self::new()
} }
} }
enum State<Geometry>
where
Geometry: Cached,
{
Empty {
previous: Option<Geometry::Cache>,
},
Filled {
bounds: Size,
geometry: Geometry::Cache,
},
}

View file

@ -2,9 +2,7 @@
#[cfg(feature = "image")] #[cfg(feature = "image")]
pub use ::image as image_rs; pub use ::image as image_rs;
use crate::core::image; use crate::core::{image, svg, Color, Radians, Rectangle};
use crate::core::svg;
use crate::core::{Color, Rectangle};
/// A raster or vector image. /// A raster or vector image.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@ -19,6 +17,12 @@ pub enum Image {
/// The bounds of the image. /// The bounds of the image.
bounds: Rectangle, bounds: Rectangle,
/// The rotation of the image.
rotation: Radians,
/// The opacity of the image.
opacity: f32,
}, },
/// A vector image. /// A vector image.
Vector { Vector {
@ -30,6 +34,12 @@ pub enum Image {
/// The bounds of the image. /// The bounds of the image.
bounds: Rectangle, bounds: Rectangle,
/// The rotation of the image.
rotation: Radians,
/// The opacity of the image.
opacity: f32,
}, },
} }
@ -37,9 +47,12 @@ impl Image {
/// Returns the bounds of the [`Image`]. /// Returns the bounds of the [`Image`].
pub fn bounds(&self) -> Rectangle { pub fn bounds(&self) -> Rectangle {
match self { match self {
Image::Raster { bounds, .. } | Image::Vector { bounds, .. } => { Image::Raster {
*bounds bounds, rotation, ..
} }
| Image::Vector {
bounds, rotation, ..
} => bounds.rotate(*rotation),
} }
} }
} }
@ -50,7 +63,8 @@ impl Image {
/// [`Handle`]: image::Handle /// [`Handle`]: image::Handle
pub fn load( pub fn load(
handle: &image::Handle, handle: &image::Handle,
) -> ::image::ImageResult<::image::DynamicImage> { ) -> ::image::ImageResult<::image::ImageBuffer<::image::Rgba<u8>, image::Bytes>>
{
use bitflags::bitflags; use bitflags::bitflags;
bitflags! { bitflags! {
@ -100,8 +114,8 @@ pub fn load(
} }
} }
match handle.data() { let (width, height, pixels) = match handle {
image::Data::Path(path) => { image::Handle::Path(_, path) => {
let image = ::image::open(path)?; let image = ::image::open(path)?;
let operation = std::fs::File::open(path) let operation = std::fs::File::open(path)
@ -110,33 +124,44 @@ pub fn load(
.and_then(|mut reader| Operation::from_exif(&mut reader).ok()) .and_then(|mut reader| Operation::from_exif(&mut reader).ok())
.unwrap_or_else(Operation::empty); .unwrap_or_else(Operation::empty);
Ok(operation.perform(image)) let rgba = operation.perform(image).into_rgba8();
(
rgba.width(),
rgba.height(),
image::Bytes::from(rgba.into_raw()),
)
} }
image::Data::Bytes(bytes) => { image::Handle::Bytes(_, bytes) => {
let image = ::image::load_from_memory(bytes)?; let image = ::image::load_from_memory(bytes)?;
let operation = let operation =
Operation::from_exif(&mut std::io::Cursor::new(bytes)) Operation::from_exif(&mut std::io::Cursor::new(bytes))
.ok() .ok()
.unwrap_or_else(Operation::empty); .unwrap_or_else(Operation::empty);
Ok(operation.perform(image)) let rgba = operation.perform(image).into_rgba8();
(
rgba.width(),
rgba.height(),
image::Bytes::from(rgba.into_raw()),
)
} }
image::Data::Rgba { image::Handle::Rgba {
width, width,
height, height,
pixels, pixels,
} => { ..
if let Some(image) = } => (*width, *height, pixels.clone()),
::image::ImageBuffer::from_vec(*width, *height, pixels.to_vec()) };
{
Ok(::image::DynamicImage::ImageRgba8(image)) if let Some(image) = ::image::ImageBuffer::from_raw(width, height, pixels) {
} else { Ok(image)
Err(::image::error::ImageError::Limits( } else {
::image::error::LimitError::from_kind( Err(::image::error::ImageError::Limits(
::image::error::LimitErrorKind::DimensionError, ::image::error::LimitError::from_kind(
), ::image::error::LimitErrorKind::DimensionError,
)) ),
} ))
}
} }
} }

View file

@ -9,10 +9,10 @@
)] )]
#![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod antialiasing; mod antialiasing;
mod cached;
mod settings; mod settings;
mod viewport; mod viewport;
pub mod cache;
pub mod color; pub mod color;
pub mod compositor; pub mod compositor;
pub mod damage; pub mod damage;
@ -27,7 +27,7 @@ pub mod text;
pub mod geometry; pub mod geometry;
pub use antialiasing::Antialiasing; pub use antialiasing::Antialiasing;
pub use cached::Cached; pub use cache::Cache;
pub use compositor::Compositor; pub use compositor::Compositor;
pub use error::Error; pub use error::Error;
pub use gradient::Gradient; pub use gradient::Gradient;

View file

@ -456,10 +456,14 @@ impl editor::Editor for Editor {
} }
} }
Action::Scroll { lines } => { Action::Scroll { lines } => {
editor.action( let (_, height) = editor.buffer().size();
font_system.raw(),
cosmic_text::Action::Scroll { lines }, if height < i32::MAX as f32 {
); editor.action(
font_system.raw(),
cosmic_text::Action::Scroll { lines },
);
}
} }
} }

View file

@ -3,7 +3,7 @@ use crate::core::image;
use crate::core::renderer; use crate::core::renderer;
use crate::core::svg; use crate::core::svg;
use crate::core::{ use crate::core::{
self, Background, Color, Point, Rectangle, Size, Transformation, self, Background, Color, Point, Radians, Rectangle, Size, Transformation,
}; };
use crate::graphics; use crate::graphics;
use crate::graphics::compositor; use crate::graphics::compositor;
@ -154,11 +154,19 @@ where
handle: Self::Handle, handle: Self::Handle,
filter_method: image::FilterMethod, filter_method: image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians,
opacity: f32,
) { ) {
delegate!( delegate!(
self, self,
renderer, renderer,
renderer.draw_image(handle, filter_method, bounds) renderer.draw_image(
handle,
filter_method,
bounds,
rotation,
opacity
)
); );
} }
} }
@ -177,8 +185,14 @@ where
handle: svg::Handle, handle: svg::Handle,
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians,
opacity: f32,
) { ) {
delegate!(self, renderer, renderer.draw_svg(handle, color, bounds)); delegate!(
self,
renderer,
renderer.draw_svg(handle, color, bounds, rotation, opacity)
);
} }
} }
@ -428,8 +442,8 @@ where
mod geometry { mod geometry {
use super::Renderer; use super::Renderer;
use crate::core::{Point, Radians, Rectangle, Size, Vector}; use crate::core::{Point, Radians, Rectangle, Size, Vector};
use crate::graphics::cache::{self, Cached};
use crate::graphics::geometry::{self, Fill, Path, Stroke, Text}; use crate::graphics::geometry::{self, Fill, Path, Stroke, Text};
use crate::graphics::Cached;
impl<A, B> geometry::Renderer for Renderer<A, B> impl<A, B> geometry::Renderer for Renderer<A, B>
where where
@ -483,21 +497,25 @@ mod geometry {
} }
} }
fn cache(self, previous: Option<Self::Cache>) -> Self::Cache { fn cache(
self,
group: cache::Group,
previous: Option<Self::Cache>,
) -> Self::Cache {
match (self, previous) { match (self, previous) {
( (
Self::Primary(geometry), Self::Primary(geometry),
Some(Geometry::Primary(previous)), Some(Geometry::Primary(previous)),
) => Geometry::Primary(geometry.cache(Some(previous))), ) => Geometry::Primary(geometry.cache(group, Some(previous))),
(Self::Primary(geometry), None) => { (Self::Primary(geometry), None) => {
Geometry::Primary(geometry.cache(None)) Geometry::Primary(geometry.cache(group, None))
} }
( (
Self::Secondary(geometry), Self::Secondary(geometry),
Some(Geometry::Secondary(previous)), Some(Geometry::Secondary(previous)),
) => Geometry::Secondary(geometry.cache(Some(previous))), ) => Geometry::Secondary(geometry.cache(group, Some(previous))),
(Self::Secondary(geometry), None) => { (Self::Secondary(geometry), None) => {
Geometry::Secondary(geometry.cache(None)) Geometry::Secondary(geometry.cache(group, None))
} }
_ => unreachable!(), _ => unreachable!(),
} }

View file

@ -18,6 +18,7 @@ debug = []
multi-window = [] multi-window = []
[dependencies] [dependencies]
bytes.workspace = true
iced_core.workspace = true iced_core.workspace = true
iced_futures.workspace = true iced_futures.workspace = true
iced_futures.features = ["thread-pool"] iced_futures.features = ["thread-pool"]

View file

@ -48,7 +48,7 @@ where
caches, caches,
queued_events: Vec::new(), queued_events: Vec::new(),
queued_messages: Vec::new(), queued_messages: Vec::new(),
mouse_interaction: mouse::Interaction::Idle, mouse_interaction: mouse::Interaction::None,
} }
} }

View file

@ -47,7 +47,7 @@ where
cache, cache,
queued_events: Vec::new(), queued_events: Vec::new(),
queued_messages: Vec::new(), queued_messages: Vec::new(),
mouse_interaction: mouse::Interaction::Idle, mouse_interaction: mouse::Interaction::None,
} }
} }

View file

@ -1,8 +1,8 @@
//! Take screenshots of a window. //! Take screenshots of a window.
use crate::core::{Rectangle, Size}; use crate::core::{Rectangle, Size};
use bytes::Bytes;
use std::fmt::{Debug, Formatter}; use std::fmt::{Debug, Formatter};
use std::sync::Arc;
/// Data of a screenshot, captured with `window::screenshot()`. /// Data of a screenshot, captured with `window::screenshot()`.
/// ///
@ -10,7 +10,7 @@ use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
pub struct Screenshot { pub struct Screenshot {
/// The bytes of the [`Screenshot`]. /// The bytes of the [`Screenshot`].
pub bytes: Arc<Vec<u8>>, pub bytes: Bytes,
/// The size of the [`Screenshot`]. /// The size of the [`Screenshot`].
pub size: Size<u32>, pub size: Size<u32>,
} }
@ -28,9 +28,9 @@ impl Debug for Screenshot {
impl Screenshot { impl Screenshot {
/// Creates a new [`Screenshot`]. /// Creates a new [`Screenshot`].
pub fn new(bytes: Vec<u8>, size: Size<u32>) -> Self { pub fn new(bytes: impl Into<Bytes>, size: Size<u32>) -> Self {
Self { Self {
bytes: Arc::new(bytes), bytes: bytes.into(),
size, size,
} }
} }
@ -68,7 +68,7 @@ impl Screenshot {
); );
Ok(Self { Ok(Self {
bytes: Arc::new(chopped), bytes: Bytes::from(chopped),
size: Size::new(region.width, region.height), size: Size::new(region.width, region.height),
}) })
} }
@ -80,6 +80,12 @@ impl AsRef<[u8]> for Screenshot {
} }
} }
impl From<Screenshot> for Bytes {
fn from(screenshot: Screenshot) -> Self {
screenshot.bytes
}
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
/// Errors that can occur when cropping a [`Screenshot`]. /// Errors that can occur when cropping a [`Screenshot`].
pub enum CropError { pub enum CropError {

View file

@ -212,26 +212,11 @@ where
..crate::graphics::Settings::default() ..crate::graphics::Settings::default()
}; };
let run = crate::shell::application::run::< Ok(crate::shell::application::run::<
Instance<Self>, Instance<Self>,
Self::Executor, Self::Executor,
<Self::Renderer as compositor::Default>::Compositor, <Self::Renderer as compositor::Default>::Compositor,
>(settings.into(), renderer_settings); >(settings.into(), renderer_settings)?)
#[cfg(target_arch = "wasm32")]
{
use crate::futures::FutureExt;
use iced_futures::backend::wasm::wasm_bindgen::Executor;
Executor::new()
.expect("Create Wasm executor")
.spawn(run.map(|_| ()));
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
Ok(crate::futures::executor::block_on(run)?)
} }
} }

View file

@ -51,6 +51,7 @@
//! We start by modelling the __state__ of our application: //! We start by modelling the __state__ of our application:
//! //!
//! ``` //! ```
//! #[derive(Default)]
//! struct Counter { //! struct Counter {
//! // The counter value //! // The counter value
//! value: i32, //! value: i32,
@ -199,8 +200,8 @@ pub use crate::core::gradient;
pub use crate::core::theme; pub use crate::core::theme;
pub use crate::core::{ pub use crate::core::{
Alignment, Background, Border, Color, ContentFit, Degrees, Gradient, Alignment, Background, Border, Color, ContentFit, Degrees, Gradient,
Length, Padding, Pixels, Point, Radians, Rectangle, Shadow, Size, Theme, Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size,
Transformation, Vector, Theme, Transformation, Vector,
}; };
pub mod clipboard { pub mod clipboard {

View file

@ -54,7 +54,7 @@ pub enum Error {
InvalidError(#[from] icon::Error), InvalidError(#[from] icon::Error),
/// The underlying OS failed to create the icon. /// The underlying OS failed to create the icon.
#[error("The underlying OS failted to create the window icon: {0}")] #[error("The underlying OS failed to create the window icon: {0}")]
OsError(#[from] io::Error), OsError(#[from] io::Error),
/// The `image` crate reported an error. /// The `image` crate reported an error.

View file

@ -550,6 +550,8 @@ impl Engine {
handle, handle,
filter_method, filter_method,
bounds, bounds,
rotation,
opacity,
} => { } => {
let physical_bounds = *bounds * _transformation; let physical_bounds = *bounds * _transformation;
@ -560,12 +562,22 @@ impl Engine {
let clip_mask = (!physical_bounds.is_within(&_clip_bounds)) let clip_mask = (!physical_bounds.is_within(&_clip_bounds))
.then_some(_clip_mask as &_); .then_some(_clip_mask as &_);
let center = physical_bounds.center();
let radians = f32::from(*rotation);
let transform = into_transform(_transformation).post_rotate_at(
radians.to_degrees(),
center.x,
center.y,
);
self.raster_pipeline.draw( self.raster_pipeline.draw(
handle, handle,
*filter_method, *filter_method,
*bounds, *bounds,
*opacity,
_pixels, _pixels,
into_transform(_transformation), transform,
clip_mask, clip_mask,
); );
} }
@ -574,6 +586,8 @@ impl Engine {
handle, handle,
color, color,
bounds, bounds,
rotation,
opacity,
} => { } => {
let physical_bounds = *bounds * _transformation; let physical_bounds = *bounds * _transformation;
@ -584,11 +598,22 @@ impl Engine {
let clip_mask = (!physical_bounds.is_within(&_clip_bounds)) let clip_mask = (!physical_bounds.is_within(&_clip_bounds))
.then_some(_clip_mask as &_); .then_some(_clip_mask as &_);
let center = physical_bounds.center();
let radians = f32::from(*rotation);
let transform = into_transform(_transformation).post_rotate_at(
radians.to_degrees(),
center.x,
center.y,
);
self.vector_pipeline.draw( self.vector_pipeline.draw(
handle, handle,
*color, *color,
physical_bounds, physical_bounds,
*opacity,
_pixels, _pixels,
transform,
clip_mask, clip_mask,
); );
} }

View file

@ -1,9 +1,10 @@
use crate::core::text::LineHeight; use crate::core::text::LineHeight;
use crate::core::{Pixels, Point, Radians, Rectangle, Size, Vector}; use crate::core::{Pixels, Point, Radians, Rectangle, Size, Vector};
use crate::graphics::cache::{self, Cached};
use crate::graphics::geometry::fill::{self, Fill}; use crate::graphics::geometry::fill::{self, Fill};
use crate::graphics::geometry::stroke::{self, Stroke}; use crate::graphics::geometry::stroke::{self, Stroke};
use crate::graphics::geometry::{self, Path, Style}; use crate::graphics::geometry::{self, Path, Style};
use crate::graphics::{Cached, Gradient, Text}; use crate::graphics::{Gradient, Text};
use crate::Primitive; use crate::Primitive;
use std::rc::Rc; use std::rc::Rc;
@ -32,7 +33,7 @@ impl Cached for Geometry {
Self::Cache(cache.clone()) Self::Cache(cache.clone())
} }
fn cache(self, _previous: Option<Cache>) -> Cache { fn cache(self, _group: cache::Group, _previous: Option<Cache>) -> Cache {
match self { match self {
Self::Live { Self::Live {
primitives, primitives,

View file

@ -1,7 +1,7 @@
use crate::core::image; use crate::core::{
use crate::core::renderer::Quad; image, renderer::Quad, svg, Background, Color, Point, Radians, Rectangle,
use crate::core::svg; Transformation,
use crate::core::{Background, Color, Point, Rectangle, Transformation}; };
use crate::graphics::damage; use crate::graphics::damage;
use crate::graphics::layer; use crate::graphics::layer;
use crate::graphics::text::{Editor, Paragraph, Text}; use crate::graphics::text::{Editor, Paragraph, Text};
@ -121,11 +121,15 @@ impl Layer {
filter_method: image::FilterMethod, filter_method: image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians,
opacity: f32,
) { ) {
let image = Image::Raster { let image = Image::Raster {
handle, handle,
filter_method, filter_method,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation,
opacity,
}; };
self.images.push(image); self.images.push(image);
@ -137,11 +141,15 @@ impl Layer {
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians,
opacity: f32,
) { ) {
let svg = Image::Vector { let svg = Image::Vector {
handle, handle,
color, color,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation,
opacity,
}; };
self.images.push(svg); self.images.push(svg);

View file

@ -377,9 +377,18 @@ impl core::image::Renderer for Renderer {
handle: Self::Handle, handle: Self::Handle,
filter_method: core::image::FilterMethod, filter_method: core::image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_image(handle, filter_method, bounds, transformation); layer.draw_image(
handle,
filter_method,
bounds,
transformation,
rotation,
opacity,
);
} }
} }
@ -397,9 +406,18 @@ impl core::svg::Renderer for Renderer {
handle: core::svg::Handle, handle: core::svg::Handle,
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_svg(handle, color, bounds, transformation); layer.draw_svg(
handle,
color,
bounds,
transformation,
rotation,
opacity,
);
} }
} }

View file

@ -31,6 +31,7 @@ impl Pipeline {
handle: &raster::Handle, handle: &raster::Handle,
filter_method: raster::FilterMethod, filter_method: raster::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
opacity: f32,
pixels: &mut tiny_skia::PixmapMut<'_>, pixels: &mut tiny_skia::PixmapMut<'_>,
transform: tiny_skia::Transform, transform: tiny_skia::Transform,
clip_mask: Option<&tiny_skia::Mask>, clip_mask: Option<&tiny_skia::Mask>,
@ -56,6 +57,7 @@ impl Pipeline {
image, image,
&tiny_skia::PixmapPaint { &tiny_skia::PixmapPaint {
quality, quality,
opacity,
..Default::default() ..Default::default()
}, },
transform, transform,
@ -71,8 +73,8 @@ impl Pipeline {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct Cache { struct Cache {
entries: FxHashMap<u64, Option<Entry>>, entries: FxHashMap<raster::Id, Option<Entry>>,
hits: FxHashSet<u64>, hits: FxHashSet<raster::Id>,
} }
impl Cache { impl Cache {
@ -83,7 +85,7 @@ impl Cache {
let id = handle.id(); let id = handle.id();
if let hash_map::Entry::Vacant(entry) = self.entries.entry(id) { if let hash_map::Entry::Vacant(entry) = self.entries.entry(id) {
let image = graphics::image::load(handle).ok()?.into_rgba8(); let image = graphics::image::load(handle).ok()?;
let mut buffer = let mut buffer =
vec![0u32; image.width() as usize * image.height() as usize]; vec![0u32; image.width() as usize * image.height() as usize];

View file

@ -4,6 +4,7 @@ use crate::graphics::text;
use resvg::usvg::{self, TreeTextToPath}; use resvg::usvg::{self, TreeTextToPath};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use tiny_skia::Transform;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::hash_map; use std::collections::hash_map;
@ -33,7 +34,9 @@ impl Pipeline {
handle: &Handle, handle: &Handle,
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
opacity: f32,
pixels: &mut tiny_skia::PixmapMut<'_>, pixels: &mut tiny_skia::PixmapMut<'_>,
transform: Transform,
clip_mask: Option<&tiny_skia::Mask>, clip_mask: Option<&tiny_skia::Mask>,
) { ) {
if let Some(image) = self.cache.borrow_mut().draw( if let Some(image) = self.cache.borrow_mut().draw(
@ -45,8 +48,11 @@ impl Pipeline {
bounds.x as i32, bounds.x as i32,
bounds.y as i32, bounds.y as i32,
image, image,
&tiny_skia::PixmapPaint::default(), &tiny_skia::PixmapPaint {
tiny_skia::Transform::identity(), opacity,
..tiny_skia::PixmapPaint::default()
},
transform,
clip_mask, clip_mask,
); );
} }

View file

@ -1,5 +1,7 @@
use std::borrow::Cow; use std::borrow::Cow;
use wgpu::util::DeviceExt;
pub fn convert( pub fn convert(
device: &wgpu::Device, device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
@ -15,28 +17,58 @@ pub fn convert(
..wgpu::SamplerDescriptor::default() ..wgpu::SamplerDescriptor::default()
}); });
//sampler in 0 #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
let sampler_layout = #[repr(C)]
struct Ratio {
u: f32,
v: f32,
}
let ratio = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("iced-wgpu::triangle::msaa ratio"),
contents: bytemuck::bytes_of(&Ratio { u: 1.0, v: 1.0 }),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM,
});
let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("iced_wgpu.offscreen.blit.sampler_layout"), label: Some("iced_wgpu.offscreen.blit.sampler_layout"),
entries: &[wgpu::BindGroupLayoutEntry { entries: &[
binding: 0, wgpu::BindGroupLayoutEntry {
visibility: wgpu::ShaderStages::FRAGMENT, binding: 0,
ty: wgpu::BindingType::Sampler( visibility: wgpu::ShaderStages::FRAGMENT,
wgpu::SamplerBindingType::NonFiltering, ty: wgpu::BindingType::Sampler(
), wgpu::SamplerBindingType::NonFiltering,
count: None, ),
}], 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_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("iced_wgpu.offscreen.sampler.bind_group"), label: Some("iced_wgpu.offscreen.sampler.bind_group"),
layout: &sampler_layout, layout: &constant_layout,
entries: &[wgpu::BindGroupEntry { entries: &[
binding: 0, wgpu::BindGroupEntry {
resource: wgpu::BindingResource::Sampler(&sampler), binding: 0,
}], resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 1,
resource: ratio.as_entire_binding(),
},
],
}); });
let texture_layout = let texture_layout =
@ -59,7 +91,7 @@ pub fn convert(
let pipeline_layout = let pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("iced_wgpu.offscreen.blit.pipeline_layout"), label: Some("iced_wgpu.offscreen.blit.pipeline_layout"),
bind_group_layouts: &[&sampler_layout, &texture_layout], bind_group_layouts: &[&constant_layout, &texture_layout],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
@ -152,7 +184,7 @@ pub fn convert(
}); });
pass.set_pipeline(&pipeline); pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &sampler_bind_group, &[]); pass.set_bind_group(0, &constant_bind_group, &[]);
pass.set_bind_group(1, &texture_bind_group, &[]); pass.set_bind_group(1, &texture_bind_group, &[]);
pass.draw(0..6, 0..1); pass.draw(0..6, 0..1);

View file

@ -59,8 +59,11 @@ impl Engine {
} }
#[cfg(any(feature = "image", feature = "svg"))] #[cfg(any(feature = "image", feature = "svg"))]
pub fn image_cache(&self) -> &crate::image::cache::Shared { pub fn create_image_cache(
self.image_pipeline.cache() &self,
device: &wgpu::Device,
) -> crate::image::Cache {
self.image_pipeline.create_cache(device)
} }
pub fn submit( pub fn submit(

View file

@ -3,6 +3,7 @@ use crate::core::text::LineHeight;
use crate::core::{ use crate::core::{
Pixels, Point, Radians, Rectangle, Size, Transformation, Vector, Pixels, Point, Radians, Rectangle, Size, Transformation, Vector,
}; };
use crate::graphics::cache::{self, Cached};
use crate::graphics::color; use crate::graphics::color;
use crate::graphics::geometry::fill::{self, Fill}; use crate::graphics::geometry::fill::{self, Fill};
use crate::graphics::geometry::{ use crate::graphics::geometry::{
@ -10,7 +11,7 @@ use crate::graphics::geometry::{
}; };
use crate::graphics::gradient::{self, Gradient}; use crate::graphics::gradient::{self, Gradient};
use crate::graphics::mesh::{self, Mesh}; use crate::graphics::mesh::{self, Mesh};
use crate::graphics::{self, Cached, Text}; use crate::graphics::{self, Text};
use crate::text; use crate::text;
use crate::triangle; use crate::triangle;
@ -38,7 +39,11 @@ impl Cached for Geometry {
Geometry::Cached(cache.clone()) Geometry::Cached(cache.clone())
} }
fn cache(self, previous: Option<Self::Cache>) -> Self::Cache { fn cache(
self,
group: cache::Group,
previous: Option<Self::Cache>,
) -> Self::Cache {
match self { match self {
Self::Live { meshes, text } => { Self::Live { meshes, text } => {
if let Some(mut previous) = previous { if let Some(mut previous) = previous {
@ -51,14 +56,14 @@ impl Cached for Geometry {
if let Some(cache) = &mut previous.text { if let Some(cache) = &mut previous.text {
cache.update(text); cache.update(text);
} else { } else {
previous.text = text::Cache::new(text); previous.text = text::Cache::new(group, text);
} }
previous previous
} else { } else {
Cache { Cache {
meshes: triangle::Cache::new(meshes), meshes: triangle::Cache::new(meshes),
text: text::Cache::new(text), text: text::Cache::new(group, text),
} }
} }
} }

View file

@ -15,15 +15,23 @@ pub const SIZE: u32 = 2048;
use crate::core::Size; use crate::core::Size;
use crate::graphics::color; use crate::graphics::color;
use std::sync::Arc;
#[derive(Debug)] #[derive(Debug)]
pub struct Atlas { pub struct Atlas {
texture: wgpu::Texture, texture: wgpu::Texture,
texture_view: wgpu::TextureView, texture_view: wgpu::TextureView,
texture_bind_group: wgpu::BindGroup,
texture_layout: Arc<wgpu::BindGroupLayout>,
layers: Vec<Layer>, layers: Vec<Layer>,
} }
impl Atlas { impl Atlas {
pub fn new(device: &wgpu::Device, backend: wgpu::Backend) -> Self { pub fn new(
device: &wgpu::Device,
backend: wgpu::Backend,
texture_layout: Arc<wgpu::BindGroupLayout>,
) -> Self {
let layers = match backend { let layers = match backend {
// On the GL backend we start with 2 layers, to help wgpu figure // On the GL backend we start with 2 layers, to help wgpu figure
// out that this texture is `GL_TEXTURE_2D_ARRAY` rather than `GL_TEXTURE_2D` // out that this texture is `GL_TEXTURE_2D_ARRAY` rather than `GL_TEXTURE_2D`
@ -60,15 +68,27 @@ impl Atlas {
..Default::default() ..Default::default()
}); });
let texture_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("iced_wgpu::image texture atlas bind group"),
layout: &texture_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture_view),
}],
});
Atlas { Atlas {
texture, texture,
texture_view, texture_view,
texture_bind_group,
texture_layout,
layers, layers,
} }
} }
pub fn view(&self) -> &wgpu::TextureView { pub fn bind_group(&self) -> &wgpu::BindGroup {
&self.texture_view &self.texture_bind_group
} }
pub fn layer_count(&self) -> usize { pub fn layer_count(&self) -> usize {
@ -94,7 +114,7 @@ impl Atlas {
entry entry
}; };
log::info!("Allocated atlas entry: {entry:?}"); log::debug!("Allocated atlas entry: {entry:?}");
// It is a webgpu requirement that: // It is a webgpu requirement that:
// BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0 // BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0
@ -147,13 +167,20 @@ impl Atlas {
} }
} }
log::info!("Current atlas: {self:?}"); if log::log_enabled!(log::Level::Debug) {
log::debug!(
"Atlas layers: {} (busy: {}, allocations: {})",
self.layer_count(),
self.layers.iter().filter(|layer| !layer.is_empty()).count(),
self.layers.iter().map(Layer::allocations).sum::<usize>(),
);
}
Some(entry) Some(entry)
} }
pub fn remove(&mut self, entry: &Entry) { pub fn remove(&mut self, entry: &Entry) {
log::info!("Removing atlas entry: {entry:?}"); log::debug!("Removing atlas entry: {entry:?}");
match entry { match entry {
Entry::Contiguous(allocation) => { Entry::Contiguous(allocation) => {
@ -266,7 +293,7 @@ impl Atlas {
} }
fn deallocate(&mut self, allocation: &Allocation) { fn deallocate(&mut self, allocation: &Allocation) {
log::info!("Deallocating atlas: {allocation:?}"); log::debug!("Deallocating atlas: {allocation:?}");
match allocation { match allocation {
Allocation::Full { layer } => { Allocation::Full { layer } => {
@ -414,5 +441,17 @@ impl Atlas {
dimension: Some(wgpu::TextureViewDimension::D2Array), dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default() ..Default::default()
}); });
self.texture_bind_group =
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,
),
}],
});
} }
} }

View file

@ -33,6 +33,10 @@ impl Allocator {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.allocations == 0 self.allocations == 0
} }
pub fn allocations(&self) -> usize {
self.allocations
}
} }
pub struct Region { pub struct Region {

View file

@ -11,4 +11,12 @@ impl Layer {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
matches!(self, Layer::Empty) matches!(self, Layer::Empty)
} }
pub fn allocations(&self) -> usize {
match self {
Layer::Empty => 0,
Layer::Busy(allocator) => allocator.allocations(),
Layer::Full => 1,
}
}
} }

View file

@ -1,8 +1,7 @@
use crate::core::{self, Size}; use crate::core::{self, Size};
use crate::image::atlas::{self, Atlas}; use crate::image::atlas::{self, Atlas};
use std::cell::{RefCell, RefMut}; use std::sync::Arc;
use std::rc::Rc;
#[derive(Debug)] #[derive(Debug)]
pub struct Cache { pub struct Cache {
@ -14,9 +13,13 @@ pub struct Cache {
} }
impl Cache { impl Cache {
pub fn new(device: &wgpu::Device, backend: wgpu::Backend) -> Self { pub fn new(
device: &wgpu::Device,
backend: wgpu::Backend,
layout: Arc<wgpu::BindGroupLayout>,
) -> Self {
Self { Self {
atlas: Atlas::new(device, backend), atlas: Atlas::new(device, backend, layout),
#[cfg(feature = "image")] #[cfg(feature = "image")]
raster: crate::image::raster::Cache::default(), raster: crate::image::raster::Cache::default(),
#[cfg(feature = "svg")] #[cfg(feature = "svg")]
@ -24,6 +27,10 @@ impl Cache {
} }
} }
pub fn bind_group(&self) -> &wgpu::BindGroup {
self.atlas.bind_group()
}
pub fn layer_count(&self) -> usize { pub fn layer_count(&self) -> usize {
self.atlas.layer_count() self.atlas.layer_count()
} }
@ -69,21 +76,6 @@ impl Cache {
) )
} }
pub fn create_bind_group(
&self,
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("iced_wgpu::image texture atlas bind group"),
layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(self.atlas.view()),
}],
})
}
pub fn trim(&mut self) { pub fn trim(&mut self) {
#[cfg(feature = "image")] #[cfg(feature = "image")]
self.raster.trim(&mut self.atlas); self.raster.trim(&mut self.atlas);
@ -92,16 +84,3 @@ impl Cache {
self.vector.trim(&mut self.atlas); self.vector.trim(&mut self.atlas);
} }
} }
#[derive(Debug, Clone)]
pub struct Shared(Rc<RefCell<Cache>>);
impl Shared {
pub fn new(cache: Cache) -> Self {
Self(Rc::new(RefCell::new(cache)))
}
pub fn lock(&self) -> RefMut<'_, Cache> {
self.0.borrow_mut()
}
}

View file

@ -13,7 +13,9 @@ use crate::core::{Rectangle, Size, Transformation};
use crate::Buffer; use crate::Buffer;
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use std::mem; use std::mem;
use std::sync::Arc;
pub use crate::graphics::Image; pub use crate::graphics::Image;
@ -22,13 +24,11 @@ pub type Batch = Vec<Image>;
#[derive(Debug)] #[derive(Debug)]
pub struct Pipeline { pub struct Pipeline {
pipeline: wgpu::RenderPipeline, pipeline: wgpu::RenderPipeline,
backend: wgpu::Backend,
nearest_sampler: wgpu::Sampler, nearest_sampler: wgpu::Sampler,
linear_sampler: wgpu::Sampler, linear_sampler: wgpu::Sampler,
texture: wgpu::BindGroup, texture_layout: Arc<wgpu::BindGroupLayout>,
texture_version: usize,
texture_layout: wgpu::BindGroupLayout,
constant_layout: wgpu::BindGroupLayout, constant_layout: wgpu::BindGroupLayout,
cache: cache::Shared,
layers: Vec<Layer>, layers: Vec<Layer>,
prepare_layer: usize, prepare_layer: usize,
} }
@ -135,14 +135,20 @@ impl Pipeline {
attributes: &wgpu::vertex_attr_array!( attributes: &wgpu::vertex_attr_array!(
// Position // Position
0 => Float32x2, 0 => Float32x2,
// Scale // Center
1 => Float32x2, 1 => Float32x2,
// Atlas position // Scale
2 => Float32x2, 2 => Float32x2,
// Rotation
3 => Float32,
// Opacity
4 => Float32,
// Atlas position
5 => Float32x2,
// Atlas scale // Atlas scale
3 => Float32x2, 6 => Float32x2,
// Layer // Layer
4 => Sint32, 7 => Sint32,
), ),
}], }],
}, },
@ -180,25 +186,20 @@ impl Pipeline {
multiview: None, multiview: None,
}); });
let cache = Cache::new(device, backend);
let texture = cache.create_bind_group(device, &texture_layout);
Pipeline { Pipeline {
pipeline, pipeline,
backend,
nearest_sampler, nearest_sampler,
linear_sampler, linear_sampler,
texture, texture_layout: Arc::new(texture_layout),
texture_version: cache.layer_count(),
texture_layout,
constant_layout, constant_layout,
cache: cache::Shared::new(cache),
layers: Vec::new(), layers: Vec::new(),
prepare_layer: 0, prepare_layer: 0,
} }
} }
pub fn cache(&self) -> &cache::Shared { pub fn create_cache(&self, device: &wgpu::Device) -> Cache {
&self.cache Cache::new(device, self.backend, self.texture_layout.clone())
} }
pub fn prepare( pub fn prepare(
@ -206,6 +207,7 @@ impl Pipeline {
device: &wgpu::Device, device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt, belt: &mut wgpu::util::StagingBelt,
cache: &mut Cache,
images: &Batch, images: &Batch,
transformation: Transformation, transformation: Transformation,
scale: f32, scale: f32,
@ -215,8 +217,6 @@ impl Pipeline {
let nearest_instances: &mut Vec<Instance> = &mut Vec::new(); let nearest_instances: &mut Vec<Instance> = &mut Vec::new();
let linear_instances: &mut Vec<Instance> = &mut Vec::new(); let linear_instances: &mut Vec<Instance> = &mut Vec::new();
let mut cache = self.cache.lock();
for image in images { for image in images {
match &image { match &image {
#[cfg(feature = "image")] #[cfg(feature = "image")]
@ -224,6 +224,8 @@ impl Pipeline {
handle, handle,
filter_method, filter_method,
bounds, bounds,
rotation,
opacity,
} => { } => {
if let Some(atlas_entry) = if let Some(atlas_entry) =
cache.upload_raster(device, encoder, handle) cache.upload_raster(device, encoder, handle)
@ -231,6 +233,8 @@ impl Pipeline {
add_instances( add_instances(
[bounds.x, bounds.y], [bounds.x, bounds.y],
[bounds.width, bounds.height], [bounds.width, bounds.height],
f32::from(*rotation),
*opacity,
atlas_entry, atlas_entry,
match filter_method { match filter_method {
crate::core::image::FilterMethod::Nearest => { crate::core::image::FilterMethod::Nearest => {
@ -251,6 +255,8 @@ impl Pipeline {
handle, handle,
color, color,
bounds, bounds,
rotation,
opacity,
} => { } => {
let size = [bounds.width, bounds.height]; let size = [bounds.width, bounds.height];
@ -260,6 +266,8 @@ impl Pipeline {
add_instances( add_instances(
[bounds.x, bounds.y], [bounds.x, bounds.y],
size, size,
f32::from(*rotation),
*opacity,
atlas_entry, atlas_entry,
nearest_instances, nearest_instances,
); );
@ -274,16 +282,6 @@ impl Pipeline {
return; return;
} }
let texture_version = cache.layer_count();
if self.texture_version != texture_version {
log::info!("Atlas has grown. Recreating bind group...");
self.texture =
cache.create_bind_group(device, &self.texture_layout);
self.texture_version = texture_version;
}
if self.layers.len() <= self.prepare_layer { if self.layers.len() <= self.prepare_layer {
self.layers.push(Layer::new( self.layers.push(Layer::new(
device, device,
@ -309,6 +307,7 @@ impl Pipeline {
pub fn render<'a>( pub fn render<'a>(
&'a self, &'a self,
cache: &'a Cache,
layer: usize, layer: usize,
bounds: Rectangle<u32>, bounds: Rectangle<u32>,
render_pass: &mut wgpu::RenderPass<'a>, render_pass: &mut wgpu::RenderPass<'a>,
@ -323,14 +322,13 @@ impl Pipeline {
bounds.height, bounds.height,
); );
render_pass.set_bind_group(1, &self.texture, &[]); render_pass.set_bind_group(1, cache.bind_group(), &[]);
layer.render(render_pass); layer.render(render_pass);
} }
} }
pub fn end_frame(&mut self) { pub fn end_frame(&mut self) {
self.cache.lock().trim();
self.prepare_layer = 0; self.prepare_layer = 0;
} }
} }
@ -487,7 +485,10 @@ impl Data {
#[derive(Debug, Clone, Copy, Zeroable, Pod)] #[derive(Debug, Clone, Copy, Zeroable, Pod)]
struct Instance { struct Instance {
_position: [f32; 2], _position: [f32; 2],
_center: [f32; 2],
_size: [f32; 2], _size: [f32; 2],
_rotation: f32,
_opacity: f32,
_position_in_atlas: [f32; 2], _position_in_atlas: [f32; 2],
_size_in_atlas: [f32; 2], _size_in_atlas: [f32; 2],
_layer: u32, _layer: u32,
@ -506,12 +507,27 @@ struct Uniforms {
fn add_instances( fn add_instances(
image_position: [f32; 2], image_position: [f32; 2],
image_size: [f32; 2], image_size: [f32; 2],
rotation: f32,
opacity: f32,
entry: &atlas::Entry, entry: &atlas::Entry,
instances: &mut Vec<Instance>, instances: &mut Vec<Instance>,
) { ) {
let center = [
image_position[0] + image_size[0] / 2.0,
image_position[1] + image_size[1] / 2.0,
];
match entry { match entry {
atlas::Entry::Contiguous(allocation) => { atlas::Entry::Contiguous(allocation) => {
add_instance(image_position, image_size, allocation, instances); add_instance(
image_position,
center,
image_size,
rotation,
opacity,
allocation,
instances,
);
} }
atlas::Entry::Fragmented { fragments, size } => { atlas::Entry::Fragmented { fragments, size } => {
let scaling_x = image_size[0] / size.width as f32; let scaling_x = image_size[0] / size.width as f32;
@ -537,7 +553,10 @@ fn add_instances(
fragment_height as f32 * scaling_y, fragment_height as f32 * scaling_y,
]; ];
add_instance(position, size, allocation, instances); add_instance(
position, center, size, rotation, opacity, allocation,
instances,
);
} }
} }
} }
@ -546,7 +565,10 @@ fn add_instances(
#[inline] #[inline]
fn add_instance( fn add_instance(
position: [f32; 2], position: [f32; 2],
center: [f32; 2],
size: [f32; 2], size: [f32; 2],
rotation: f32,
opacity: f32,
allocation: &atlas::Allocation, allocation: &atlas::Allocation,
instances: &mut Vec<Instance>, instances: &mut Vec<Instance>,
) { ) {
@ -556,7 +578,10 @@ fn add_instance(
let instance = Instance { let instance = Instance {
_position: position, _position: position,
_center: center,
_size: size, _size: size,
_rotation: rotation,
_opacity: opacity,
_position_in_atlas: [ _position_in_atlas: [
(x as f32 + 0.5) / atlas::SIZE as f32, (x as f32 + 0.5) / atlas::SIZE as f32,
(y as f32 + 0.5) / atlas::SIZE as f32, (y as f32 + 0.5) / atlas::SIZE as f32,

View file

@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
#[derive(Debug)] #[derive(Debug)]
pub enum Memory { pub enum Memory {
/// Image data on host /// Image data on host
Host(image_rs::ImageBuffer<image_rs::Rgba<u8>, Vec<u8>>), Host(image_rs::ImageBuffer<image_rs::Rgba<u8>, image::Bytes>),
/// Storage entry /// Storage entry
Device(atlas::Entry), Device(atlas::Entry),
/// Image not found /// Image not found
@ -38,8 +38,9 @@ impl Memory {
/// Caches image raster data /// Caches image raster data
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct Cache { pub struct Cache {
map: FxHashMap<u64, Memory>, map: FxHashMap<image::Id, Memory>,
hits: FxHashSet<u64>, hits: FxHashSet<image::Id>,
should_trim: bool,
} }
impl Cache { impl Cache {
@ -50,11 +51,13 @@ impl Cache {
} }
let memory = match graphics::image::load(handle) { let memory = match graphics::image::load(handle) {
Ok(image) => Memory::Host(image.to_rgba8()), Ok(image) => Memory::Host(image),
Err(image_rs::error::ImageError::IoError(_)) => Memory::NotFound, Err(image_rs::error::ImageError::IoError(_)) => Memory::NotFound,
Err(_) => Memory::Invalid, Err(_) => Memory::Invalid,
}; };
self.should_trim = true;
self.insert(handle, memory); self.insert(handle, memory);
self.get(handle).unwrap() self.get(handle).unwrap()
} }
@ -86,6 +89,11 @@ impl Cache {
/// Trim cache misses from cache /// Trim cache misses from cache
pub fn trim(&mut self, atlas: &mut Atlas) { pub fn trim(&mut self, atlas: &mut Atlas) {
// Only trim if new entries have landed in the `Cache`
if !self.should_trim {
return;
}
let hits = &self.hits; let hits = &self.hits;
self.map.retain(|k, memory| { self.map.retain(|k, memory| {
@ -101,6 +109,7 @@ impl Cache {
}); });
self.hits.clear(); self.hits.clear();
self.should_trim = false;
} }
fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> { fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> {

View file

@ -37,6 +37,7 @@ pub struct Cache {
rasterized: FxHashMap<(u64, u32, u32, ColorFilter), atlas::Entry>, rasterized: FxHashMap<(u64, u32, u32, ColorFilter), atlas::Entry>,
svg_hits: FxHashSet<u64>, svg_hits: FxHashSet<u64>,
rasterized_hits: FxHashSet<(u64, u32, u32, ColorFilter)>, rasterized_hits: FxHashSet<(u64, u32, u32, ColorFilter)>,
should_trim: bool,
} }
type ColorFilter = Option<[u8; 4]>; type ColorFilter = Option<[u8; 4]>;
@ -76,6 +77,8 @@ impl Cache {
} }
} }
self.should_trim = true;
let _ = self.svgs.insert(handle.id(), svg); let _ = self.svgs.insert(handle.id(), svg);
self.svgs.get(&handle.id()).unwrap() self.svgs.get(&handle.id()).unwrap()
} }
@ -176,6 +179,10 @@ impl Cache {
/// Load svg and upload raster data /// Load svg and upload raster data
pub fn trim(&mut self, atlas: &mut Atlas) { pub fn trim(&mut self, atlas: &mut Atlas) {
if !self.should_trim {
return;
}
let svg_hits = &self.svg_hits; let svg_hits = &self.svg_hits;
let rasterized_hits = &self.rasterized_hits; let rasterized_hits = &self.rasterized_hits;
@ -191,6 +198,7 @@ impl Cache {
}); });
self.svg_hits.clear(); self.svg_hits.clear();
self.rasterized_hits.clear(); self.rasterized_hits.clear();
self.should_trim = false;
} }
} }

View file

@ -1,5 +1,6 @@
use crate::core::renderer; use crate::core::{
use crate::core::{Background, Color, Point, Rectangle, Transformation}; renderer, Background, Color, Point, Radians, Rectangle, Transformation,
};
use crate::graphics; use crate::graphics;
use crate::graphics::color; use crate::graphics::color;
use crate::graphics::layer; use crate::graphics::layer;
@ -117,11 +118,15 @@ impl Layer {
filter_method: crate::core::image::FilterMethod, filter_method: crate::core::image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians,
opacity: f32,
) { ) {
let image = Image::Raster { let image = Image::Raster {
handle, handle,
filter_method, filter_method,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation,
opacity,
}; };
self.images.push(image); self.images.push(image);
@ -133,11 +138,15 @@ impl Layer {
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians,
opacity: f32,
) { ) {
let svg = Image::Vector { let svg = Image::Vector {
handle, handle,
color, color,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation,
opacity,
}; };
self.images.push(svg); self.images.push(svg);

View file

@ -62,6 +62,7 @@ pub use geometry::Geometry;
use crate::core::{ use crate::core::{
Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation,
Vector,
}; };
use crate::graphics::text::{Editor, Paragraph}; use crate::graphics::text::{Editor, Paragraph};
use crate::graphics::Viewport; use crate::graphics::Viewport;
@ -81,11 +82,12 @@ pub struct Renderer {
// TODO: Centralize all the image feature handling // TODO: Centralize all the image feature handling
#[cfg(any(feature = "svg", feature = "image"))] #[cfg(any(feature = "svg", feature = "image"))]
image_cache: image::cache::Shared, image_cache: std::cell::RefCell<image::Cache>,
} }
impl Renderer { impl Renderer {
pub fn new( pub fn new(
_device: &wgpu::Device,
_engine: &Engine, _engine: &Engine,
default_font: Font, default_font: Font,
default_text_size: Pixels, default_text_size: Pixels,
@ -99,7 +101,9 @@ impl Renderer {
text_storage: text::Storage::new(), text_storage: text::Storage::new(),
#[cfg(any(feature = "svg", feature = "image"))] #[cfg(any(feature = "svg", feature = "image"))]
image_cache: _engine.image_cache().clone(), image_cache: std::cell::RefCell::new(
_engine.create_image_cache(_device),
),
} }
} }
@ -121,6 +125,9 @@ impl Renderer {
self.triangle_storage.trim(); self.triangle_storage.trim();
self.text_storage.trim(); self.text_storage.trim();
#[cfg(any(feature = "svg", feature = "image"))]
self.image_cache.borrow_mut().trim();
} }
fn prepare( fn prepare(
@ -190,6 +197,7 @@ impl Renderer {
device, device,
encoder, encoder,
&mut engine.staging_belt, &mut engine.staging_belt,
&mut self.image_cache.borrow_mut(),
&layer.images, &layer.images,
viewport.projection(), viewport.projection(),
scale_factor, scale_factor,
@ -245,6 +253,8 @@ impl Renderer {
#[cfg(any(feature = "svg", feature = "image"))] #[cfg(any(feature = "svg", feature = "image"))]
let mut image_layer = 0; let mut image_layer = 0;
#[cfg(any(feature = "svg", feature = "image"))]
let image_cache = self.image_cache.borrow();
let scale_factor = viewport.scale_factor() as f32; let scale_factor = viewport.scale_factor() as f32;
let physical_bounds = Rectangle::<f32>::from(Rectangle::with_size( let physical_bounds = Rectangle::<f32>::from(Rectangle::with_size(
@ -358,6 +368,7 @@ impl Renderer {
#[cfg(any(feature = "svg", feature = "image"))] #[cfg(any(feature = "svg", feature = "image"))]
if !layer.images.is_empty() { if !layer.images.is_empty() {
engine.image_pipeline.render( engine.image_pipeline.render(
&image_cache,
image_layer, image_layer,
scissor_rect, scissor_rect,
&mut render_pass, &mut render_pass,
@ -378,7 +389,6 @@ impl Renderer {
use crate::core::alignment; use crate::core::alignment;
use crate::core::text::Renderer as _; use crate::core::text::Renderer as _;
use crate::core::Renderer as _; use crate::core::Renderer as _;
use crate::core::Vector;
self.with_layer( self.with_layer(
Rectangle::with_size(viewport.logical_size()), Rectangle::with_size(viewport.logical_size()),
@ -509,7 +519,7 @@ impl core::image::Renderer for Renderer {
type Handle = core::image::Handle; type Handle = core::image::Handle;
fn measure_image(&self, handle: &Self::Handle) -> Size<u32> { fn measure_image(&self, handle: &Self::Handle) -> Size<u32> {
self.image_cache.lock().measure_image(handle) self.image_cache.borrow_mut().measure_image(handle)
} }
fn draw_image( fn draw_image(
@ -517,16 +527,25 @@ impl core::image::Renderer for Renderer {
handle: Self::Handle, handle: Self::Handle,
filter_method: core::image::FilterMethod, filter_method: core::image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_image(handle, filter_method, bounds, transformation); layer.draw_image(
handle,
filter_method,
bounds,
transformation,
rotation,
opacity,
);
} }
} }
#[cfg(feature = "svg")] #[cfg(feature = "svg")]
impl core::svg::Renderer for Renderer { impl core::svg::Renderer for Renderer {
fn measure_svg(&self, handle: &core::svg::Handle) -> Size<u32> { fn measure_svg(&self, handle: &core::svg::Handle) -> Size<u32> {
self.image_cache.lock().measure_svg(handle) self.image_cache.borrow_mut().measure_svg(handle)
} }
fn draw_svg( fn draw_svg(
@ -534,9 +553,18 @@ impl core::svg::Renderer for Renderer {
handle: core::svg::Handle, handle: core::svg::Handle,
color_filter: Option<Color>, color_filter: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_svg(handle, color_filter, bounds, transformation); layer.draw_svg(
handle,
color_filter,
bounds,
transformation,
rotation,
opacity,
);
} }
} }

View file

@ -67,7 +67,7 @@ pub struct Storage {
impl Storage { impl Storage {
/// Returns `true` if `Storage` contains a type `T`. /// Returns `true` if `Storage` contains a type `T`.
pub fn has<T: 'static>(&self) -> bool { pub fn has<T: 'static>(&self) -> bool {
self.pipelines.get(&TypeId::of::<T>()).is_some() self.pipelines.contains_key(&TypeId::of::<T>())
} }
/// Inserts the data `T` in to [`Storage`]. /// Inserts the data `T` in to [`Storage`].

View file

@ -51,3 +51,29 @@ impl From<graphics::Settings> for Settings {
} }
} }
} }
/// Obtains a [`wgpu::PresentMode`] from the current environment
/// configuration, if set.
///
/// The value returned by this function can be changed by setting
/// the `ICED_PRESENT_MODE` env variable. The possible values are:
///
/// - `vsync` → [`wgpu::PresentMode::AutoVsync`]
/// - `no_vsync` → [`wgpu::PresentMode::AutoNoVsync`]
/// - `immediate` → [`wgpu::PresentMode::Immediate`]
/// - `fifo` → [`wgpu::PresentMode::Fifo`]
/// - `fifo_relaxed` → [`wgpu::PresentMode::FifoRelaxed`]
/// - `mailbox` → [`wgpu::PresentMode::Mailbox`]
pub fn present_mode_from_env() -> Option<wgpu::PresentMode> {
let present_mode = std::env::var("ICED_PRESENT_MODE").ok()?;
match present_mode.to_lowercase().as_str() {
"vsync" => Some(wgpu::PresentMode::AutoVsync),
"no_vsync" => Some(wgpu::PresentMode::AutoNoVsync),
"immediate" => Some(wgpu::PresentMode::Immediate),
"fifo" => Some(wgpu::PresentMode::Fifo),
"fifo_relaxed" => Some(wgpu::PresentMode::FifoRelaxed),
"mailbox" => Some(wgpu::PresentMode::Mailbox),
_ => None,
}
}

View file

@ -9,40 +9,55 @@ struct Globals {
struct VertexInput { struct VertexInput {
@builtin(vertex_index) vertex_index: u32, @builtin(vertex_index) vertex_index: u32,
@location(0) pos: vec2<f32>, @location(0) pos: vec2<f32>,
@location(1) scale: vec2<f32>, @location(1) center: vec2<f32>,
@location(2) atlas_pos: vec2<f32>, @location(2) scale: vec2<f32>,
@location(3) atlas_scale: vec2<f32>, @location(3) rotation: f32,
@location(4) layer: i32, @location(4) opacity: f32,
@location(5) atlas_pos: vec2<f32>,
@location(6) atlas_scale: vec2<f32>,
@location(7) layer: i32,
} }
struct VertexOutput { struct VertexOutput {
@builtin(position) position: vec4<f32>, @builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>, @location(0) uv: vec2<f32>,
@location(1) layer: f32, // this should be an i32, but naga currently reads that as requiring interpolation. @location(1) layer: f32, // this should be an i32, but naga currently reads that as requiring interpolation.
@location(2) opacity: f32,
} }
@vertex @vertex
fn vs_main(input: VertexInput) -> VertexOutput { fn vs_main(input: VertexInput) -> VertexOutput {
var out: VertexOutput; var out: VertexOutput;
let v_pos = vertex_position(input.vertex_index); // Generate a vertex position in the range [0, 1] from the vertex index.
var v_pos = vertex_position(input.vertex_index);
// Map the vertex position to the atlas texture.
out.uv = vec2<f32>(v_pos * input.atlas_scale + input.atlas_pos); out.uv = vec2<f32>(v_pos * input.atlas_scale + input.atlas_pos);
out.layer = f32(input.layer); out.layer = f32(input.layer);
out.opacity = input.opacity;
var transform: mat4x4<f32> = mat4x4<f32>( // Calculate the vertex position and move the center to the origin
vec4<f32>(input.scale.x, 0.0, 0.0, 0.0), v_pos = input.pos + v_pos * input.scale - input.center;
vec4<f32>(0.0, input.scale.y, 0.0, 0.0),
// Apply the rotation around the center of the image
let cos_rot = cos(input.rotation);
let sin_rot = sin(input.rotation);
let rotate = mat4x4<f32>(
vec4<f32>(cos_rot, sin_rot, 0.0, 0.0),
vec4<f32>(-sin_rot, cos_rot, 0.0, 0.0),
vec4<f32>(0.0, 0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 1.0, 0.0),
vec4<f32>(input.pos, 0.0, 1.0) vec4<f32>(0.0, 0.0, 0.0, 1.0)
); );
out.position = globals.transform * transform * vec4<f32>(v_pos, 0.0, 1.0); // Calculate the final position of the vertex
out.position = globals.transform * (vec4<f32>(input.center, 0.0, 0.0) + rotate * vec4<f32>(v_pos, 0.0, 1.0));
return out; return out;
} }
@fragment @fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
return textureSample(u_texture, u_sampler, input.uv, i32(input.layer)); // Sample the texture at the given UV coordinate and layer.
return textureSample(u_texture, u_sampler, input.uv, i32(input.layer)) * vec4<f32>(1.0, 1.0, 1.0, input.opacity);
} }

View file

@ -1,12 +1,13 @@
use crate::core::alignment; use crate::core::alignment;
use crate::core::{Rectangle, Size, Transformation}; use crate::core::{Rectangle, Size, Transformation};
use crate::graphics::cache;
use crate::graphics::color; use crate::graphics::color;
use crate::graphics::text::cache::{self, Cache as BufferCache}; use crate::graphics::text::cache::{self as text_cache, Cache as BufferCache};
use crate::graphics::text::{font_system, to_color, Editor, Paragraph}; use crate::graphics::text::{font_system, to_color, Editor, Paragraph};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::FxHashMap;
use std::collections::hash_map; use std::collections::hash_map;
use std::rc::Rc; use std::rc::{self, Rc};
use std::sync::atomic::{self, AtomicU64}; use std::sync::atomic::{self, AtomicU64};
use std::sync::Arc; use std::sync::Arc;
@ -35,6 +36,7 @@ pub enum Item {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Cache { pub struct Cache {
id: Id, id: Id,
group: cache::Group,
text: Rc<[Text]>, text: Rc<[Text]>,
version: usize, version: usize,
} }
@ -43,7 +45,7 @@ pub struct Cache {
pub struct Id(u64); pub struct Id(u64);
impl Cache { impl Cache {
pub fn new(text: Vec<Text>) -> Option<Self> { pub fn new(group: cache::Group, text: Vec<Text>) -> Option<Self> {
static NEXT_ID: AtomicU64 = AtomicU64::new(0); static NEXT_ID: AtomicU64 = AtomicU64::new(0);
if text.is_empty() { if text.is_empty() {
@ -52,12 +54,17 @@ impl Cache {
Some(Self { Some(Self {
id: Id(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)), id: Id(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)),
group,
text: Rc::from(text), text: Rc::from(text),
version: 0, version: 0,
}) })
} }
pub fn update(&mut self, text: Vec<Text>) { pub fn update(&mut self, text: Vec<Text>) {
if self.text.is_empty() && text.is_empty() {
return;
}
self.text = Rc::from(text); self.text = Rc::from(text);
self.version += 1; self.version += 1;
} }
@ -65,16 +72,25 @@ impl Cache {
struct Upload { struct Upload {
renderer: glyphon::TextRenderer, renderer: glyphon::TextRenderer,
atlas: glyphon::TextAtlas,
buffer_cache: BufferCache, buffer_cache: BufferCache,
transformation: Transformation, transformation: Transformation,
version: usize, version: usize,
group_version: usize,
text: rc::Weak<[Text]>,
_atlas: rc::Weak<()>,
} }
#[derive(Default)] #[derive(Default)]
pub struct Storage { pub struct Storage {
groups: FxHashMap<cache::Group, Group>,
uploads: FxHashMap<Id, Upload>, uploads: FxHashMap<Id, Upload>,
recently_used: FxHashSet<Id>, }
struct Group {
atlas: glyphon::TextAtlas,
version: usize,
should_trim: bool,
handle: Rc<()>, // Keeps track of active uploads
} }
impl Storage { impl Storage {
@ -82,12 +98,15 @@ impl Storage {
Self::default() Self::default()
} }
fn get(&self, cache: &Cache) -> Option<&Upload> { fn get(&self, cache: &Cache) -> Option<(&glyphon::TextAtlas, &Upload)> {
if cache.text.is_empty() { if cache.text.is_empty() {
return None; return None;
} }
self.uploads.get(&cache.id) self.groups
.get(&cache.group)
.map(|group| &group.atlas)
.zip(self.uploads.get(&cache.id))
} }
fn prepare( fn prepare(
@ -101,41 +120,63 @@ impl Storage {
bounds: Rectangle, bounds: Rectangle,
target_size: Size<u32>, target_size: Size<u32>,
) { ) {
let group_count = self.groups.len();
let group = self.groups.entry(cache.group).or_insert_with(|| {
log::debug!(
"New text atlas: {:?} (total: {})",
cache.group,
group_count + 1
);
Group {
atlas: glyphon::TextAtlas::with_color_mode(
device, queue, format, COLOR_MODE,
),
version: 0,
should_trim: false,
handle: Rc::new(()),
}
});
match self.uploads.entry(cache.id) { match self.uploads.entry(cache.id) {
hash_map::Entry::Occupied(entry) => { hash_map::Entry::Occupied(entry) => {
let upload = entry.into_mut(); let upload = entry.into_mut();
if !cache.text.is_empty() if upload.version != cache.version
&& (upload.version != cache.version || upload.group_version != group.version
|| upload.transformation != new_transformation) || upload.transformation != new_transformation
{ {
let _ = prepare( if !cache.text.is_empty() {
device, let _ = prepare(
queue, device,
encoder, queue,
&mut upload.renderer, encoder,
&mut upload.atlas, &mut upload.renderer,
&mut upload.buffer_cache, &mut group.atlas,
&cache.text, &mut upload.buffer_cache,
bounds, &cache.text,
new_transformation, bounds,
target_size, new_transformation,
); target_size,
);
}
// Only trim if glyphs have changed
group.should_trim =
group.should_trim || upload.version != cache.version;
upload.text = Rc::downgrade(&cache.text);
upload.version = cache.version; upload.version = cache.version;
upload.group_version = group.version;
upload.transformation = new_transformation; upload.transformation = new_transformation;
upload.buffer_cache.trim(); upload.buffer_cache.trim();
upload.atlas.trim();
} }
} }
hash_map::Entry::Vacant(entry) => { hash_map::Entry::Vacant(entry) => {
let mut atlas = glyphon::TextAtlas::with_color_mode(
device, queue, format, COLOR_MODE,
);
let mut renderer = glyphon::TextRenderer::new( let mut renderer = glyphon::TextRenderer::new(
&mut atlas, &mut group.atlas,
device, device,
wgpu::MultisampleState::default(), wgpu::MultisampleState::default(),
None, None,
@ -143,41 +184,76 @@ impl Storage {
let mut buffer_cache = BufferCache::new(); let mut buffer_cache = BufferCache::new();
let _ = prepare( if !cache.text.is_empty() {
device, let _ = prepare(
queue, device,
encoder, queue,
&mut renderer, encoder,
&mut atlas, &mut renderer,
&mut buffer_cache, &mut group.atlas,
&cache.text, &mut buffer_cache,
bounds, &cache.text,
new_transformation, bounds,
target_size, new_transformation,
); target_size,
);
}
let _ = entry.insert(Upload { let _ = entry.insert(Upload {
renderer, renderer,
atlas,
buffer_cache, buffer_cache,
transformation: new_transformation, transformation: new_transformation,
version: 0, version: 0,
group_version: group.version,
text: Rc::downgrade(&cache.text),
_atlas: Rc::downgrade(&group.handle),
}); });
log::info!( group.should_trim = cache.group.is_singleton();
log::debug!(
"New text upload: {} (total: {})", "New text upload: {} (total: {})",
cache.id.0, cache.id.0,
self.uploads.len() self.uploads.len()
); );
} }
} }
let _ = self.recently_used.insert(cache.id);
} }
pub fn trim(&mut self) { pub fn trim(&mut self) {
self.uploads.retain(|id, _| self.recently_used.contains(id)); self.uploads
self.recently_used.clear(); .retain(|_id, upload| upload.text.strong_count() > 0);
self.groups.retain(|id, group| {
let active_uploads = Rc::weak_count(&group.handle);
if active_uploads == 0 {
log::debug!("Dropping text atlas: {id:?}");
return false;
}
if group.should_trim {
log::trace!("Trimming text atlas: {id:?}");
group.atlas.trim();
group.should_trim = false;
// We only need to worry about glyph fighting
// when the atlas may be shared by multiple
// uploads.
if !id.is_singleton() {
log::debug!(
"Invalidating text atlas: {id:?} \
(uploads: {active_uploads})"
);
group.version += 1;
}
}
true
});
} }
} }
@ -306,10 +382,10 @@ impl Pipeline {
layer_count += 1; layer_count += 1;
} }
Item::Cached { cache, .. } => { Item::Cached { cache, .. } => {
if let Some(upload) = storage.get(cache) { if let Some((atlas, upload)) = storage.get(cache) {
upload upload
.renderer .renderer
.render(&upload.atlas, render_pass) .render(atlas, render_pass)
.expect("Render cached text"); .expect("Render cached text");
} }
} }
@ -345,7 +421,7 @@ fn prepare(
enum Allocation { enum Allocation {
Paragraph(Paragraph), Paragraph(Paragraph),
Editor(Editor), Editor(Editor),
Cache(cache::KeyHash), Cache(text_cache::KeyHash),
Raw(Arc<glyphon::Buffer>), Raw(Arc<glyphon::Buffer>),
} }
@ -369,7 +445,7 @@ fn prepare(
} => { } => {
let (key, _) = buffer_cache.allocate( let (key, _) = buffer_cache.allocate(
font_system, font_system,
cache::Key { text_cache::Key {
content, content,
size: f32::from(*size), size: f32::from(*size),
line_height: f32::from(*line_height), line_height: f32::from(*line_height),

Some files were not shown because too many files have changed in this diff Show more