Merge branch 'master' of https://github.com/iced-rs/iced into iced-rs-master
This commit is contained in:
commit
477887b387
120 changed files with 4104 additions and 2129 deletions
2
.github/workflows/check.yml
vendored
2
.github/workflows/check.yml
vendored
|
|
@ -17,8 +17,6 @@ jobs:
|
|||
run: cargo build --package tour --target wasm32-unknown-unknown
|
||||
- name: Check compilation of `todos` example
|
||||
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:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
|
|||
2
.github/workflows/document.yml
vendored
2
.github/workflows/document.yml
vendored
|
|
@ -27,6 +27,8 @@ jobs:
|
|||
-p iced
|
||||
- name: Write CNAME file
|
||||
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
|
||||
if: github.ref == 'refs/heads/master'
|
||||
uses: peaceiris/actions-gh-pages@v3
|
||||
|
|
|
|||
|
|
@ -137,6 +137,7 @@ iced_winit = { version = "0.13.0-dev", path = "winit" }
|
|||
async-std = "1.0"
|
||||
bitflags = "2.0"
|
||||
bytemuck = { version = "1.0", features = ["derive"] }
|
||||
bytes = "1.6"
|
||||
cosmic-text = "0.10"
|
||||
dark-light = "1.0"
|
||||
futures = "0.3"
|
||||
|
|
@ -171,11 +172,11 @@ unicode-segmentation = "1.0"
|
|||
wasm-bindgen-futures = "0.4"
|
||||
wasm-timer = "0.2"
|
||||
web-sys = "=0.3.67"
|
||||
web-time = "0.2"
|
||||
web-time = "1.1"
|
||||
wgpu = "0.19"
|
||||
winapi = "0.3"
|
||||
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]
|
||||
rust_2018_idioms = "forbid"
|
||||
|
|
|
|||
101
benches/wgpu.rs
101
benches/wgpu.rs
|
|
@ -3,7 +3,7 @@ use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
|||
|
||||
use iced::alignment;
|
||||
use iced::mouse;
|
||||
use iced::widget::{canvas, text};
|
||||
use iced::widget::{canvas, stack, text};
|
||||
use iced::{
|
||||
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) {
|
||||
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 - 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(
|
||||
|
|
@ -63,7 +70,8 @@ fn benchmark(
|
|||
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 =
|
||||
graphics::Viewport::with_physical_size(Size::new(3840, 2160), 2.0);
|
||||
|
|
@ -125,52 +133,59 @@ fn benchmark(
|
|||
});
|
||||
}
|
||||
|
||||
fn scene<'a, Message: 'a, Theme: 'a>(
|
||||
n: usize,
|
||||
) -> Element<'a, Message, Theme, Renderer> {
|
||||
fn scene<'a, Message: 'a>(n: usize) -> Element<'a, Message, Theme, Renderer> {
|
||||
struct Scene {
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl<Message, Theme> canvas::Program<Message, Theme, Renderer> for Scene {
|
||||
type State = canvas::Cache<Renderer>;
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
cache: &Self::State,
|
||||
renderer: &Renderer,
|
||||
_theme: &Theme,
|
||||
bounds: Rectangle,
|
||||
_cursor: mouse::Cursor,
|
||||
) -> Vec<canvas::Geometry<Renderer>> {
|
||||
vec![cache.draw(renderer, bounds.size(), |frame| {
|
||||
for i in 0..self.n {
|
||||
frame.fill_rectangle(
|
||||
Point::new(0.0, i as f32),
|
||||
Size::new(10.0, 10.0),
|
||||
Color::WHITE,
|
||||
);
|
||||
}
|
||||
|
||||
for i in 0..self.n {
|
||||
frame.fill_text(canvas::Text {
|
||||
content: i.to_string(),
|
||||
position: Point::new(0.0, i as f32),
|
||||
color: Color::BLACK,
|
||||
size: Pixels::from(16),
|
||||
line_height: text::LineHeight::default(),
|
||||
font: Font::DEFAULT,
|
||||
horizontal_alignment: alignment::Horizontal::Left,
|
||||
vertical_alignment: alignment::Vertical::Top,
|
||||
shaping: text::Shaping::Basic,
|
||||
});
|
||||
}
|
||||
})]
|
||||
}
|
||||
}
|
||||
|
||||
canvas(Scene { n })
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
struct Scene {
|
||||
fn layered_text<'a, Message: 'a>(
|
||||
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,
|
||||
});
|
||||
}
|
||||
})]
|
||||
}
|
||||
) -> Element<'a, Message, Theme, Renderer> {
|
||||
stack((0..n).map(|i| text(format!("I am paragraph {i}!")).into()))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.into()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ advanced = []
|
|||
|
||||
[dependencies]
|
||||
bitflags.workspace = true
|
||||
bytes.workspace = true
|
||||
glam.workspace = true
|
||||
log.workspace = true
|
||||
num-traits.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
use crate::{Point, Rectangle, Vector};
|
||||
|
||||
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
|
||||
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
|
||||
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 {
|
||||
fn eq(&self, other: &f32) -> bool {
|
||||
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
|
||||
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
|
||||
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 {
|
||||
fn from(radians: Radians) -> Self {
|
||||
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 {
|
||||
fn add_assign(&mut self, rhs: Radians) {
|
||||
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 {
|
||||
fn eq(&self, other: &f32) -> bool {
|
||||
self.0.eq(other)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
//! Control the fit of some content (like an image) within a space.
|
||||
use crate::Size;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// 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
|
||||
|
|
@ -11,7 +13,7 @@ use crate::Size;
|
|||
/// in CSS, see [Mozilla's docs][1], or run the `tour` example
|
||||
///
|
||||
/// [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 {
|
||||
/// 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
|
||||
/// any part of it, particularly when the image itself is the focus of the
|
||||
/// screen.
|
||||
#[default]
|
||||
Contain,
|
||||
|
||||
/// 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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,45 @@
|
|||
//! Load and draw raster graphics.
|
||||
use crate::{Rectangle, Size};
|
||||
pub use bytes::Bytes;
|
||||
|
||||
use crate::{Radians, Rectangle, Size};
|
||||
|
||||
use rustc_hash::FxHasher;
|
||||
use std::hash::{Hash, Hasher as _};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A handle of some image data.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Handle {
|
||||
id: u64,
|
||||
data: Data,
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum Handle {
|
||||
/// A file handle. The image data will be read
|
||||
/// 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 {
|
||||
|
|
@ -18,56 +47,48 @@ impl Handle {
|
|||
///
|
||||
/// 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 {
|
||||
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
|
||||
/// 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.
|
||||
/// Creates an image [`Handle`] containing the encoded image data directly.
|
||||
///
|
||||
/// 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
|
||||
/// because you downloaded or generated it procedurally.
|
||||
pub fn from_memory(
|
||||
bytes: impl AsRef<[u8]> + Send + Sync + 'static,
|
||||
) -> Handle {
|
||||
Self::from_data(Data::Bytes(Bytes::new(bytes)))
|
||||
pub fn from_bytes(bytes: impl Into<Bytes>) -> Handle {
|
||||
Self::Bytes(Id::unique(), bytes.into())
|
||||
}
|
||||
|
||||
fn from_data(data: Data) -> Handle {
|
||||
let mut hasher = FxHasher::default();
|
||||
data.hash(&mut hasher);
|
||||
|
||||
Handle {
|
||||
id: hasher.finish(),
|
||||
data,
|
||||
/// Creates an image [`Handle`] containing the decoded image pixels directly.
|
||||
///
|
||||
/// 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
|
||||
/// `width * height * 4`.
|
||||
///
|
||||
/// 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`].
|
||||
pub fn id(&self) -> u64 {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// Returns a reference to the image [`Data`].
|
||||
pub fn data(&self) -> &Data {
|
||||
&self.data
|
||||
pub fn id(&self) -> Id {
|
||||
match self {
|
||||
Handle::Path(id, _)
|
||||
| Handle::Bytes(id, _)
|
||||
| Handle::Rgba { id, .. } => *id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -80,93 +101,49 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
impl Hash 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 {
|
||||
impl std::fmt::Debug for Handle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Data::Path(path) => write!(f, "Path({path:?})"),
|
||||
Data::Bytes(_) => write!(f, "Bytes(...)"),
|
||||
Data::Rgba { width, height, .. } => {
|
||||
Self::Path(_, path) => write!(f, "Path({path:?})"),
|
||||
Self::Bytes(_, _) => write!(f, "Bytes(...)"),
|
||||
Self::Rgba { 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.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
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`]
|
||||
///
|
||||
/// [`Handle`]: Self::Handle
|
||||
type Handle: Clone + Hash;
|
||||
type Handle: Clone;
|
||||
|
||||
/// Returns the dimensions of an image for the given [`Handle`].
|
||||
fn measure_image(&self, handle: &Self::Handle) -> Size<u32>;
|
||||
|
|
@ -196,5 +173,7 @@ pub trait Renderer: crate::Renderer {
|
|||
handle: Self::Handle,
|
||||
filter_method: FilterMethod,
|
||||
bounds: Rectangle,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ impl<'a> Layout<'a> {
|
|||
}
|
||||
|
||||
/// 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| {
|
||||
Layout::with_offset(
|
||||
Vector::new(self.position.x, self.position.y),
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ mod padding;
|
|||
mod pixels;
|
||||
mod point;
|
||||
mod rectangle;
|
||||
mod rotation;
|
||||
mod shadow;
|
||||
mod shell;
|
||||
mod size;
|
||||
|
|
@ -64,6 +65,7 @@ pub use pixels::Pixels;
|
|||
pub use point::Point;
|
||||
pub use rectangle::Rectangle;
|
||||
pub use renderer::Renderer;
|
||||
pub use rotation::Rotation;
|
||||
pub use shadow::Shadow;
|
||||
pub use shell::Shell;
|
||||
pub use size::Size;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
#[allow(missing_docs)]
|
||||
pub enum Interaction {
|
||||
#[default]
|
||||
None,
|
||||
Idle,
|
||||
Pointer,
|
||||
Grab,
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ where
|
|||
_viewport: &Rectangle,
|
||||
_renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
mouse::Interaction::Idle
|
||||
mouse::Interaction::None
|
||||
}
|
||||
|
||||
/// Returns true if the cursor is over the [`Overlay`].
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
pub struct Rectangle<T = f32> {
|
||||
/// X coordinate of the top-left corner.
|
||||
|
|
@ -172,6 +172,18 @@ impl Rectangle<f32> {
|
|||
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> {
|
||||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ use crate::renderer::{self, Renderer};
|
|||
use crate::svg;
|
||||
use crate::text::{self, Text};
|
||||
use crate::{
|
||||
Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation,
|
||||
Background, Color, Font, Pixels, Point, Radians, Rectangle, Size,
|
||||
Transformation,
|
||||
};
|
||||
|
||||
impl Renderer for () {
|
||||
|
|
@ -171,6 +172,8 @@ impl image::Renderer for () {
|
|||
_handle: Self::Handle,
|
||||
_filter_method: image::FilterMethod,
|
||||
_bounds: Rectangle,
|
||||
_rotation: Radians,
|
||||
_opacity: f32,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -185,6 +188,8 @@ impl svg::Renderer for () {
|
|||
_handle: svg::Handle,
|
||||
_color: Option<Color>,
|
||||
_bounds: Rectangle,
|
||||
_rotation: Radians,
|
||||
_opacity: f32,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
|
|||
72
core/src/rotation.rs
Normal file
72
core/src/rotation.rs
Normal 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))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::Vector;
|
||||
use crate::{Radians, Vector};
|
||||
|
||||
/// An amount of space in 2 dimensions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
|
|
@ -51,6 +51,19 @@ impl Size {
|
|||
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> {
|
||||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Load and draw vector graphics.
|
||||
use crate::{Color, Rectangle, Size};
|
||||
use crate::{Color, Radians, Rectangle, Size};
|
||||
|
||||
use rustc_hash::FxHasher;
|
||||
use std::borrow::Cow;
|
||||
|
|
@ -100,5 +100,7 @@ pub trait Renderer: crate::Renderer {
|
|||
handle: Handle,
|
||||
color: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@ impl<T> Vector<T> {
|
|||
impl Vector {
|
||||
/// The zero [`Vector`].
|
||||
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>
|
||||
|
|
|
|||
|
|
@ -137,7 +137,7 @@ where
|
|||
_viewport: &Rectangle,
|
||||
_renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
mouse::Interaction::Idle
|
||||
mouse::Interaction::None
|
||||
}
|
||||
|
||||
/// Returns the overlay of the [`Widget`], if there is any.
|
||||
|
|
|
|||
13
docs/redirect.html
Normal file
13
docs/redirect.html
Normal 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>
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
//! This example showcases an interactive `Canvas` for drawing Bézier curves.
|
||||
use iced::widget::{button, column, text};
|
||||
use iced::{Alignment, Element, Length};
|
||||
use iced::alignment;
|
||||
use iced::widget::{button, container, horizontal_space, hover};
|
||||
use iced::{Element, Length, Theme};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program("Bezier Tool - Iced", Example::update, Example::view)
|
||||
.theme(|_| Theme::CatppuccinMocha)
|
||||
.antialiasing(true)
|
||||
.run()
|
||||
}
|
||||
|
|
@ -35,16 +37,22 @@ impl Example {
|
|||
}
|
||||
|
||||
fn view(&self) -> Element<Message> {
|
||||
column![
|
||||
text("Bezier tool example").width(Length::Shrink).size(50),
|
||||
container(hover(
|
||||
self.bezier.view(&self.curves).map(Message::AddCurve),
|
||||
button("Clear")
|
||||
.style(button::danger)
|
||||
.on_press(Message::Clear),
|
||||
]
|
||||
if self.curves.is_empty() {
|
||||
container(horizontal_space())
|
||||
} else {
|
||||
container(
|
||||
button("Clear")
|
||||
.style(button::danger)
|
||||
.on_press(Message::Clear),
|
||||
)
|
||||
.padding(10)
|
||||
.width(Length::Fill)
|
||||
.align_x(alignment::Horizontal::Right)
|
||||
},
|
||||
))
|
||||
.padding(20)
|
||||
.spacing(20)
|
||||
.align_items(Alignment::Center)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
@ -139,22 +147,24 @@ mod bezier {
|
|||
&self,
|
||||
state: &Self::State,
|
||||
renderer: &Renderer,
|
||||
_theme: &Theme,
|
||||
theme: &Theme,
|
||||
bounds: Rectangle,
|
||||
cursor: mouse::Cursor,
|
||||
) -> Vec<Geometry> {
|
||||
let content =
|
||||
self.state.cache.draw(renderer, bounds.size(), |frame| {
|
||||
Curve::draw_all(self.curves, frame);
|
||||
Curve::draw_all(self.curves, frame, theme);
|
||||
|
||||
frame.stroke(
|
||||
&Path::rectangle(Point::ORIGIN, frame.size()),
|
||||
Stroke::default().with_width(2.0),
|
||||
Stroke::default()
|
||||
.with_width(2.0)
|
||||
.with_color(theme.palette().text),
|
||||
);
|
||||
});
|
||||
|
||||
if let Some(pending) = state {
|
||||
vec![content, pending.draw(renderer, bounds, cursor)]
|
||||
vec![content, pending.draw(renderer, theme, bounds, cursor)]
|
||||
} else {
|
||||
vec![content]
|
||||
}
|
||||
|
|
@ -182,7 +192,7 @@ mod bezier {
|
|||
}
|
||||
|
||||
impl Curve {
|
||||
fn draw_all(curves: &[Curve], frame: &mut Frame) {
|
||||
fn draw_all(curves: &[Curve], frame: &mut Frame, theme: &Theme) {
|
||||
let curves = Path::new(|p| {
|
||||
for curve in curves {
|
||||
p.move_to(curve.from);
|
||||
|
|
@ -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(
|
||||
&self,
|
||||
renderer: &Renderer,
|
||||
theme: &Theme,
|
||||
bounds: Rectangle,
|
||||
cursor: mouse::Cursor,
|
||||
) -> Geometry {
|
||||
|
|
@ -213,7 +229,12 @@ mod bezier {
|
|||
match *self {
|
||||
Pending::One { from } => {
|
||||
let line = Path::line(from, cursor_position);
|
||||
frame.stroke(&line, Stroke::default().with_width(2.0));
|
||||
frame.stroke(
|
||||
&line,
|
||||
Stroke::default()
|
||||
.with_width(2.0)
|
||||
.with_color(theme.palette().text),
|
||||
);
|
||||
}
|
||||
Pending::Two { from, to } => {
|
||||
let curve = Curve {
|
||||
|
|
@ -222,7 +243,7 @@ mod bezier {
|
|||
control: cursor_position,
|
||||
};
|
||||
|
||||
Curve::draw_all(&[curve], &mut frame);
|
||||
Curve::draw_all(&[curve], &mut frame, theme);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{checkbox, column, container, row, text};
|
||||
use iced::{Element, Font, Length};
|
||||
use iced::widget::{center, checkbox, column, row, text};
|
||||
use iced::{Element, Font};
|
||||
|
||||
const ICON_FONT: Font = Font::with_name("icons");
|
||||
|
||||
|
|
@ -68,11 +68,6 @@ impl Example {
|
|||
let content =
|
||||
column![default_checkbox, checkboxes, custom_checkbox].spacing(20);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,3 +10,4 @@ iced.workspace = true
|
|||
iced.features = ["canvas", "tokio", "debug"]
|
||||
|
||||
time = { version = "0.3", features = ["local-offset"] }
|
||||
tracing-subscriber = "0.3"
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ use iced::{
|
|||
};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
iced::program("Clock - Iced", Clock::update, Clock::view)
|
||||
.subscription(Clock::subscription)
|
||||
.theme(Clock::theme)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{
|
||||
column, combo_box, container, scrollable, text, vertical_space,
|
||||
center, column, combo_box, scrollable, text, vertical_space,
|
||||
};
|
||||
use iced::{Alignment, Element, Length};
|
||||
|
||||
|
|
@ -68,12 +68,7 @@ impl Example {
|
|||
.align_items(Alignment::Center)
|
||||
.spacing(10);
|
||||
|
||||
container(scrollable(content))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(scrollable(content)).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::container;
|
||||
use iced::{Element, Length};
|
||||
use iced::widget::center;
|
||||
use iced::Element;
|
||||
|
||||
use numeric_input::numeric_input;
|
||||
|
||||
|
|
@ -27,10 +27,8 @@ impl Component {
|
|||
}
|
||||
|
||||
fn view(&self) -> Element<Message> {
|
||||
container(numeric_input(self.value, Message::NumericInputChanged))
|
||||
center(numeric_input(self.value, Message::NumericInputChanged))
|
||||
.padding(20)
|
||||
.height(Length::Fill)
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,8 +81,8 @@ mod quad {
|
|||
}
|
||||
}
|
||||
|
||||
use iced::widget::{column, container, slider, text};
|
||||
use iced::{Alignment, Color, Element, Length, Shadow, Vector};
|
||||
use iced::widget::{center, column, slider, text};
|
||||
use iced::{Alignment, Color, Element, Shadow, Vector};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::run("Custom Quad - Iced", Example::update, Example::view)
|
||||
|
|
@ -187,12 +187,7 @@ impl Example {
|
|||
.max_width(500)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use scene::Scene;
|
|||
|
||||
use iced::time::Instant;
|
||||
use iced::widget::shader::wgpu;
|
||||
use iced::widget::{checkbox, column, container, row, shader, slider, text};
|
||||
use iced::widget::{center, checkbox, column, row, shader, slider, text};
|
||||
use iced::window;
|
||||
use iced::{Alignment, Color, Element, Length, Subscription};
|
||||
|
||||
|
|
@ -123,12 +123,7 @@ impl IcedCubes {
|
|||
let shader =
|
||||
shader(&self.scene).width(Length::Fill).height(Length::Fill);
|
||||
|
||||
container(column![shader, controls].align_items(Alignment::Center))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(column![shader, controls].align_items(Alignment::Center)).into()
|
||||
}
|
||||
|
||||
fn subscription(&self) -> Subscription<Message> {
|
||||
|
|
|
|||
|
|
@ -82,8 +82,8 @@ mod circle {
|
|||
}
|
||||
|
||||
use circle::circle;
|
||||
use iced::widget::{column, container, slider, text};
|
||||
use iced::{Alignment, Element, Length};
|
||||
use iced::widget::{center, column, slider, text};
|
||||
use iced::{Alignment, Element};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::run("Custom Widget - Iced", Example::update, Example::view)
|
||||
|
|
@ -122,12 +122,7 @@ impl Example {
|
|||
.max_width(500)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
mod download;
|
||||
|
||||
use iced::widget::{button, column, container, progress_bar, text, Column};
|
||||
use iced::{Alignment, Element, Length, Subscription};
|
||||
use iced::widget::{button, center, column, progress_bar, text, Column};
|
||||
use iced::{Alignment, Element, Subscription};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program("Download Progress - Iced", Example::update, Example::view)
|
||||
|
|
@ -67,13 +67,7 @@ impl Example {
|
|||
.spacing(20)
|
||||
.align_items(Alignment::End);
|
||||
|
||||
container(downloads)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.padding(20)
|
||||
.into()
|
||||
center(downloads).padding(20).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -277,7 +277,7 @@ fn action<'a, Message: Clone + 'a>(
|
|||
label: &'a str,
|
||||
on_press: Option<Message>,
|
||||
) -> Element<'a, Message> {
|
||||
let action = button(container(content).width(30).center_x());
|
||||
let action = button(container(content).center_x().width(30));
|
||||
|
||||
if let Some(on_press) = on_press {
|
||||
tooltip(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use iced::alignment;
|
||||
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::{Alignment, Command, Element, Length, Subscription};
|
||||
|
||||
|
|
@ -84,11 +84,6 @@ impl Events {
|
|||
.push(toggle)
|
||||
.push(exit);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use iced::widget::{button, column, container};
|
||||
use iced::widget::{button, center, column};
|
||||
use iced::window;
|
||||
use iced::{Alignment, Command, Element, Length};
|
||||
use iced::{Alignment, Command, Element};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program("Exit - Iced", Exit::update, Exit::view).run()
|
||||
|
|
@ -46,12 +46,6 @@ impl Exit {
|
|||
.spacing(10)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.padding(20)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).padding(20).into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
10
examples/ferris/Cargo.toml
Normal file
10
examples/ferris/Cargo.toml
Normal 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
211
examples/ferris/src/main.rs
Normal 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()
|
||||
}
|
||||
|
|
@ -153,7 +153,7 @@ mod rainbow {
|
|||
}
|
||||
|
||||
use iced::widget::{column, container, scrollable};
|
||||
use iced::{Element, Length};
|
||||
use iced::Element;
|
||||
use rainbow::rainbow;
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
|
|
@ -176,12 +176,7 @@ fn view(_state: &()) -> Element<'_, ()> {
|
|||
.spacing(20)
|
||||
.max_width(500);
|
||||
|
||||
let scrollable =
|
||||
scrollable(container(content).width(Length::Fill).center_x());
|
||||
let scrollable = scrollable(container(content).center_x());
|
||||
|
||||
container(scrollable)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_y()
|
||||
.into()
|
||||
container(scrollable).center_y().into()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,25 +10,8 @@ The __[`main`]__ file contains all the code of the example.
|
|||
|
||||
You can run it with `cargo run`:
|
||||
```
|
||||
cargo run --package integration_wgpu
|
||||
cargo run --package integration
|
||||
```
|
||||
|
||||
### How to run this example with WebGL backend
|
||||
NOTE: Currently, WebGL backend is still experimental, so expect bugs.
|
||||
|
||||
```sh
|
||||
# 0. Install prerequisites
|
||||
cargo install wasm-bindgen-cli https
|
||||
# 1. cd to the current folder
|
||||
# 2. Compile wasm module
|
||||
cargo build -p integration_wgpu --target wasm32-unknown-unknown
|
||||
# 3. Invoke wasm-bindgen
|
||||
wasm-bindgen ../../target/wasm32-unknown-unknown/debug/integration_wgpu.wasm --out-dir . --target web --no-typescript
|
||||
# 4. run http server
|
||||
http
|
||||
# 5. Open 127.0.0.1:8000 in browser
|
||||
```
|
||||
|
||||
|
||||
[`main`]: src/main.rs
|
||||
[`wgpu`]: https://github.com/gfx-rs/wgpu
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
@ -18,305 +18,342 @@ use iced_winit::winit;
|
|||
use iced_winit::Clipboard;
|
||||
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event::WindowEvent,
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
keyboard::ModifiersState,
|
||||
};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use wasm_bindgen::JsCast;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use web_sys::HtmlCanvasElement;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use winit::platform::web::WindowBuilderExtWebSys;
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let canvas_element = {
|
||||
console_log::init().expect("Initialize logger");
|
||||
|
||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||
|
||||
web_sys::window()
|
||||
.and_then(|win| win.document())
|
||||
.and_then(|doc| doc.get_element_by_id("iced_canvas"))
|
||||
.and_then(|element| element.dyn_into::<HtmlCanvasElement>().ok())
|
||||
.expect("Get canvas element")
|
||||
};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn main() -> Result<(), winit::error::EventLoopError> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Initialize winit
|
||||
let event_loop = EventLoop::new()?;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let window = winit::window::WindowBuilder::new()
|
||||
.with_canvas(Some(canvas_element))
|
||||
.build(&event_loop)?;
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum Runner {
|
||||
Loading,
|
||||
Ready {
|
||||
window: Arc<winit::window::Window>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
surface: wgpu::Surface<'static>,
|
||||
format: wgpu::TextureFormat,
|
||||
engine: Engine,
|
||||
renderer: Renderer,
|
||||
scene: Scene,
|
||||
state: program::State<Controls>,
|
||||
cursor_position: Option<winit::dpi::PhysicalPosition<f64>>,
|
||||
clipboard: Clipboard,
|
||||
viewport: Viewport,
|
||||
modifiers: ModifiersState,
|
||||
resized: bool,
|
||||
debug: Debug,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let window = winit::window::Window::new(&event_loop)?;
|
||||
impl winit::application::ApplicationHandler for Runner {
|
||||
fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
|
||||
if let Self::Loading = self {
|
||||
let window = Arc::new(
|
||||
event_loop
|
||||
.create_window(
|
||||
winit::window::WindowAttributes::default(),
|
||||
)
|
||||
.expect("Create window"),
|
||||
);
|
||||
|
||||
let window = Arc::new(window);
|
||||
let physical_size = window.inner_size();
|
||||
let viewport = Viewport::with_physical_size(
|
||||
Size::new(physical_size.width, physical_size.height),
|
||||
window.scale_factor(),
|
||||
);
|
||||
let clipboard = Clipboard::connect(&window);
|
||||
|
||||
let physical_size = window.inner_size();
|
||||
let mut viewport = Viewport::with_physical_size(
|
||||
Size::new(physical_size.width, physical_size.height),
|
||||
window.scale_factor(),
|
||||
);
|
||||
let mut cursor_position = None;
|
||||
let mut modifiers = ModifiersState::default();
|
||||
let mut clipboard = Clipboard::connect(&window);
|
||||
let backend =
|
||||
wgpu::util::backend_bits_from_env().unwrap_or_default();
|
||||
|
||||
// Initialize wgpu
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let default_backend = wgpu::Backends::GL;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let default_backend = wgpu::Backends::PRIMARY;
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: backend,
|
||||
..Default::default()
|
||||
});
|
||||
let surface = instance
|
||||
.create_surface(window.clone())
|
||||
.expect("Create window surface");
|
||||
|
||||
let backend =
|
||||
wgpu::util::backend_bits_from_env().unwrap_or(default_backend);
|
||||
let (format, adapter, device, queue) =
|
||||
futures::futures::executor::block_on(async {
|
||||
let adapter =
|
||||
wgpu::util::initialize_adapter_from_env_or_default(
|
||||
&instance,
|
||||
Some(&surface),
|
||||
)
|
||||
.await
|
||||
.expect("Create adapter");
|
||||
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: backend,
|
||||
..Default::default()
|
||||
});
|
||||
let surface = instance.create_surface(window.clone())?;
|
||||
let adapter_features = adapter.features();
|
||||
|
||||
let (format, adapter, device, queue) =
|
||||
futures::futures::executor::block_on(async {
|
||||
let adapter = wgpu::util::initialize_adapter_from_env_or_default(
|
||||
&instance,
|
||||
Some(&surface),
|
||||
)
|
||||
.await
|
||||
.expect("Create adapter");
|
||||
let capabilities = surface.get_capabilities(&adapter);
|
||||
|
||||
let adapter_features = adapter.features();
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
required_features: adapter_features
|
||||
& wgpu::Features::default(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Request device");
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let needed_limits = wgpu::Limits::downlevel_webgl2_defaults()
|
||||
.using_resolution(adapter.limits());
|
||||
(
|
||||
capabilities
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(wgpu::TextureFormat::is_srgb)
|
||||
.or_else(|| {
|
||||
capabilities.formats.first().copied()
|
||||
})
|
||||
.expect("Get preferred format"),
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
)
|
||||
});
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let needed_limits = wgpu::Limits::default();
|
||||
|
||||
let capabilities = surface.get_capabilities(&adapter);
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
required_features: adapter_features
|
||||
& wgpu::Features::default(),
|
||||
required_limits: needed_limits,
|
||||
surface.configure(
|
||||
&device,
|
||||
&wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: physical_size.width,
|
||||
height: physical_size.height,
|
||||
present_mode: wgpu::PresentMode::AutoVsync,
|
||||
alpha_mode: wgpu::CompositeAlphaMode::Auto,
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Request device");
|
||||
);
|
||||
|
||||
(
|
||||
capabilities
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(wgpu::TextureFormat::is_srgb)
|
||||
.or_else(|| capabilities.formats.first().copied())
|
||||
.expect("Get preferred format"),
|
||||
adapter,
|
||||
// Initialize scene and GUI controls
|
||||
let scene = Scene::new(&device, format);
|
||||
let controls = Controls::new();
|
||||
|
||||
// Initialize iced
|
||||
let mut debug = Debug::new();
|
||||
let engine =
|
||||
Engine::new(&adapter, &device, &queue, format, None);
|
||||
let mut renderer = Renderer::new(
|
||||
&device,
|
||||
&engine,
|
||||
Font::default(),
|
||||
Pixels::from(16),
|
||||
);
|
||||
|
||||
let state = program::State::new(
|
||||
controls,
|
||||
viewport.logical_size(),
|
||||
&mut renderer,
|
||||
&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,
|
||||
queue,
|
||||
)
|
||||
});
|
||||
surface,
|
||||
format,
|
||||
engine,
|
||||
renderer,
|
||||
scene,
|
||||
state,
|
||||
viewport,
|
||||
cursor_position,
|
||||
modifiers,
|
||||
clipboard,
|
||||
resized,
|
||||
debug,
|
||||
} = self
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
surface.configure(
|
||||
&device,
|
||||
&wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: physical_size.width,
|
||||
height: physical_size.height,
|
||||
present_mode: wgpu::PresentMode::AutoVsync,
|
||||
alpha_mode: wgpu::CompositeAlphaMode::Auto,
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
},
|
||||
);
|
||||
match event {
|
||||
WindowEvent::RedrawRequested => {
|
||||
if *resized {
|
||||
let size = window.inner_size();
|
||||
|
||||
let mut resized = false;
|
||||
|
||||
// Initialize scene and GUI controls
|
||||
let scene = Scene::new(&device, format);
|
||||
let controls = Controls::new();
|
||||
|
||||
// Initialize iced
|
||||
let mut 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 },
|
||||
*viewport = Viewport::with_physical_size(
|
||||
Size::new(size.width, size.height),
|
||||
window.scale_factor(),
|
||||
);
|
||||
|
||||
let program = state.program();
|
||||
|
||||
let view = frame.texture.create_view(
|
||||
&wgpu::TextureViewDescriptor::default(),
|
||||
surface.configure(
|
||||
device,
|
||||
&wgpu::SurfaceConfiguration {
|
||||
format: *format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
present_mode: wgpu::PresentMode::AutoVsync,
|
||||
alpha_mode: wgpu::CompositeAlphaMode::Auto,
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
},
|
||||
);
|
||||
|
||||
{
|
||||
// We clear the frame
|
||||
let mut render_pass = Scene::clear(
|
||||
&view,
|
||||
&mut encoder,
|
||||
program.background_color(),
|
||||
*resized = false;
|
||||
}
|
||||
|
||||
match surface.get_current_texture() {
|
||||
Ok(frame) => {
|
||||
let mut encoder = device.create_command_encoder(
|
||||
&wgpu::CommandEncoderDescriptor { label: None },
|
||||
);
|
||||
|
||||
// Draw the scene
|
||||
scene.draw(&mut render_pass);
|
||||
let program = state.program();
|
||||
|
||||
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(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// And then iced on top
|
||||
renderer.present(
|
||||
&mut engine,
|
||||
&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}. \
|
||||
Err(error) => match error {
|
||||
wgpu::SurfaceError::OutOfMemory => {
|
||||
panic!(
|
||||
"Swapchain error: {error}. \
|
||||
Rendering cannot continue."
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
// Try rendering again next frame.
|
||||
window.request_redraw();
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
*cursor_position = Some(position);
|
||||
}
|
||||
WindowEvent::ModifiersChanged(new_modifiers) => {
|
||||
*modifiers = new_modifiers.state();
|
||||
}
|
||||
WindowEvent::Resized(_) => {
|
||||
*resized = true;
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
event_loop.exit();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Map window event to iced event
|
||||
if let Some(event) = iced_winit::conversion::window_event(
|
||||
window::Id::MAIN,
|
||||
event,
|
||||
window.scale_factor(),
|
||||
*modifiers,
|
||||
) {
|
||||
state.queue_event(event);
|
||||
}
|
||||
|
||||
// If there are events pending
|
||||
if !state.is_queue_empty() {
|
||||
// We update iced
|
||||
let _ = state.update(
|
||||
viewport.logical_size(),
|
||||
cursor_position
|
||||
.map(|p| {
|
||||
conversion::cursor_position(
|
||||
p,
|
||||
viewport.scale_factor(),
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
// Try rendering again next frame.
|
||||
window.request_redraw();
|
||||
}
|
||||
})
|
||||
.map(mouse::Cursor::Available)
|
||||
.unwrap_or(mouse::Cursor::Unavailable),
|
||||
renderer,
|
||||
&Theme::Dark,
|
||||
&renderer::Style {
|
||||
text_color: Color::WHITE,
|
||||
},
|
||||
}
|
||||
clipboard,
|
||||
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
|
||||
if !state.is_queue_empty() {
|
||||
// We update iced
|
||||
let _ = state.update(
|
||||
viewport.logical_size(),
|
||||
cursor_position
|
||||
.map(|p| {
|
||||
conversion::cursor_position(p, viewport.scale_factor())
|
||||
})
|
||||
.map(mouse::Cursor::Available)
|
||||
.unwrap_or(mouse::Cursor::Unavailable),
|
||||
&mut renderer,
|
||||
&Theme::Dark,
|
||||
&renderer::Style {
|
||||
text_color: Color::WHITE,
|
||||
},
|
||||
&mut clipboard,
|
||||
&mut debug,
|
||||
);
|
||||
|
||||
// and request a redraw
|
||||
window.request_redraw();
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
let mut runner = Runner::Loading;
|
||||
event_loop.run_app(&mut runner)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use iced::keyboard;
|
||||
use iced::mouse;
|
||||
use iced::widget::{
|
||||
button, canvas, checkbox, column, container, horizontal_space, pick_list,
|
||||
row, scrollable, text,
|
||||
button, canvas, center, checkbox, column, container, horizontal_space,
|
||||
pick_list, row, scrollable, text,
|
||||
};
|
||||
use iced::{
|
||||
color, Alignment, Element, Font, Length, Point, Rectangle, Renderer,
|
||||
|
|
@ -76,7 +76,7 @@ impl Layout {
|
|||
.spacing(20)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
let example = container(if self.explain {
|
||||
let example = center(if self.explain {
|
||||
self.example.view().explain(color!(0x0000ff))
|
||||
} else {
|
||||
self.example.view()
|
||||
|
|
@ -87,11 +87,7 @@ impl Layout {
|
|||
container::Style::default()
|
||||
.with_border(palette.background.strong.color, 4.0)
|
||||
})
|
||||
.padding(4)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y();
|
||||
.padding(4);
|
||||
|
||||
let controls = row([
|
||||
(!self.example.is_first()).then_some(
|
||||
|
|
@ -195,12 +191,7 @@ impl Default for Example {
|
|||
}
|
||||
|
||||
fn centered<'a>() -> Element<'a, Message> {
|
||||
container(text("I am centered!").size(50))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(text("I am centered!").size(50)).into()
|
||||
}
|
||||
|
||||
fn column_<'a>() -> Element<'a, Message> {
|
||||
|
|
@ -260,7 +251,6 @@ fn application<'a>() -> Element<'a, Message> {
|
|||
.align_items(Alignment::Center),
|
||||
)
|
||||
.style(container::rounded_box)
|
||||
.height(Length::Fill)
|
||||
.center_y();
|
||||
|
||||
let content = container(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{column, container, row, slider, text};
|
||||
use iced::{Element, Length};
|
||||
use iced::widget::{center, column, row, slider, text};
|
||||
use iced::Element;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
|
|
@ -73,7 +73,7 @@ impl LoadingSpinners {
|
|||
})
|
||||
.spacing(20);
|
||||
|
||||
container(
|
||||
center(
|
||||
column.push(
|
||||
row![
|
||||
text("Cycle duration:"),
|
||||
|
|
@ -87,10 +87,6 @@ impl LoadingSpinners {
|
|||
.spacing(20.0),
|
||||
),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{button, column, container, text};
|
||||
use iced::{Alignment, Element, Length};
|
||||
use iced::widget::{button, center, column, text};
|
||||
use iced::{Alignment, Element};
|
||||
|
||||
use loupe::loupe;
|
||||
|
||||
|
|
@ -31,7 +31,7 @@ impl Loupe {
|
|||
}
|
||||
|
||||
fn view(&self) -> Element<Message> {
|
||||
container(loupe(
|
||||
center(loupe(
|
||||
3.0,
|
||||
column![
|
||||
button("Increment").on_press(Message::Increment),
|
||||
|
|
@ -41,10 +41,6 @@ impl Loupe {
|
|||
.padding(20)
|
||||
.align_items(Alignment::Center),
|
||||
))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
@ -159,7 +155,7 @@ mod loupe {
|
|||
if cursor.is_over(layout.bounds()) {
|
||||
mouse::Interaction::ZoomIn
|
||||
} else {
|
||||
mouse::Interaction::Idle
|
||||
mouse::Interaction::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,11 @@ use iced::event::{self, Event};
|
|||
use iced::keyboard;
|
||||
use iced::keyboard::key;
|
||||
use iced::widget::{
|
||||
self, button, column, container, horizontal_space, pick_list, row, text,
|
||||
text_input,
|
||||
self, button, center, column, container, horizontal_space, mouse_area,
|
||||
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;
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
|
|
@ -99,13 +98,7 @@ impl App {
|
|||
row![text("Top Left"), horizontal_space(), text("Top Right")]
|
||||
.align_items(Alignment::Start)
|
||||
.height(Length::Fill),
|
||||
container(
|
||||
button(text("Show Modal")).on_press(Message::ShowModal)
|
||||
)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill),
|
||||
center(button(text("Show Modal")).on_press(Message::ShowModal)),
|
||||
row![
|
||||
text("Bottom Left"),
|
||||
horizontal_space(),
|
||||
|
|
@ -116,12 +109,10 @@ impl App {
|
|||
]
|
||||
.height(Length::Fill),
|
||||
)
|
||||
.padding(10)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill);
|
||||
.padding(10);
|
||||
|
||||
if self.show_modal {
|
||||
let modal = container(
|
||||
let signup = container(
|
||||
column![
|
||||
text("Sign Up").size(24),
|
||||
column![
|
||||
|
|
@ -162,9 +153,7 @@ impl App {
|
|||
.padding(10)
|
||||
.style(container::rounded_box);
|
||||
|
||||
Modal::new(content, modal)
|
||||
.on_blur(Message::HideModal)
|
||||
.into()
|
||||
modal(content, signup, Message::HideModal)
|
||||
} else {
|
||||
content.into()
|
||||
}
|
||||
|
|
@ -203,326 +192,29 @@ impl fmt::Display for Plan {
|
|||
}
|
||||
}
|
||||
|
||||
mod modal {
|
||||
use iced::advanced::layout::{self, Layout};
|
||||
use iced::advanced::overlay;
|
||||
use iced::advanced::renderer;
|
||||
use iced::advanced::widget::{self, Widget};
|
||||
use iced::advanced::{self, Clipboard, Shell};
|
||||
use iced::alignment::Alignment;
|
||||
use iced::event;
|
||||
use iced::mouse;
|
||||
use iced::{Color, Element, Event, Length, Point, Rectangle, Size, Vector};
|
||||
|
||||
/// A widget that centers a modal element over some base element
|
||||
pub struct Modal<'a, Message, Theme, Renderer> {
|
||||
base: Element<'a, Message, Theme, Renderer>,
|
||||
modal: Element<'a, Message, Theme, Renderer>,
|
||||
on_blur: Option<Message>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> Modal<'a, Message, Theme, Renderer> {
|
||||
/// Returns a new [`Modal`]
|
||||
pub fn new(
|
||||
base: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
modal: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
base: base.into(),
|
||||
modal: modal.into(),
|
||||
on_blur: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the message that will be produces when the background
|
||||
/// of the [`Modal`] is pressed
|
||||
pub fn on_blur(self, on_blur: Message) -> Self {
|
||||
Self {
|
||||
on_blur: Some(on_blur),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for Modal<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: advanced::Renderer,
|
||||
Message: Clone,
|
||||
{
|
||||
fn children(&self) -> Vec<widget::Tree> {
|
||||
vec![
|
||||
widget::Tree::new(&self.base),
|
||||
widget::Tree::new(&self.modal),
|
||||
]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut widget::Tree) {
|
||||
tree.diff_children(&[&self.base, &self.modal]);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.base.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&self,
|
||||
tree: &mut widget::Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
self.base.as_widget().layout(
|
||||
&mut tree.children[0],
|
||||
renderer,
|
||||
limits,
|
||||
)
|
||||
}
|
||||
|
||||
fn on_event(
|
||||
&mut self,
|
||||
state: &mut widget::Tree,
|
||||
event: Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) -> event::Status {
|
||||
self.base.as_widget_mut().on_event(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &widget::Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.base.as_widget().draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
_renderer: &Renderer,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
Some(overlay::Element::new(Box::new(Overlay {
|
||||
position: layout.position() + translation,
|
||||
content: &mut self.modal,
|
||||
tree: &mut state.children[1],
|
||||
size: layout.bounds().size(),
|
||||
on_blur: self.on_blur.clone(),
|
||||
})))
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.base.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&self,
|
||||
state: &mut widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation<Message>,
|
||||
) {
|
||||
self.base.as_widget().operate(
|
||||
&mut state.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct Overlay<'a, 'b, Message, Theme, Renderer> {
|
||||
position: Point,
|
||||
content: &'b mut Element<'a, Message, Theme, Renderer>,
|
||||
tree: &'b mut widget::Tree,
|
||||
size: Size,
|
||||
on_blur: Option<Message>,
|
||||
}
|
||||
|
||||
impl<'a, 'b, Message, Theme, Renderer>
|
||||
overlay::Overlay<Message, Theme, Renderer>
|
||||
for Overlay<'a, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: advanced::Renderer,
|
||||
Message: Clone,
|
||||
{
|
||||
fn layout(
|
||||
&mut self,
|
||||
renderer: &Renderer,
|
||||
_bounds: Size,
|
||||
) -> layout::Node {
|
||||
let limits = layout::Limits::new(Size::ZERO, self.size)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill);
|
||||
|
||||
let child = self
|
||||
.content
|
||||
.as_widget()
|
||||
.layout(self.tree, renderer, &limits)
|
||||
.align(Alignment::Center, Alignment::Center, limits.max());
|
||||
|
||||
layout::Node::with_children(self.size, vec![child])
|
||||
.move_to(self.position)
|
||||
}
|
||||
|
||||
fn on_event(
|
||||
&mut self,
|
||||
event: Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) -> event::Status {
|
||||
let content_bounds = layout.children().next().unwrap().bounds();
|
||||
|
||||
if let Some(message) = self.on_blur.as_ref() {
|
||||
if let Event::Mouse(mouse::Event::ButtonPressed(
|
||||
mouse::Button::Left,
|
||||
)) = &event
|
||||
{
|
||||
if !cursor.is_over(content_bounds) {
|
||||
shell.publish(message.clone());
|
||||
return event::Status::Captured;
|
||||
fn modal<'a, Message>(
|
||||
base: impl Into<Element<'a, Message>>,
|
||||
content: impl Into<Element<'a, Message>>,
|
||||
on_blur: Message,
|
||||
) -> Element<'a, Message>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
{
|
||||
stack![
|
||||
base.into(),
|
||||
mouse_area(center(opaque(content)).style(|_theme| {
|
||||
container::Style {
|
||||
background: Some(
|
||||
Color {
|
||||
a: 0.8,
|
||||
..Color::BLACK
|
||||
}
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
..container::Style::default()
|
||||
}
|
||||
|
||||
self.content.as_widget_mut().on_event(
|
||||
self.tree,
|
||||
event,
|
||||
layout.children().next().unwrap(),
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
&layout.bounds(),
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: layout.bounds(),
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
Color {
|
||||
a: 0.80,
|
||||
..Color::BLACK
|
||||
},
|
||||
);
|
||||
|
||||
self.content.as_widget().draw(
|
||||
self.tree,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout.children().next().unwrap(),
|
||||
cursor,
|
||||
&layout.bounds(),
|
||||
);
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation<Message>,
|
||||
) {
|
||||
self.content.as_widget().operate(
|
||||
self.tree,
|
||||
layout.children().next().unwrap(),
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.content.as_widget().mouse_interaction(
|
||||
self.tree,
|
||||
layout.children().next().unwrap(),
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn overlay<'c>(
|
||||
&'c mut self,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
) -> Option<overlay::Element<'c, Message, Theme, Renderer>> {
|
||||
self.content.as_widget_mut().overlay(
|
||||
self.tree,
|
||||
layout.children().next().unwrap(),
|
||||
renderer,
|
||||
Vector::ZERO,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<Modal<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: 'a,
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + advanced::Renderer,
|
||||
{
|
||||
fn from(modal: Modal<'a, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(modal)
|
||||
}
|
||||
}
|
||||
}))
|
||||
.on_press(on_blur)
|
||||
]
|
||||
.into()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
use iced::event;
|
||||
use iced::executor;
|
||||
use iced::multi_window::{self, Application};
|
||||
use iced::widget::{button, column, container, scrollable, text, text_input};
|
||||
use iced::widget::{
|
||||
button, center, column, container, scrollable, text, text_input,
|
||||
};
|
||||
use iced::window;
|
||||
use iced::{
|
||||
Alignment, Command, Element, Length, Point, Settings, Subscription, Theme,
|
||||
|
|
@ -128,12 +130,7 @@ impl multi_window::Application for Example {
|
|||
fn view(&self, window: window::Id) -> Element<Message> {
|
||||
let content = self.windows.get(&window).unwrap().view(window);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
|
||||
fn theme(&self, window: window::Id) -> Self::Theme {
|
||||
|
|
@ -210,6 +207,6 @@ impl Window {
|
|||
.align_items(Alignment::Center),
|
||||
);
|
||||
|
||||
container(content).width(200).center_x().into()
|
||||
container(content).center_x().width(200).into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,12 +291,7 @@ fn view_content<'a>(
|
|||
.spacing(10)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(scrollable(content))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.padding(5)
|
||||
.center_y()
|
||||
.into()
|
||||
container(scrollable(content)).center_y().padding(5).into()
|
||||
}
|
||||
|
||||
fn view_controls<'a>(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
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};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
|
|
@ -83,12 +83,7 @@ impl Pokedex {
|
|||
.align_items(Alignment::End),
|
||||
};
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -188,7 +183,7 @@ impl Pokemon {
|
|||
{
|
||||
let bytes = reqwest::get(&url).await?.bytes().await?;
|
||||
|
||||
Ok(image::Handle::from_memory(bytes))
|
||||
Ok(image::Handle::from_bytes(bytes))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
use iced::widget::{
|
||||
column, container, pick_list, qr_code, row, text, text_input,
|
||||
};
|
||||
use iced::{Alignment, Element, Length, Theme};
|
||||
use iced::widget::{center, column, pick_list, qr_code, row, text, text_input};
|
||||
use iced::{Alignment, Element, Theme};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program(
|
||||
|
|
@ -72,13 +70,7 @@ impl QRGenerator {
|
|||
.spacing(20)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.padding(20)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).padding(20).into()
|
||||
}
|
||||
|
||||
fn theme(&self) -> Theme {
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ impl Example {
|
|||
fn view(&self) -> Element<'_, Message> {
|
||||
let image: Element<Message> = if let Some(screenshot) = &self.screenshot
|
||||
{
|
||||
image(image::Handle::from_pixels(
|
||||
image(image::Handle::from_rgba(
|
||||
screenshot.size.width,
|
||||
screenshot.size.height,
|
||||
screenshot.clone(),
|
||||
|
|
@ -123,12 +123,10 @@ impl Example {
|
|||
};
|
||||
|
||||
let image = container(image)
|
||||
.center_y()
|
||||
.padding(10)
|
||||
.style(container::rounded_box)
|
||||
.width(Length::FillPortion(2))
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y();
|
||||
.width(Length::FillPortion(2));
|
||||
|
||||
let crop_origin_controls = row![
|
||||
text("X:")
|
||||
|
|
@ -213,12 +211,7 @@ impl Example {
|
|||
.spacing(40)
|
||||
};
|
||||
|
||||
let side_content = container(controls)
|
||||
.align_x(alignment::Horizontal::Center)
|
||||
.width(Length::FillPortion(1))
|
||||
.height(Length::Fill)
|
||||
.center_y()
|
||||
.center_x();
|
||||
let side_content = container(controls).center_y();
|
||||
|
||||
let content = row![side_content, image]
|
||||
.spacing(10)
|
||||
|
|
@ -226,13 +219,7 @@ impl Example {
|
|||
.height(Length::Fill)
|
||||
.align_items(Alignment::Center);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.padding(10)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
container(content).padding(10).into()
|
||||
}
|
||||
|
||||
fn subscription(&self) -> Subscription<Message> {
|
||||
|
|
|
|||
|
|
@ -327,7 +327,7 @@ impl ScrollableDemo {
|
|||
.spacing(10)
|
||||
.into();
|
||||
|
||||
container(content).padding(20).center_x().center_y().into()
|
||||
container(content).padding(20).into()
|
||||
}
|
||||
|
||||
fn theme(&self) -> Theme {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{column, container, slider, text, vertical_slider};
|
||||
use iced::{Element, Length};
|
||||
use iced::widget::{center, column, container, slider, text, vertical_slider};
|
||||
use iced::Element;
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::run("Slider - Iced", Slider::update, Slider::view)
|
||||
|
|
@ -54,18 +54,14 @@ impl Slider {
|
|||
|
||||
let text = text(self.value);
|
||||
|
||||
container(
|
||||
center(
|
||||
column![
|
||||
container(v_slider).width(Length::Fill).center_x(),
|
||||
container(h_slider).width(Length::Fill).center_x(),
|
||||
container(text).width(Length::Fill).center_x(),
|
||||
container(v_slider).center_x(),
|
||||
container(h_slider).center_x(),
|
||||
container(text).center_x()
|
||||
]
|
||||
.spacing(25),
|
||||
)
|
||||
.height(Length::Fill)
|
||||
.width(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use iced::alignment;
|
||||
use iced::keyboard;
|
||||
use iced::time;
|
||||
use iced::widget::{button, column, container, row, text};
|
||||
use iced::{Alignment, Element, Length, Subscription, Theme};
|
||||
use iced::widget::{button, center, column, row, text};
|
||||
use iced::{Alignment, Element, Subscription, Theme};
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
|
|
@ -128,12 +128,7 @@ impl Stopwatch {
|
|||
.align_items(Alignment::Center)
|
||||
.spacing(20);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
|
||||
fn theme(&self) -> Theme {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use iced::widget::{
|
||||
button, checkbox, column, container, horizontal_rule, pick_list,
|
||||
progress_bar, row, scrollable, slider, text, text_input, toggler,
|
||||
vertical_rule, vertical_space,
|
||||
button, center, checkbox, column, horizontal_rule, pick_list, progress_bar,
|
||||
row, scrollable, slider, text, text_input, toggler, vertical_rule,
|
||||
vertical_space,
|
||||
};
|
||||
use iced::{Alignment, Element, Length, Theme};
|
||||
|
||||
|
|
@ -106,12 +106,7 @@ impl Styling {
|
|||
.padding(20)
|
||||
.max_width(600);
|
||||
|
||||
container(content)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content).into()
|
||||
}
|
||||
|
||||
fn theme(&self) -> Theme {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use iced::widget::{checkbox, column, container, svg};
|
||||
use iced::widget::{center, checkbox, column, container, svg};
|
||||
use iced::{color, Element, Length};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
|
|
@ -44,19 +44,12 @@ impl Tiger {
|
|||
checkbox("Apply a color filter", self.apply_color_filter)
|
||||
.on_toggle(Message::ToggleColorFilter);
|
||||
|
||||
container(
|
||||
column![
|
||||
svg,
|
||||
container(apply_color_filter).width(Length::Fill).center_x()
|
||||
]
|
||||
.spacing(20)
|
||||
.height(Length::Fill),
|
||||
center(
|
||||
column![svg, container(apply_color_filter).center_x()]
|
||||
.spacing(20)
|
||||
.height(Length::Fill),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.padding(20)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use iced::widget::{button, column, container, text};
|
||||
use iced::{system, Command, Element, Length};
|
||||
use iced::{system, Command, Element};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program("System Information - Iced", Example::update, Example::view)
|
||||
|
|
@ -136,11 +136,6 @@ impl Example {
|
|||
}
|
||||
};
|
||||
|
||||
container(content)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.into()
|
||||
container(content).center().into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
13
examples/the_matrix/Cargo.toml
Normal file
13
examples/the_matrix/Cargo.toml
Normal 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"
|
||||
115
examples/the_matrix/src/main.rs
Normal file
115
examples/the_matrix/src/main.rs
Normal 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()
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
)]
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ use iced::event::{self, Event};
|
|||
use iced::keyboard;
|
||||
use iced::keyboard::key;
|
||||
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};
|
||||
|
||||
|
|
@ -102,7 +102,7 @@ impl App {
|
|||
.then_some(Message::Add),
|
||||
);
|
||||
|
||||
let content = container(
|
||||
let content = center(
|
||||
column![
|
||||
subtitle(
|
||||
"Title",
|
||||
|
|
@ -146,11 +146,7 @@ impl App {
|
|||
]
|
||||
.spacing(10)
|
||||
.max_width(200),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y();
|
||||
);
|
||||
|
||||
toast::Manager::new(content, &self.toasts, Message::Close)
|
||||
.timeout(self.timeout_secs)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use iced::alignment::{self, Alignment};
|
||||
use iced::keyboard;
|
||||
use iced::widget::{
|
||||
self, button, checkbox, column, container, keyed_column, row, scrollable,
|
||||
text, text_input, Text,
|
||||
self, button, center, checkbox, column, container, keyed_column, row,
|
||||
scrollable, text, text_input, Text,
|
||||
};
|
||||
use iced::window;
|
||||
use iced::{Command, Element, Font, Length, Subscription};
|
||||
|
|
@ -238,7 +238,7 @@ impl Todos {
|
|||
.spacing(20)
|
||||
.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> {
|
||||
container(
|
||||
center(
|
||||
text("Loading...")
|
||||
.horizontal_alignment(alignment::Horizontal::Center)
|
||||
.size(50),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
|
||||
fn empty_message(message: &str) -> Element<'_, Message> {
|
||||
container(
|
||||
center(
|
||||
text(message)
|
||||
.width(Length::Fill)
|
||||
.size(25)
|
||||
|
|
@ -455,7 +452,6 @@ fn empty_message(message: &str) -> Element<'_, Message> {
|
|||
.color([0.7, 0.7, 0.7]),
|
||||
)
|
||||
.height(200)
|
||||
.center_y()
|
||||
.into()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use iced::widget::tooltip::Position;
|
||||
use iced::widget::{button, container, tooltip};
|
||||
use iced::{Element, Length};
|
||||
use iced::widget::{button, center, container, tooltip};
|
||||
use iced::Element;
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::run("Tooltip - Iced", Tooltip::update, Tooltip::view)
|
||||
|
|
@ -43,12 +43,7 @@ impl Tooltip {
|
|||
.gap(10)
|
||||
.style(container::rounded_box);
|
||||
|
||||
container(tooltip)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(tooltip).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,11 +76,10 @@ impl Tour {
|
|||
} else {
|
||||
content
|
||||
})
|
||||
.width(Length::Fill)
|
||||
.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)
|
||||
.width(width),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.center_x()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use iced::event::{self, Event};
|
||||
use iced::widget::{container, text};
|
||||
use iced::{Element, Length, Subscription};
|
||||
use iced::widget::{center, text};
|
||||
use iced::{Element, Subscription};
|
||||
|
||||
pub fn main() -> iced::Result {
|
||||
iced::program("URL Handler - Iced", App::update, App::view)
|
||||
|
|
@ -44,11 +44,6 @@ impl App {
|
|||
None => text("No URL received yet!"),
|
||||
};
|
||||
|
||||
container(content.size(48))
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
center(content.size(48)).into()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ mod echo;
|
|||
|
||||
use iced::alignment::{self, Alignment};
|
||||
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 once_cell::sync::Lazy;
|
||||
|
|
@ -31,7 +31,10 @@ enum Message {
|
|||
|
||||
impl WebSocket {
|
||||
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> {
|
||||
|
|
@ -85,14 +88,10 @@ impl WebSocket {
|
|||
|
||||
fn view(&self) -> Element<Message> {
|
||||
let message_log: Element<_> = if self.messages.is_empty() {
|
||||
container(
|
||||
center(
|
||||
text("Your messages will appear here...")
|
||||
.color(color!(0x888888)),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.center_x()
|
||||
.center_y()
|
||||
.into()
|
||||
} else {
|
||||
scrollable(
|
||||
|
|
|
|||
|
|
@ -55,13 +55,15 @@ pub mod time {
|
|||
|
||||
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 = {
|
||||
futures::stream::unfold(
|
||||
tokio::time::interval_at(start, self.0),
|
||||
|mut interval| async move {
|
||||
Some((interval.tick().await, interval))
|
||||
},
|
||||
)
|
||||
futures::stream::unfold(interval, |mut interval| async move {
|
||||
Some((interval.tick().await, interval))
|
||||
})
|
||||
};
|
||||
|
||||
stream.map(tokio::time::Instant::into_std).boxed()
|
||||
|
|
|
|||
189
graphics/src/cache.rs
Normal file
189
graphics/src/cache.rs
Normal 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 {
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {}
|
||||
}
|
||||
|
|
@ -18,8 +18,8 @@ pub use text::Text;
|
|||
|
||||
pub use crate::gradient::{self, Gradient};
|
||||
|
||||
use crate::cache::Cached;
|
||||
use crate::core::{self, Size};
|
||||
use crate::Cached;
|
||||
|
||||
/// A renderer capable of drawing some [`Self::Geometry`].
|
||||
pub trait Renderer: core::Renderer {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use crate::cache::{self, Cached};
|
||||
use crate::core::Size;
|
||||
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.
|
||||
///
|
||||
|
|
@ -12,7 +12,13 @@ pub struct Cache<Renderer>
|
|||
where
|
||||
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>
|
||||
|
|
@ -22,20 +28,25 @@ where
|
|||
/// Creates a new empty [`Cache`].
|
||||
pub fn new() -> Self {
|
||||
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.
|
||||
pub fn clear(&self) {
|
||||
use std::ops::Deref;
|
||||
|
||||
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 };
|
||||
self.raw.clear();
|
||||
}
|
||||
|
||||
/// Draws geometry using the provided closure and stores it in the
|
||||
|
|
@ -56,27 +67,30 @@ where
|
|||
) -> Renderer::Geometry {
|
||||
use std::ops::Deref;
|
||||
|
||||
let previous = match self.state.borrow().deref() {
|
||||
State::Empty { previous } => previous.clone(),
|
||||
State::Filled {
|
||||
bounds: cached_bounds,
|
||||
geometry,
|
||||
} => {
|
||||
if *cached_bounds == bounds {
|
||||
return Cached::load(geometry);
|
||||
let state = self.raw.state();
|
||||
|
||||
let previous = match state.borrow().deref() {
|
||||
cache::State::Empty { previous } => {
|
||||
previous.as_ref().map(|data| data.geometry.clone())
|
||||
}
|
||||
cache::State::Filled { current } => {
|
||||
if current.bounds == bounds {
|
||||
return Cached::load(¤t.geometry);
|
||||
}
|
||||
|
||||
Some(geometry.clone())
|
||||
Some(current.geometry.clone())
|
||||
}
|
||||
};
|
||||
|
||||
let mut frame = Frame::new(renderer, bounds);
|
||||
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);
|
||||
|
||||
*self.state.borrow_mut() = State::Filled { bounds, geometry };
|
||||
*state.borrow_mut() = cache::State::Filled {
|
||||
current: Data { bounds, geometry },
|
||||
};
|
||||
|
||||
result
|
||||
}
|
||||
|
|
@ -85,16 +99,10 @@ where
|
|||
impl<Renderer> std::fmt::Debug for Cache<Renderer>
|
||||
where
|
||||
Renderer: geometry::Renderer,
|
||||
<Renderer::Geometry as Cached>::Cache: std::fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let state = self.state.borrow();
|
||||
|
||||
match *state {
|
||||
State::Empty { .. } => write!(f, "Cache::Empty"),
|
||||
State::Filled { bounds, .. } => {
|
||||
write!(f, "Cache::Filled {{ bounds: {bounds:?} }}")
|
||||
}
|
||||
}
|
||||
write!(f, "{:?}", &self.raw)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -106,16 +114,3 @@ where
|
|||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
enum State<Geometry>
|
||||
where
|
||||
Geometry: Cached,
|
||||
{
|
||||
Empty {
|
||||
previous: Option<Geometry::Cache>,
|
||||
},
|
||||
Filled {
|
||||
bounds: Size,
|
||||
geometry: Geometry::Cache,
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,7 @@
|
|||
#[cfg(feature = "image")]
|
||||
pub use ::image as image_rs;
|
||||
|
||||
use crate::core::image;
|
||||
use crate::core::svg;
|
||||
use crate::core::{Color, Rectangle};
|
||||
use crate::core::{image, svg, Color, Radians, Rectangle};
|
||||
|
||||
/// A raster or vector image.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
|
|
@ -19,6 +17,12 @@ pub enum Image {
|
|||
|
||||
/// The bounds of the image.
|
||||
bounds: Rectangle,
|
||||
|
||||
/// The rotation of the image.
|
||||
rotation: Radians,
|
||||
|
||||
/// The opacity of the image.
|
||||
opacity: f32,
|
||||
},
|
||||
/// A vector image.
|
||||
Vector {
|
||||
|
|
@ -30,6 +34,12 @@ pub enum Image {
|
|||
|
||||
/// The bounds of the image.
|
||||
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`].
|
||||
pub fn bounds(&self) -> Rectangle {
|
||||
match self {
|
||||
Image::Raster { bounds, .. } | Image::Vector { bounds, .. } => {
|
||||
*bounds
|
||||
Image::Raster {
|
||||
bounds, rotation, ..
|
||||
}
|
||||
| Image::Vector {
|
||||
bounds, rotation, ..
|
||||
} => bounds.rotate(*rotation),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -50,7 +63,8 @@ impl Image {
|
|||
/// [`Handle`]: image::Handle
|
||||
pub fn load(
|
||||
handle: &image::Handle,
|
||||
) -> ::image::ImageResult<::image::DynamicImage> {
|
||||
) -> ::image::ImageResult<::image::ImageBuffer<::image::Rgba<u8>, image::Bytes>>
|
||||
{
|
||||
use bitflags::bitflags;
|
||||
|
||||
bitflags! {
|
||||
|
|
@ -100,8 +114,8 @@ pub fn load(
|
|||
}
|
||||
}
|
||||
|
||||
match handle.data() {
|
||||
image::Data::Path(path) => {
|
||||
let (width, height, pixels) = match handle {
|
||||
image::Handle::Path(_, path) => {
|
||||
let image = ::image::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())
|
||||
.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 operation =
|
||||
Operation::from_exif(&mut std::io::Cursor::new(bytes))
|
||||
.ok()
|
||||
.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,
|
||||
height,
|
||||
pixels,
|
||||
} => {
|
||||
if let Some(image) =
|
||||
::image::ImageBuffer::from_vec(*width, *height, pixels.to_vec())
|
||||
{
|
||||
Ok(::image::DynamicImage::ImageRgba8(image))
|
||||
} else {
|
||||
Err(::image::error::ImageError::Limits(
|
||||
::image::error::LimitError::from_kind(
|
||||
::image::error::LimitErrorKind::DimensionError,
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
..
|
||||
} => (*width, *height, pixels.clone()),
|
||||
};
|
||||
|
||||
if let Some(image) = ::image::ImageBuffer::from_raw(width, height, pixels) {
|
||||
Ok(image)
|
||||
} else {
|
||||
Err(::image::error::ImageError::Limits(
|
||||
::image::error::LimitError::from_kind(
|
||||
::image::error::LimitErrorKind::DimensionError,
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@
|
|||
)]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
mod antialiasing;
|
||||
mod cached;
|
||||
mod settings;
|
||||
mod viewport;
|
||||
|
||||
pub mod cache;
|
||||
pub mod color;
|
||||
pub mod compositor;
|
||||
pub mod damage;
|
||||
|
|
@ -27,7 +27,7 @@ pub mod text;
|
|||
pub mod geometry;
|
||||
|
||||
pub use antialiasing::Antialiasing;
|
||||
pub use cached::Cached;
|
||||
pub use cache::Cache;
|
||||
pub use compositor::Compositor;
|
||||
pub use error::Error;
|
||||
pub use gradient::Gradient;
|
||||
|
|
|
|||
|
|
@ -456,10 +456,14 @@ impl editor::Editor for Editor {
|
|||
}
|
||||
}
|
||||
Action::Scroll { lines } => {
|
||||
editor.action(
|
||||
font_system.raw(),
|
||||
cosmic_text::Action::Scroll { lines },
|
||||
);
|
||||
let (_, height) = editor.buffer().size();
|
||||
|
||||
if height < i32::MAX as f32 {
|
||||
editor.action(
|
||||
font_system.raw(),
|
||||
cosmic_text::Action::Scroll { lines },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use crate::core::image;
|
|||
use crate::core::renderer;
|
||||
use crate::core::svg;
|
||||
use crate::core::{
|
||||
self, Background, Color, Point, Rectangle, Size, Transformation,
|
||||
self, Background, Color, Point, Radians, Rectangle, Size, Transformation,
|
||||
};
|
||||
use crate::graphics;
|
||||
use crate::graphics::compositor;
|
||||
|
|
@ -154,11 +154,19 @@ where
|
|||
handle: Self::Handle,
|
||||
filter_method: image::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
delegate!(
|
||||
self,
|
||||
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,
|
||||
color: Option<Color>,
|
||||
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 {
|
||||
use super::Renderer;
|
||||
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::Cached;
|
||||
|
||||
impl<A, B> geometry::Renderer for Renderer<A, B>
|
||||
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) {
|
||||
(
|
||||
Self::Primary(geometry),
|
||||
Some(Geometry::Primary(previous)),
|
||||
) => Geometry::Primary(geometry.cache(Some(previous))),
|
||||
) => Geometry::Primary(geometry.cache(group, Some(previous))),
|
||||
(Self::Primary(geometry), None) => {
|
||||
Geometry::Primary(geometry.cache(None))
|
||||
Geometry::Primary(geometry.cache(group, None))
|
||||
}
|
||||
(
|
||||
Self::Secondary(geometry),
|
||||
Some(Geometry::Secondary(previous)),
|
||||
) => Geometry::Secondary(geometry.cache(Some(previous))),
|
||||
) => Geometry::Secondary(geometry.cache(group, Some(previous))),
|
||||
(Self::Secondary(geometry), None) => {
|
||||
Geometry::Secondary(geometry.cache(None))
|
||||
Geometry::Secondary(geometry.cache(group, None))
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ debug = []
|
|||
multi-window = []
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
iced_core.workspace = true
|
||||
iced_futures.workspace = true
|
||||
iced_futures.features = ["thread-pool"]
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ where
|
|||
caches,
|
||||
queued_events: Vec::new(),
|
||||
queued_messages: Vec::new(),
|
||||
mouse_interaction: mouse::Interaction::Idle,
|
||||
mouse_interaction: mouse::Interaction::None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ where
|
|||
cache,
|
||||
queued_events: Vec::new(),
|
||||
queued_messages: Vec::new(),
|
||||
mouse_interaction: mouse::Interaction::Idle,
|
||||
mouse_interaction: mouse::Interaction::None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
//! Take screenshots of a window.
|
||||
use crate::core::{Rectangle, Size};
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Data of a screenshot, captured with `window::screenshot()`.
|
||||
///
|
||||
|
|
@ -10,7 +10,7 @@ use std::sync::Arc;
|
|||
#[derive(Clone)]
|
||||
pub struct Screenshot {
|
||||
/// The bytes of the [`Screenshot`].
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
pub bytes: Bytes,
|
||||
/// The size of the [`Screenshot`].
|
||||
pub size: Size<u32>,
|
||||
}
|
||||
|
|
@ -28,9 +28,9 @@ impl Debug for Screenshot {
|
|||
|
||||
impl 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 {
|
||||
bytes: Arc::new(bytes),
|
||||
bytes: bytes.into(),
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
|
@ -68,7 +68,7 @@ impl Screenshot {
|
|||
);
|
||||
|
||||
Ok(Self {
|
||||
bytes: Arc::new(chopped),
|
||||
bytes: Bytes::from(chopped),
|
||||
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)]
|
||||
/// Errors that can occur when cropping a [`Screenshot`].
|
||||
pub enum CropError {
|
||||
|
|
|
|||
|
|
@ -212,26 +212,11 @@ where
|
|||
..crate::graphics::Settings::default()
|
||||
};
|
||||
|
||||
let run = crate::shell::application::run::<
|
||||
Ok(crate::shell::application::run::<
|
||||
Instance<Self>,
|
||||
Self::Executor,
|
||||
<Self::Renderer as compositor::Default>::Compositor,
|
||||
>(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)?)
|
||||
>(settings.into(), renderer_settings)?)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@
|
|||
//! We start by modelling the __state__ of our application:
|
||||
//!
|
||||
//! ```
|
||||
//! #[derive(Default)]
|
||||
//! struct Counter {
|
||||
//! // The counter value
|
||||
//! value: i32,
|
||||
|
|
@ -199,8 +200,8 @@ pub use crate::core::gradient;
|
|||
pub use crate::core::theme;
|
||||
pub use crate::core::{
|
||||
Alignment, Background, Border, Color, ContentFit, Degrees, Gradient,
|
||||
Length, Padding, Pixels, Point, Radians, Rectangle, Shadow, Size, Theme,
|
||||
Transformation, Vector,
|
||||
Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size,
|
||||
Theme, Transformation, Vector,
|
||||
};
|
||||
|
||||
pub mod clipboard {
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ pub enum Error {
|
|||
InvalidError(#[from] icon::Error),
|
||||
|
||||
/// 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),
|
||||
|
||||
/// The `image` crate reported an error.
|
||||
|
|
|
|||
|
|
@ -550,6 +550,8 @@ impl Engine {
|
|||
handle,
|
||||
filter_method,
|
||||
bounds,
|
||||
rotation,
|
||||
opacity,
|
||||
} => {
|
||||
let physical_bounds = *bounds * _transformation;
|
||||
|
||||
|
|
@ -560,12 +562,22 @@ impl Engine {
|
|||
let clip_mask = (!physical_bounds.is_within(&_clip_bounds))
|
||||
.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(
|
||||
handle,
|
||||
*filter_method,
|
||||
*bounds,
|
||||
*opacity,
|
||||
_pixels,
|
||||
into_transform(_transformation),
|
||||
transform,
|
||||
clip_mask,
|
||||
);
|
||||
}
|
||||
|
|
@ -574,6 +586,8 @@ impl Engine {
|
|||
handle,
|
||||
color,
|
||||
bounds,
|
||||
rotation,
|
||||
opacity,
|
||||
} => {
|
||||
let physical_bounds = *bounds * _transformation;
|
||||
|
||||
|
|
@ -584,11 +598,22 @@ impl Engine {
|
|||
let clip_mask = (!physical_bounds.is_within(&_clip_bounds))
|
||||
.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(
|
||||
handle,
|
||||
*color,
|
||||
physical_bounds,
|
||||
*opacity,
|
||||
_pixels,
|
||||
transform,
|
||||
clip_mask,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
use crate::core::text::LineHeight;
|
||||
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::stroke::{self, Stroke};
|
||||
use crate::graphics::geometry::{self, Path, Style};
|
||||
use crate::graphics::{Cached, Gradient, Text};
|
||||
use crate::graphics::{Gradient, Text};
|
||||
use crate::Primitive;
|
||||
|
||||
use std::rc::Rc;
|
||||
|
|
@ -32,7 +33,7 @@ impl Cached for Geometry {
|
|||
Self::Cache(cache.clone())
|
||||
}
|
||||
|
||||
fn cache(self, _previous: Option<Cache>) -> Cache {
|
||||
fn cache(self, _group: cache::Group, _previous: Option<Cache>) -> Cache {
|
||||
match self {
|
||||
Self::Live {
|
||||
primitives,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::core::image;
|
||||
use crate::core::renderer::Quad;
|
||||
use crate::core::svg;
|
||||
use crate::core::{Background, Color, Point, Rectangle, Transformation};
|
||||
use crate::core::{
|
||||
image, renderer::Quad, svg, Background, Color, Point, Radians, Rectangle,
|
||||
Transformation,
|
||||
};
|
||||
use crate::graphics::damage;
|
||||
use crate::graphics::layer;
|
||||
use crate::graphics::text::{Editor, Paragraph, Text};
|
||||
|
|
@ -121,11 +121,15 @@ impl Layer {
|
|||
filter_method: image::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
transformation: Transformation,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
let image = Image::Raster {
|
||||
handle,
|
||||
filter_method,
|
||||
bounds: bounds * transformation,
|
||||
rotation,
|
||||
opacity,
|
||||
};
|
||||
|
||||
self.images.push(image);
|
||||
|
|
@ -137,11 +141,15 @@ impl Layer {
|
|||
color: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
transformation: Transformation,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
let svg = Image::Vector {
|
||||
handle,
|
||||
color,
|
||||
bounds: bounds * transformation,
|
||||
rotation,
|
||||
opacity,
|
||||
};
|
||||
|
||||
self.images.push(svg);
|
||||
|
|
|
|||
|
|
@ -377,9 +377,18 @@ impl core::image::Renderer for Renderer {
|
|||
handle: Self::Handle,
|
||||
filter_method: core::image::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
rotation: core::Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
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,
|
||||
color: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
rotation: core::Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
let (layer, transformation) = self.layers.current_mut();
|
||||
layer.draw_svg(handle, color, bounds, transformation);
|
||||
layer.draw_svg(
|
||||
handle,
|
||||
color,
|
||||
bounds,
|
||||
transformation,
|
||||
rotation,
|
||||
opacity,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ impl Pipeline {
|
|||
handle: &raster::Handle,
|
||||
filter_method: raster::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
opacity: f32,
|
||||
pixels: &mut tiny_skia::PixmapMut<'_>,
|
||||
transform: tiny_skia::Transform,
|
||||
clip_mask: Option<&tiny_skia::Mask>,
|
||||
|
|
@ -56,6 +57,7 @@ impl Pipeline {
|
|||
image,
|
||||
&tiny_skia::PixmapPaint {
|
||||
quality,
|
||||
opacity,
|
||||
..Default::default()
|
||||
},
|
||||
transform,
|
||||
|
|
@ -71,8 +73,8 @@ impl Pipeline {
|
|||
|
||||
#[derive(Debug, Default)]
|
||||
struct Cache {
|
||||
entries: FxHashMap<u64, Option<Entry>>,
|
||||
hits: FxHashSet<u64>,
|
||||
entries: FxHashMap<raster::Id, Option<Entry>>,
|
||||
hits: FxHashSet<raster::Id>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
|
|
@ -83,7 +85,7 @@ impl Cache {
|
|||
let id = handle.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 =
|
||||
vec![0u32; image.width() as usize * image.height() as usize];
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ use crate::graphics::text;
|
|||
|
||||
use resvg::usvg::{self, TreeTextToPath};
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use tiny_skia::Transform;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::hash_map;
|
||||
|
|
@ -33,7 +34,9 @@ impl Pipeline {
|
|||
handle: &Handle,
|
||||
color: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
opacity: f32,
|
||||
pixels: &mut tiny_skia::PixmapMut<'_>,
|
||||
transform: Transform,
|
||||
clip_mask: Option<&tiny_skia::Mask>,
|
||||
) {
|
||||
if let Some(image) = self.cache.borrow_mut().draw(
|
||||
|
|
@ -45,8 +48,11 @@ impl Pipeline {
|
|||
bounds.x as i32,
|
||||
bounds.y as i32,
|
||||
image,
|
||||
&tiny_skia::PixmapPaint::default(),
|
||||
tiny_skia::Transform::identity(),
|
||||
&tiny_skia::PixmapPaint {
|
||||
opacity,
|
||||
..tiny_skia::PixmapPaint::default()
|
||||
},
|
||||
transform,
|
||||
clip_mask,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
use std::borrow::Cow;
|
||||
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub fn convert(
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
|
|
@ -15,28 +17,58 @@ pub fn convert(
|
|||
..wgpu::SamplerDescriptor::default()
|
||||
});
|
||||
|
||||
//sampler in 0
|
||||
let sampler_layout =
|
||||
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
|
||||
#[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 {
|
||||
label: Some("iced_wgpu.offscreen.blit.sampler_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(
|
||||
wgpu::SamplerBindingType::NonFiltering,
|
||||
),
|
||||
count: None,
|
||||
}],
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(
|
||||
wgpu::SamplerBindingType::NonFiltering,
|
||||
),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let sampler_bind_group =
|
||||
let constant_bind_group =
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("iced_wgpu.offscreen.sampler.bind_group"),
|
||||
layout: &sampler_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
}],
|
||||
layout: &constant_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: ratio.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let texture_layout =
|
||||
|
|
@ -59,7 +91,7 @@ pub fn convert(
|
|||
let pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
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: &[],
|
||||
});
|
||||
|
||||
|
|
@ -152,7 +184,7 @@ pub fn convert(
|
|||
});
|
||||
|
||||
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.draw(0..6, 0..1);
|
||||
|
||||
|
|
|
|||
|
|
@ -59,8 +59,11 @@ impl Engine {
|
|||
}
|
||||
|
||||
#[cfg(any(feature = "image", feature = "svg"))]
|
||||
pub fn image_cache(&self) -> &crate::image::cache::Shared {
|
||||
self.image_pipeline.cache()
|
||||
pub fn create_image_cache(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
) -> crate::image::Cache {
|
||||
self.image_pipeline.create_cache(device)
|
||||
}
|
||||
|
||||
pub fn submit(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ use crate::core::text::LineHeight;
|
|||
use crate::core::{
|
||||
Pixels, Point, Radians, Rectangle, Size, Transformation, Vector,
|
||||
};
|
||||
use crate::graphics::cache::{self, Cached};
|
||||
use crate::graphics::color;
|
||||
use crate::graphics::geometry::fill::{self, Fill};
|
||||
use crate::graphics::geometry::{
|
||||
|
|
@ -10,7 +11,7 @@ use crate::graphics::geometry::{
|
|||
};
|
||||
use crate::graphics::gradient::{self, Gradient};
|
||||
use crate::graphics::mesh::{self, Mesh};
|
||||
use crate::graphics::{self, Cached, Text};
|
||||
use crate::graphics::{self, Text};
|
||||
use crate::text;
|
||||
use crate::triangle;
|
||||
|
||||
|
|
@ -38,7 +39,11 @@ impl Cached for Geometry {
|
|||
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 {
|
||||
Self::Live { meshes, text } => {
|
||||
if let Some(mut previous) = previous {
|
||||
|
|
@ -51,14 +56,14 @@ impl Cached for Geometry {
|
|||
if let Some(cache) = &mut previous.text {
|
||||
cache.update(text);
|
||||
} else {
|
||||
previous.text = text::Cache::new(text);
|
||||
previous.text = text::Cache::new(group, text);
|
||||
}
|
||||
|
||||
previous
|
||||
} else {
|
||||
Cache {
|
||||
meshes: triangle::Cache::new(meshes),
|
||||
text: text::Cache::new(text),
|
||||
text: text::Cache::new(group, text),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,15 +15,23 @@ pub const SIZE: u32 = 2048;
|
|||
use crate::core::Size;
|
||||
use crate::graphics::color;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Atlas {
|
||||
texture: wgpu::Texture,
|
||||
texture_view: wgpu::TextureView,
|
||||
texture_bind_group: wgpu::BindGroup,
|
||||
texture_layout: Arc<wgpu::BindGroupLayout>,
|
||||
layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
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 {
|
||||
// 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`
|
||||
|
|
@ -60,15 +68,27 @@ impl Atlas {
|
|||
..Default::default()
|
||||
});
|
||||
|
||||
let texture_bind_group =
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("iced_wgpu::image texture atlas bind group"),
|
||||
layout: &texture_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&texture_view),
|
||||
}],
|
||||
});
|
||||
|
||||
Atlas {
|
||||
texture,
|
||||
texture_view,
|
||||
texture_bind_group,
|
||||
texture_layout,
|
||||
layers,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(&self) -> &wgpu::TextureView {
|
||||
&self.texture_view
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup {
|
||||
&self.texture_bind_group
|
||||
}
|
||||
|
||||
pub fn layer_count(&self) -> usize {
|
||||
|
|
@ -94,7 +114,7 @@ impl Atlas {
|
|||
entry
|
||||
};
|
||||
|
||||
log::info!("Allocated atlas entry: {entry:?}");
|
||||
log::debug!("Allocated atlas entry: {entry:?}");
|
||||
|
||||
// It is a webgpu requirement that:
|
||||
// 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)
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, entry: &Entry) {
|
||||
log::info!("Removing atlas entry: {entry:?}");
|
||||
log::debug!("Removing atlas entry: {entry:?}");
|
||||
|
||||
match entry {
|
||||
Entry::Contiguous(allocation) => {
|
||||
|
|
@ -266,7 +293,7 @@ impl Atlas {
|
|||
}
|
||||
|
||||
fn deallocate(&mut self, allocation: &Allocation) {
|
||||
log::info!("Deallocating atlas: {allocation:?}");
|
||||
log::debug!("Deallocating atlas: {allocation:?}");
|
||||
|
||||
match allocation {
|
||||
Allocation::Full { layer } => {
|
||||
|
|
@ -414,5 +441,17 @@ impl Atlas {
|
|||
dimension: Some(wgpu::TextureViewDimension::D2Array),
|
||||
..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,
|
||||
),
|
||||
}],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,10 @@ impl Allocator {
|
|||
pub fn is_empty(&self) -> bool {
|
||||
self.allocations == 0
|
||||
}
|
||||
|
||||
pub fn allocations(&self) -> usize {
|
||||
self.allocations
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Region {
|
||||
|
|
|
|||
|
|
@ -11,4 +11,12 @@ impl Layer {
|
|||
pub fn is_empty(&self) -> bool {
|
||||
matches!(self, Layer::Empty)
|
||||
}
|
||||
|
||||
pub fn allocations(&self) -> usize {
|
||||
match self {
|
||||
Layer::Empty => 0,
|
||||
Layer::Busy(allocator) => allocator.allocations(),
|
||||
Layer::Full => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
use crate::core::{self, Size};
|
||||
use crate::image::atlas::{self, Atlas};
|
||||
|
||||
use std::cell::{RefCell, RefMut};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Cache {
|
||||
|
|
@ -14,9 +13,13 @@ pub struct 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 {
|
||||
atlas: Atlas::new(device, backend),
|
||||
atlas: Atlas::new(device, backend, layout),
|
||||
#[cfg(feature = "image")]
|
||||
raster: crate::image::raster::Cache::default(),
|
||||
#[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 {
|
||||
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) {
|
||||
#[cfg(feature = "image")]
|
||||
self.raster.trim(&mut self.atlas);
|
||||
|
|
@ -92,16 +84,3 @@ impl Cache {
|
|||
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()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ use crate::core::{Rectangle, Size, Transformation};
|
|||
use crate::Buffer;
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
use std::mem;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use crate::graphics::Image;
|
||||
|
||||
|
|
@ -22,13 +24,11 @@ pub type Batch = Vec<Image>;
|
|||
#[derive(Debug)]
|
||||
pub struct Pipeline {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
backend: wgpu::Backend,
|
||||
nearest_sampler: wgpu::Sampler,
|
||||
linear_sampler: wgpu::Sampler,
|
||||
texture: wgpu::BindGroup,
|
||||
texture_version: usize,
|
||||
texture_layout: wgpu::BindGroupLayout,
|
||||
texture_layout: Arc<wgpu::BindGroupLayout>,
|
||||
constant_layout: wgpu::BindGroupLayout,
|
||||
cache: cache::Shared,
|
||||
layers: Vec<Layer>,
|
||||
prepare_layer: usize,
|
||||
}
|
||||
|
|
@ -135,14 +135,20 @@ impl Pipeline {
|
|||
attributes: &wgpu::vertex_attr_array!(
|
||||
// Position
|
||||
0 => Float32x2,
|
||||
// Scale
|
||||
// Center
|
||||
1 => Float32x2,
|
||||
// Atlas position
|
||||
// Scale
|
||||
2 => Float32x2,
|
||||
// Rotation
|
||||
3 => Float32,
|
||||
// Opacity
|
||||
4 => Float32,
|
||||
// Atlas position
|
||||
5 => Float32x2,
|
||||
// Atlas scale
|
||||
3 => Float32x2,
|
||||
6 => Float32x2,
|
||||
// Layer
|
||||
4 => Sint32,
|
||||
7 => Sint32,
|
||||
),
|
||||
}],
|
||||
},
|
||||
|
|
@ -180,25 +186,20 @@ impl Pipeline {
|
|||
multiview: None,
|
||||
});
|
||||
|
||||
let cache = Cache::new(device, backend);
|
||||
let texture = cache.create_bind_group(device, &texture_layout);
|
||||
|
||||
Pipeline {
|
||||
pipeline,
|
||||
backend,
|
||||
nearest_sampler,
|
||||
linear_sampler,
|
||||
texture,
|
||||
texture_version: cache.layer_count(),
|
||||
texture_layout,
|
||||
texture_layout: Arc::new(texture_layout),
|
||||
constant_layout,
|
||||
cache: cache::Shared::new(cache),
|
||||
layers: Vec::new(),
|
||||
prepare_layer: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cache(&self) -> &cache::Shared {
|
||||
&self.cache
|
||||
pub fn create_cache(&self, device: &wgpu::Device) -> Cache {
|
||||
Cache::new(device, self.backend, self.texture_layout.clone())
|
||||
}
|
||||
|
||||
pub fn prepare(
|
||||
|
|
@ -206,6 +207,7 @@ impl Pipeline {
|
|||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
cache: &mut Cache,
|
||||
images: &Batch,
|
||||
transformation: Transformation,
|
||||
scale: f32,
|
||||
|
|
@ -215,8 +217,6 @@ impl Pipeline {
|
|||
let nearest_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 {
|
||||
match &image {
|
||||
#[cfg(feature = "image")]
|
||||
|
|
@ -224,6 +224,8 @@ impl Pipeline {
|
|||
handle,
|
||||
filter_method,
|
||||
bounds,
|
||||
rotation,
|
||||
opacity,
|
||||
} => {
|
||||
if let Some(atlas_entry) =
|
||||
cache.upload_raster(device, encoder, handle)
|
||||
|
|
@ -231,6 +233,8 @@ impl Pipeline {
|
|||
add_instances(
|
||||
[bounds.x, bounds.y],
|
||||
[bounds.width, bounds.height],
|
||||
f32::from(*rotation),
|
||||
*opacity,
|
||||
atlas_entry,
|
||||
match filter_method {
|
||||
crate::core::image::FilterMethod::Nearest => {
|
||||
|
|
@ -251,6 +255,8 @@ impl Pipeline {
|
|||
handle,
|
||||
color,
|
||||
bounds,
|
||||
rotation,
|
||||
opacity,
|
||||
} => {
|
||||
let size = [bounds.width, bounds.height];
|
||||
|
||||
|
|
@ -260,6 +266,8 @@ impl Pipeline {
|
|||
add_instances(
|
||||
[bounds.x, bounds.y],
|
||||
size,
|
||||
f32::from(*rotation),
|
||||
*opacity,
|
||||
atlas_entry,
|
||||
nearest_instances,
|
||||
);
|
||||
|
|
@ -274,16 +282,6 @@ impl Pipeline {
|
|||
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 {
|
||||
self.layers.push(Layer::new(
|
||||
device,
|
||||
|
|
@ -309,6 +307,7 @@ impl Pipeline {
|
|||
|
||||
pub fn render<'a>(
|
||||
&'a self,
|
||||
cache: &'a Cache,
|
||||
layer: usize,
|
||||
bounds: Rectangle<u32>,
|
||||
render_pass: &mut wgpu::RenderPass<'a>,
|
||||
|
|
@ -323,14 +322,13 @@ impl Pipeline {
|
|||
bounds.height,
|
||||
);
|
||||
|
||||
render_pass.set_bind_group(1, &self.texture, &[]);
|
||||
render_pass.set_bind_group(1, cache.bind_group(), &[]);
|
||||
|
||||
layer.render(render_pass);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_frame(&mut self) {
|
||||
self.cache.lock().trim();
|
||||
self.prepare_layer = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -487,7 +485,10 @@ impl Data {
|
|||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
struct Instance {
|
||||
_position: [f32; 2],
|
||||
_center: [f32; 2],
|
||||
_size: [f32; 2],
|
||||
_rotation: f32,
|
||||
_opacity: f32,
|
||||
_position_in_atlas: [f32; 2],
|
||||
_size_in_atlas: [f32; 2],
|
||||
_layer: u32,
|
||||
|
|
@ -506,12 +507,27 @@ struct Uniforms {
|
|||
fn add_instances(
|
||||
image_position: [f32; 2],
|
||||
image_size: [f32; 2],
|
||||
rotation: f32,
|
||||
opacity: f32,
|
||||
entry: &atlas::Entry,
|
||||
instances: &mut Vec<Instance>,
|
||||
) {
|
||||
let center = [
|
||||
image_position[0] + image_size[0] / 2.0,
|
||||
image_position[1] + image_size[1] / 2.0,
|
||||
];
|
||||
|
||||
match entry {
|
||||
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 } => {
|
||||
let scaling_x = image_size[0] / size.width as f32;
|
||||
|
|
@ -537,7 +553,10 @@ fn add_instances(
|
|||
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]
|
||||
fn add_instance(
|
||||
position: [f32; 2],
|
||||
center: [f32; 2],
|
||||
size: [f32; 2],
|
||||
rotation: f32,
|
||||
opacity: f32,
|
||||
allocation: &atlas::Allocation,
|
||||
instances: &mut Vec<Instance>,
|
||||
) {
|
||||
|
|
@ -556,7 +578,10 @@ fn add_instance(
|
|||
|
||||
let instance = Instance {
|
||||
_position: position,
|
||||
_center: center,
|
||||
_size: size,
|
||||
_rotation: rotation,
|
||||
_opacity: opacity,
|
||||
_position_in_atlas: [
|
||||
(x as f32 + 0.5) / atlas::SIZE as f32,
|
||||
(y as f32 + 0.5) / atlas::SIZE as f32,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
|||
#[derive(Debug)]
|
||||
pub enum Memory {
|
||||
/// 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
|
||||
Device(atlas::Entry),
|
||||
/// Image not found
|
||||
|
|
@ -38,8 +38,9 @@ impl Memory {
|
|||
/// Caches image raster data
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Cache {
|
||||
map: FxHashMap<u64, Memory>,
|
||||
hits: FxHashSet<u64>,
|
||||
map: FxHashMap<image::Id, Memory>,
|
||||
hits: FxHashSet<image::Id>,
|
||||
should_trim: bool,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
|
|
@ -50,11 +51,13 @@ impl Cache {
|
|||
}
|
||||
|
||||
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(_) => Memory::Invalid,
|
||||
};
|
||||
|
||||
self.should_trim = true;
|
||||
|
||||
self.insert(handle, memory);
|
||||
self.get(handle).unwrap()
|
||||
}
|
||||
|
|
@ -86,6 +89,11 @@ impl Cache {
|
|||
|
||||
/// Trim cache misses from cache
|
||||
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;
|
||||
|
||||
self.map.retain(|k, memory| {
|
||||
|
|
@ -101,6 +109,7 @@ impl Cache {
|
|||
});
|
||||
|
||||
self.hits.clear();
|
||||
self.should_trim = false;
|
||||
}
|
||||
|
||||
fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> {
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ pub struct Cache {
|
|||
rasterized: FxHashMap<(u64, u32, u32, ColorFilter), atlas::Entry>,
|
||||
svg_hits: FxHashSet<u64>,
|
||||
rasterized_hits: FxHashSet<(u64, u32, u32, ColorFilter)>,
|
||||
should_trim: bool,
|
||||
}
|
||||
|
||||
type ColorFilter = Option<[u8; 4]>;
|
||||
|
|
@ -76,6 +77,8 @@ impl Cache {
|
|||
}
|
||||
}
|
||||
|
||||
self.should_trim = true;
|
||||
|
||||
let _ = self.svgs.insert(handle.id(), svg);
|
||||
self.svgs.get(&handle.id()).unwrap()
|
||||
}
|
||||
|
|
@ -176,6 +179,10 @@ impl Cache {
|
|||
|
||||
/// Load svg and upload raster data
|
||||
pub fn trim(&mut self, atlas: &mut Atlas) {
|
||||
if !self.should_trim {
|
||||
return;
|
||||
}
|
||||
|
||||
let svg_hits = &self.svg_hits;
|
||||
let rasterized_hits = &self.rasterized_hits;
|
||||
|
||||
|
|
@ -191,6 +198,7 @@ impl Cache {
|
|||
});
|
||||
self.svg_hits.clear();
|
||||
self.rasterized_hits.clear();
|
||||
self.should_trim = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use crate::core::renderer;
|
||||
use crate::core::{Background, Color, Point, Rectangle, Transformation};
|
||||
use crate::core::{
|
||||
renderer, Background, Color, Point, Radians, Rectangle, Transformation,
|
||||
};
|
||||
use crate::graphics;
|
||||
use crate::graphics::color;
|
||||
use crate::graphics::layer;
|
||||
|
|
@ -117,11 +118,15 @@ impl Layer {
|
|||
filter_method: crate::core::image::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
transformation: Transformation,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
let image = Image::Raster {
|
||||
handle,
|
||||
filter_method,
|
||||
bounds: bounds * transformation,
|
||||
rotation,
|
||||
opacity,
|
||||
};
|
||||
|
||||
self.images.push(image);
|
||||
|
|
@ -133,11 +138,15 @@ impl Layer {
|
|||
color: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
transformation: Transformation,
|
||||
rotation: Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
let svg = Image::Vector {
|
||||
handle,
|
||||
color,
|
||||
bounds: bounds * transformation,
|
||||
rotation,
|
||||
opacity,
|
||||
};
|
||||
|
||||
self.images.push(svg);
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ pub use geometry::Geometry;
|
|||
|
||||
use crate::core::{
|
||||
Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation,
|
||||
Vector,
|
||||
};
|
||||
use crate::graphics::text::{Editor, Paragraph};
|
||||
use crate::graphics::Viewport;
|
||||
|
|
@ -81,11 +82,12 @@ pub struct Renderer {
|
|||
|
||||
// TODO: Centralize all the image feature handling
|
||||
#[cfg(any(feature = "svg", feature = "image"))]
|
||||
image_cache: image::cache::Shared,
|
||||
image_cache: std::cell::RefCell<image::Cache>,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn new(
|
||||
_device: &wgpu::Device,
|
||||
_engine: &Engine,
|
||||
default_font: Font,
|
||||
default_text_size: Pixels,
|
||||
|
|
@ -99,7 +101,9 @@ impl Renderer {
|
|||
text_storage: text::Storage::new(),
|
||||
|
||||
#[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.text_storage.trim();
|
||||
|
||||
#[cfg(any(feature = "svg", feature = "image"))]
|
||||
self.image_cache.borrow_mut().trim();
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
|
|
@ -190,6 +197,7 @@ impl Renderer {
|
|||
device,
|
||||
encoder,
|
||||
&mut engine.staging_belt,
|
||||
&mut self.image_cache.borrow_mut(),
|
||||
&layer.images,
|
||||
viewport.projection(),
|
||||
scale_factor,
|
||||
|
|
@ -245,6 +253,8 @@ impl Renderer {
|
|||
|
||||
#[cfg(any(feature = "svg", feature = "image"))]
|
||||
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 physical_bounds = Rectangle::<f32>::from(Rectangle::with_size(
|
||||
|
|
@ -358,6 +368,7 @@ impl Renderer {
|
|||
#[cfg(any(feature = "svg", feature = "image"))]
|
||||
if !layer.images.is_empty() {
|
||||
engine.image_pipeline.render(
|
||||
&image_cache,
|
||||
image_layer,
|
||||
scissor_rect,
|
||||
&mut render_pass,
|
||||
|
|
@ -378,7 +389,6 @@ impl Renderer {
|
|||
use crate::core::alignment;
|
||||
use crate::core::text::Renderer as _;
|
||||
use crate::core::Renderer as _;
|
||||
use crate::core::Vector;
|
||||
|
||||
self.with_layer(
|
||||
Rectangle::with_size(viewport.logical_size()),
|
||||
|
|
@ -509,7 +519,7 @@ impl core::image::Renderer for Renderer {
|
|||
type Handle = core::image::Handle;
|
||||
|
||||
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(
|
||||
|
|
@ -517,16 +527,25 @@ impl core::image::Renderer for Renderer {
|
|||
handle: Self::Handle,
|
||||
filter_method: core::image::FilterMethod,
|
||||
bounds: Rectangle,
|
||||
rotation: core::Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
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")]
|
||||
impl core::svg::Renderer for Renderer {
|
||||
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(
|
||||
|
|
@ -534,9 +553,18 @@ impl core::svg::Renderer for Renderer {
|
|||
handle: core::svg::Handle,
|
||||
color_filter: Option<Color>,
|
||||
bounds: Rectangle,
|
||||
rotation: core::Radians,
|
||||
opacity: f32,
|
||||
) {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ pub struct Storage {
|
|||
impl Storage {
|
||||
/// Returns `true` if `Storage` contains a type `T`.
|
||||
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`].
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,40 +9,55 @@ struct Globals {
|
|||
struct VertexInput {
|
||||
@builtin(vertex_index) vertex_index: u32,
|
||||
@location(0) pos: vec2<f32>,
|
||||
@location(1) scale: vec2<f32>,
|
||||
@location(2) atlas_pos: vec2<f32>,
|
||||
@location(3) atlas_scale: vec2<f32>,
|
||||
@location(4) layer: i32,
|
||||
@location(1) center: vec2<f32>,
|
||||
@location(2) scale: vec2<f32>,
|
||||
@location(3) rotation: f32,
|
||||
@location(4) opacity: f32,
|
||||
@location(5) atlas_pos: vec2<f32>,
|
||||
@location(6) atlas_scale: vec2<f32>,
|
||||
@location(7) layer: i32,
|
||||
}
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) layer: f32, // this should be an i32, but naga currently reads that as requiring interpolation.
|
||||
@location(2) opacity: f32,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(input: VertexInput) -> 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.layer = f32(input.layer);
|
||||
out.opacity = input.opacity;
|
||||
|
||||
var transform: mat4x4<f32> = mat4x4<f32>(
|
||||
vec4<f32>(input.scale.x, 0.0, 0.0, 0.0),
|
||||
vec4<f32>(0.0, input.scale.y, 0.0, 0.0),
|
||||
// Calculate the vertex position and move the center to the origin
|
||||
v_pos = input.pos + v_pos * input.scale - input.center;
|
||||
|
||||
// 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>(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;
|
||||
}
|
||||
|
||||
@fragment
|
||||
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);
|
||||
}
|
||||
|
|
|
|||
178
wgpu/src/text.rs
178
wgpu/src/text.rs
|
|
@ -1,12 +1,13 @@
|
|||
use crate::core::alignment;
|
||||
use crate::core::{Rectangle, Size, Transformation};
|
||||
use crate::graphics::cache;
|
||||
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 rustc_hash::{FxHashMap, FxHashSet};
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::collections::hash_map;
|
||||
use std::rc::Rc;
|
||||
use std::rc::{self, Rc};
|
||||
use std::sync::atomic::{self, AtomicU64};
|
||||
use std::sync::Arc;
|
||||
|
||||
|
|
@ -35,6 +36,7 @@ pub enum Item {
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct Cache {
|
||||
id: Id,
|
||||
group: cache::Group,
|
||||
text: Rc<[Text]>,
|
||||
version: usize,
|
||||
}
|
||||
|
|
@ -43,7 +45,7 @@ pub struct Cache {
|
|||
pub struct Id(u64);
|
||||
|
||||
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);
|
||||
|
||||
if text.is_empty() {
|
||||
|
|
@ -52,12 +54,17 @@ impl Cache {
|
|||
|
||||
Some(Self {
|
||||
id: Id(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)),
|
||||
group,
|
||||
text: Rc::from(text),
|
||||
version: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update(&mut self, text: Vec<Text>) {
|
||||
if self.text.is_empty() && text.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.text = Rc::from(text);
|
||||
self.version += 1;
|
||||
}
|
||||
|
|
@ -65,16 +72,25 @@ impl Cache {
|
|||
|
||||
struct Upload {
|
||||
renderer: glyphon::TextRenderer,
|
||||
atlas: glyphon::TextAtlas,
|
||||
buffer_cache: BufferCache,
|
||||
transformation: Transformation,
|
||||
version: usize,
|
||||
group_version: usize,
|
||||
text: rc::Weak<[Text]>,
|
||||
_atlas: rc::Weak<()>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Storage {
|
||||
groups: FxHashMap<cache::Group, Group>,
|
||||
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 {
|
||||
|
|
@ -82,12 +98,15 @@ impl Storage {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
fn get(&self, cache: &Cache) -> Option<&Upload> {
|
||||
fn get(&self, cache: &Cache) -> Option<(&glyphon::TextAtlas, &Upload)> {
|
||||
if cache.text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.uploads.get(&cache.id)
|
||||
self.groups
|
||||
.get(&cache.group)
|
||||
.map(|group| &group.atlas)
|
||||
.zip(self.uploads.get(&cache.id))
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
|
|
@ -101,41 +120,63 @@ impl Storage {
|
|||
bounds: Rectangle,
|
||||
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) {
|
||||
hash_map::Entry::Occupied(entry) => {
|
||||
let upload = entry.into_mut();
|
||||
|
||||
if !cache.text.is_empty()
|
||||
&& (upload.version != cache.version
|
||||
|| upload.transformation != new_transformation)
|
||||
if upload.version != cache.version
|
||||
|| upload.group_version != group.version
|
||||
|| upload.transformation != new_transformation
|
||||
{
|
||||
let _ = prepare(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
&mut upload.renderer,
|
||||
&mut upload.atlas,
|
||||
&mut upload.buffer_cache,
|
||||
&cache.text,
|
||||
bounds,
|
||||
new_transformation,
|
||||
target_size,
|
||||
);
|
||||
if !cache.text.is_empty() {
|
||||
let _ = prepare(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
&mut upload.renderer,
|
||||
&mut group.atlas,
|
||||
&mut upload.buffer_cache,
|
||||
&cache.text,
|
||||
bounds,
|
||||
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.group_version = group.version;
|
||||
upload.transformation = new_transformation;
|
||||
|
||||
upload.buffer_cache.trim();
|
||||
upload.atlas.trim();
|
||||
}
|
||||
}
|
||||
hash_map::Entry::Vacant(entry) => {
|
||||
let mut atlas = glyphon::TextAtlas::with_color_mode(
|
||||
device, queue, format, COLOR_MODE,
|
||||
);
|
||||
|
||||
let mut renderer = glyphon::TextRenderer::new(
|
||||
&mut atlas,
|
||||
&mut group.atlas,
|
||||
device,
|
||||
wgpu::MultisampleState::default(),
|
||||
None,
|
||||
|
|
@ -143,41 +184,76 @@ impl Storage {
|
|||
|
||||
let mut buffer_cache = BufferCache::new();
|
||||
|
||||
let _ = prepare(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
&mut renderer,
|
||||
&mut atlas,
|
||||
&mut buffer_cache,
|
||||
&cache.text,
|
||||
bounds,
|
||||
new_transformation,
|
||||
target_size,
|
||||
);
|
||||
if !cache.text.is_empty() {
|
||||
let _ = prepare(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
&mut renderer,
|
||||
&mut group.atlas,
|
||||
&mut buffer_cache,
|
||||
&cache.text,
|
||||
bounds,
|
||||
new_transformation,
|
||||
target_size,
|
||||
);
|
||||
}
|
||||
|
||||
let _ = entry.insert(Upload {
|
||||
renderer,
|
||||
atlas,
|
||||
buffer_cache,
|
||||
transformation: new_transformation,
|
||||
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: {})",
|
||||
cache.id.0,
|
||||
self.uploads.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = self.recently_used.insert(cache.id);
|
||||
}
|
||||
|
||||
pub fn trim(&mut self) {
|
||||
self.uploads.retain(|id, _| self.recently_used.contains(id));
|
||||
self.recently_used.clear();
|
||||
self.uploads
|
||||
.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;
|
||||
}
|
||||
Item::Cached { cache, .. } => {
|
||||
if let Some(upload) = storage.get(cache) {
|
||||
if let Some((atlas, upload)) = storage.get(cache) {
|
||||
upload
|
||||
.renderer
|
||||
.render(&upload.atlas, render_pass)
|
||||
.render(atlas, render_pass)
|
||||
.expect("Render cached text");
|
||||
}
|
||||
}
|
||||
|
|
@ -345,7 +421,7 @@ fn prepare(
|
|||
enum Allocation {
|
||||
Paragraph(Paragraph),
|
||||
Editor(Editor),
|
||||
Cache(cache::KeyHash),
|
||||
Cache(text_cache::KeyHash),
|
||||
Raw(Arc<glyphon::Buffer>),
|
||||
}
|
||||
|
||||
|
|
@ -369,7 +445,7 @@ fn prepare(
|
|||
} => {
|
||||
let (key, _) = buffer_cache.allocate(
|
||||
font_system,
|
||||
cache::Key {
|
||||
text_cache::Key {
|
||||
content,
|
||||
size: f32::from(*size),
|
||||
line_height: f32::from(*line_height),
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue