Introduce Refinement trait and derive macro

This commit is contained in:
Nathan Sobo 2023-08-18 01:03:46 -06:00
parent 19ccb19c96
commit 9b74dc196e
22 changed files with 6164 additions and 244 deletions

50
Cargo.lock generated
View File

@ -2161,6 +2161,15 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "derive_refineable"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "dhat"
version = "0.3.2"
@ -3149,6 +3158,7 @@ dependencies = [
"png",
"postage",
"rand 0.8.5",
"refineable",
"resvg",
"schemars",
"seahash",
@ -4964,34 +4974,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "optional_struct"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e60da57c6a9d057c07f1a90ca7abed9d104fca0d0db1a7d7e3304e4567d977fd"
dependencies = [
"optional_struct_internal",
"optional_struct_macro_impl",
]
[[package]]
name = "optional_struct_internal"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64e389cec0df3c934737dadc7b927a8e05b8c8ef792cd1af06a524bd129e9f4d"
[[package]]
name = "optional_struct_macro_impl"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "286db11c92049709d5fbbe89eecaa2febc0efe6c18d94d9ebf942e592ac80f9f"
dependencies = [
"optional_struct_internal",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "orbclient"
version = "0.3.45"
@ -5303,9 +5285,9 @@ dependencies = [
"derive_more",
"gpui",
"log",
"optional_struct",
"parking_lot 0.11.2",
"playground_macros",
"refineable",
"serde",
"simplelog",
"smallvec",
@ -5988,6 +5970,16 @@ dependencies = [
"thiserror",
]
[[package]]
name = "refineable"
version = "0.1.0"
dependencies = [
"derive_refineable",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "regalloc2"
version = "0.2.3"

View File

@ -17,6 +17,8 @@ members = [
"crates/copilot",
"crates/copilot_button",
"crates/db",
"crates/refineable",
"crates/refineable/derive_refineable",
"crates/diagnostics",
"crates/drag_and_drop",
"crates/editor",
@ -94,6 +96,7 @@ ordered-float = { version = "2.1.1" }
parking_lot = { version = "0.11.1" }
postage = { version = "0.5", features = ["futures-traits"] }
rand = { version = "0.8.5" }
refineable = { path = "./crates/refineable" }
regex = { version = "1.5" }
rust-embed = { version = "6.3", features = ["include-exclude"] }
schemars = { version = "0.8" }

View File

@ -39,6 +39,7 @@ pathfinder_color = "0.5"
pathfinder_geometry = "0.5"
postage.workspace = true
rand.workspace = true
refineable.workspace = true
resvg = "0.14"
schemars = "0.8"
seahash = "4.1"

View File

@ -12,9 +12,9 @@ anyhow.workspace = true
derive_more.workspace = true
gpui = { path = ".." }
log.workspace = true
optional_struct = "0.3.1"
playground_macros = { path = "../playground_macros" }
parking_lot.workspace = true
refineable.workspace = true
serde.workspace = true
simplelog = "0.9"
smallvec.workspace = true

View File

@ -1,12 +1,13 @@
use crate::{
adapter::Adapter,
color::Hsla,
style::{Display, ElementStyle, Fill, Overflow, Position},
hoverable::Hoverable,
style::{Display, Fill, Overflow, Position, StyleRefinement},
};
use anyhow::Result;
pub use gpui::LayoutContext;
use gpui::{
geometry::{DefinedLength, Length},
geometry::{DefinedLength, Length, PointRefinement},
platform::{MouseButton, MouseButtonEvent},
EngineLayout, EventContext, RenderContext, ViewContext,
};
@ -26,7 +27,7 @@ pub struct Layout<'a, E: ?Sized> {
}
pub struct ElementMetadata<V> {
pub style: ElementStyle,
pub style: StyleRefinement,
pub handlers: Vec<EventHandler<V>>,
}
@ -49,7 +50,7 @@ impl<V> Clone for EventHandler<V> {
impl<V> Default for ElementMetadata<V> {
fn default() -> Self {
Self {
style: ElementStyle::default(),
style: StyleRefinement::default(),
handlers: Vec::new(),
}
}
@ -58,11 +59,17 @@ impl<V> Default for ElementMetadata<V> {
pub trait Element<V: 'static>: 'static {
type Layout: 'static;
fn style_mut(&mut self) -> &mut ElementStyle;
fn declared_style(&mut self) -> &mut StyleRefinement;
fn computed_style(&mut self) -> &StyleRefinement {
self.declared_style()
}
fn handlers_mut(&mut self) -> &mut Vec<EventHandler<V>>;
fn layout(&mut self, view: &mut V, cx: &mut LayoutContext<V>)
-> Result<(NodeId, Self::Layout)>;
fn paint<'a>(
&mut self,
layout: Layout<Self::Layout>,
@ -208,7 +215,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().display = Display::Block;
self.declared_style().display = Some(Display::Block);
self
}
@ -216,7 +223,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().display = Display::Flex;
self.declared_style().display = Some(Display::Flex);
self
}
@ -224,7 +231,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().display = Display::Grid;
self.declared_style().display = Some(Display::Grid);
self
}
@ -234,8 +241,10 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Visible;
self.style_mut().overflow.y = Overflow::Visible;
self.declared_style().overflow = PointRefinement {
x: Some(Overflow::Visible),
y: Some(Overflow::Visible),
};
self
}
@ -243,8 +252,10 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Hidden;
self.style_mut().overflow.y = Overflow::Hidden;
self.declared_style().overflow = PointRefinement {
x: Some(Overflow::Hidden),
y: Some(Overflow::Hidden),
};
self
}
@ -252,8 +263,10 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Scroll;
self.style_mut().overflow.y = Overflow::Scroll;
self.declared_style().overflow = PointRefinement {
x: Some(Overflow::Scroll),
y: Some(Overflow::Scroll),
};
self
}
@ -261,7 +274,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Visible;
self.declared_style().overflow.x = Some(Overflow::Visible);
self
}
@ -269,7 +282,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Hidden;
self.declared_style().overflow.x = Some(Overflow::Hidden);
self
}
@ -277,7 +290,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.x = Overflow::Scroll;
self.declared_style().overflow.x = Some(Overflow::Scroll);
self
}
@ -285,7 +298,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.y = Overflow::Visible;
self.declared_style().overflow.y = Some(Overflow::Visible);
self
}
@ -293,7 +306,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.y = Overflow::Hidden;
self.declared_style().overflow.y = Some(Overflow::Hidden);
self
}
@ -301,7 +314,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().overflow.y = Overflow::Scroll;
self.declared_style().overflow.y = Some(Overflow::Scroll);
self
}
@ -311,7 +324,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().position = Position::Relative;
self.declared_style().position = Some(Position::Relative);
self
}
@ -319,7 +332,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().position = Position::Absolute;
self.declared_style().position = Some(Position::Absolute);
self
}
@ -329,10 +342,11 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().inset.top = length;
self.style_mut().inset.right = length;
self.style_mut().inset.bottom = length;
self.style_mut().inset.left = length;
let inset = &mut self.declared_style().inset;
inset.top = Some(length);
inset.right = Some(length);
inset.bottom = Some(length);
inset.left = Some(length);
self
}
@ -340,7 +354,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.width = width.into();
self.declared_style().size.width = Some(width.into());
self
}
@ -348,7 +362,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.width = Length::Auto;
self.declared_style().size.width = Some(Length::Auto);
self
}
@ -357,7 +371,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.width = length;
self.declared_style().size.width = Some(length);
self
}
@ -366,7 +380,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().min_size.width = length;
self.declared_style().min_size.width = Some(length);
self
}
@ -374,7 +388,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.height = height.into();
self.declared_style().size.height = Some(height.into());
self
}
@ -382,7 +396,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.height = Length::Auto;
self.declared_style().size.height = Some(Length::Auto);
self
}
@ -391,7 +405,7 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().size.height = height;
self.declared_style().size.height = Some(height);
self
}
@ -400,23 +414,22 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().min_size.height = length;
self.declared_style().min_size.height = Some(length);
self
}
fn hoverable(self) -> Hoverable<V, Self>
where
Self: Sized,
{
Hoverable::new(self)
}
fn fill(mut self, fill: impl Into<Fill>) -> Self
where
Self: Sized,
{
self.style_mut().fill = Some(fill.into());
self
}
fn hover_fill(mut self, fill: impl Into<Fill>) -> Self
where
Self: Sized,
{
self.style_mut().hover_fill = Some(fill.into());
self.declared_style().fill = Some(fill.into());
self
}
@ -424,14 +437,14 @@ pub trait Element<V: 'static>: 'static {
where
Self: Sized,
{
self.style_mut().text_color = Some(color.into());
self.declared_style().text_color = Some(color.into());
self
}
}
// Object-safe counterpart of Element used by AnyElement to store elements as trait objects.
trait ElementObject<V> {
fn style_mut(&mut self) -> &mut ElementStyle;
fn style(&mut self) -> &mut StyleRefinement;
fn handlers_mut(&mut self) -> &mut Vec<EventHandler<V>>;
fn layout(&mut self, view: &mut V, cx: &mut LayoutContext<V>)
-> Result<(NodeId, Box<dyn Any>)>;
@ -444,8 +457,8 @@ trait ElementObject<V> {
}
impl<V: 'static, E: Element<V>> ElementObject<V> for E {
fn style_mut(&mut self) -> &mut ElementStyle {
Element::style_mut(self)
fn style(&mut self) -> &mut StyleRefinement {
Element::declared_style(self)
}
fn handlers_mut(&mut self) -> &mut Vec<EventHandler<V>> {
@ -498,11 +511,9 @@ impl<V: 'static> AnyElement<V> {
}
pub fn push_text_style(&mut self, cx: &mut impl RenderContext) -> bool {
let text_style = self.element.style_mut().text_style();
let text_style = self.element.style().text_style();
if let Some(text_style) = text_style {
let mut current_text_style = cx.text_style();
text_style.apply(&mut current_text_style);
cx.push_text_style(current_text_style);
cx.push_text_style(cx.text_style().refine(text_style));
true
} else {
false
@ -524,20 +535,17 @@ impl<V: 'static> AnyElement<V> {
from_element: element_layout.as_mut(),
};
let fill_color = self
.element
.style_mut()
.fill
.as_ref()
.and_then(Fill::color)
.map(Into::into);
let style = self.element.style();
cx.scene.push_quad(gpui::scene::Quad {
bounds: layout.from_engine.bounds,
background: fill_color,
border: Default::default(),
corner_radii: Default::default(),
});
let fill_color = style.fill.as_ref().and_then(|fill| fill.color());
if let Some(fill_color) = fill_color {
cx.scene.push_quad(gpui::scene::Quad {
bounds: layout.from_engine.bounds,
background: Some(fill_color.into()),
border: Default::default(),
corner_radii: Default::default(),
});
}
for event_handler in self.element.handlers_mut().iter().cloned() {
let EngineLayout { order, bounds } = layout.from_engine;
@ -574,8 +582,8 @@ impl<V: 'static> AnyElement<V> {
impl<V: 'static> Element<V> for AnyElement<V> {
type Layout = ();
fn style_mut(&mut self) -> &mut ElementStyle {
self.element.style_mut()
fn declared_style(&mut self) -> &mut StyleRefinement {
self.element.style()
}
fn handlers_mut(&mut self) -> &mut Vec<EventHandler<V>> {

View File

@ -2,23 +2,24 @@ use crate::{
element::{
AnyElement, Element, EventHandler, IntoElement, Layout, LayoutContext, NodeId, PaintContext,
},
style::ElementStyle,
style::{Style, StyleRefinement},
};
use anyhow::{anyhow, Result};
use gpui::LayoutNodeId;
use playground_macros::IntoElement;
use refineable::Refineable;
#[derive(IntoElement)]
#[element_crate = "crate"]
pub struct Frame<V: 'static> {
style: ElementStyle,
style: StyleRefinement,
handlers: Vec<EventHandler<V>>,
children: Vec<AnyElement<V>>,
}
pub fn frame<V>() -> Frame<V> {
Frame {
style: ElementStyle::default(),
style: StyleRefinement::default(),
handlers: Vec::new(),
children: Vec::new(),
}
@ -27,7 +28,7 @@ pub fn frame<V>() -> Frame<V> {
impl<V: 'static> Element<V> for Frame<V> {
type Layout = ();
fn style_mut(&mut self) -> &mut ElementStyle {
fn declared_style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
@ -47,10 +48,11 @@ impl<V: 'static> Element<V> for Frame<V> {
.collect::<Result<Vec<LayoutNodeId>>>()?;
let rem_size = cx.rem_pixels();
let style = Style::default().refine(&self.style);
let node_id = cx
.layout_engine()
.ok_or_else(|| anyhow!("no layout engine"))?
.add_node(self.style.to_taffy(rem_size), child_layout_node_ids)?;
.add_node(style.to_taffy(rem_size), child_layout_node_ids)?;
Ok((node_id, ()))
}

View File

@ -0,0 +1,80 @@
use std::{cell::Cell, marker::PhantomData, rc::Rc};
use gpui::{
geometry::{rect::RectF, vector::Vector2F},
scene::MouseMove,
EngineLayout,
};
use crate::{
element::Element,
style::{Style, StyleRefinement},
};
pub struct Hoverable<V, E> {
hover_style: StyleRefinement,
computed_style: Option<Style>,
view_type: PhantomData<V>,
child: E,
}
impl<V, E> Hoverable<V, E> {
pub fn new(child: E) -> Self {
Self {
hover_style: StyleRefinement::default(),
computed_style: None,
view_type: PhantomData,
child,
}
}
}
impl<V: 'static, E: Element<V>> Element<V> for Hoverable<V, E> {
type Layout = E::Layout;
fn declared_style(&mut self) -> &mut StyleRefinement {
&mut self.hover_style
}
fn computed_style(&mut self) -> &StyleRefinement {
todo!()
}
fn handlers_mut(&mut self) -> &mut Vec<crate::element::EventHandler<V>> {
self.child.handlers_mut()
}
fn layout(
&mut self,
view: &mut V,
cx: &mut gpui::LayoutContext<V>,
) -> anyhow::Result<(taffy::tree::NodeId, Self::Layout)> {
self.child.layout(view, cx)
}
fn paint<'a>(
&mut self,
layout: crate::element::Layout<Self::Layout>,
view: &mut V,
cx: &mut crate::element::PaintContext<V>,
) -> anyhow::Result<()> {
let EngineLayout { bounds, order } = layout.from_engine;
let window_bounds = RectF::new(Vector2F::zero(), cx.window_size());
let was_hovered = Rc::new(Cell::new(false));
self.child.paint(layout, view, cx)?;
cx.draw_interactive_region(
order,
window_bounds,
false,
move |view, event: &MouseMove, cx| {
let is_hovered = bounds.contains_point(cx.mouse_position());
if is_hovered != was_hovered.get() {
was_hovered.set(is_hovered);
cx.repaint();
}
},
);
Ok(())
}
}

View File

@ -18,6 +18,7 @@ mod color;
mod components;
mod element;
mod frame;
mod hoverable;
mod paint_context;
mod style;
mod text;

View File

@ -1,17 +1,24 @@
use crate::color::Hsla;
use gpui::geometry::{DefinedLength, Edges, Length, Point, Size};
use gpui::{
fonts::TextStyleRefinement,
geometry::{
DefinedLength, Edges, EdgesRefinement, Length, Point, PointRefinement, Size, SizeRefinement,
},
};
use refineable::Refineable;
pub use taffy::style::{
AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
Overflow, Position,
};
#[derive(Clone)]
pub struct ElementStyle {
#[derive(Clone, Refineable)]
pub struct Style {
/// What layout strategy should be used?
pub display: Display,
// Overflow properties
/// How children overflowing their container should affect layout
#[refineable]
pub overflow: Point<Overflow>,
/// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
pub scrollbar_width: f32,
@ -20,24 +27,31 @@ pub struct ElementStyle {
/// What should the `position` value of this struct use as a base offset?
pub position: Position,
/// How should the position of this element be tweaked relative to the layout defined?
#[refineable]
pub inset: Edges<Length>,
// Size properies
/// Sets the initial size of the item
#[refineable]
pub size: Size<Length>,
/// Controls the minimum size of the item
#[refineable]
pub min_size: Size<Length>,
/// Controls the maximum size of the item
#[refineable]
pub max_size: Size<Length>,
/// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
pub aspect_ratio: Option<f32>,
// Spacing Properties
/// How large should the margin be on each side?
#[refineable]
pub margin: Edges<Length>,
/// How large should the padding be on each side?
#[refineable]
pub padding: Edges<DefinedLength>,
/// How large should the border be on each side?
#[refineable]
pub border: Edges<DefinedLength>,
// Alignment properties
@ -50,6 +64,7 @@ pub struct ElementStyle {
/// How should contained within this item be aligned in the main/inline axis
pub justify_content: Option<JustifyContent>,
/// How large should the gaps between items in a flex container be?
#[refineable]
pub gap: Size<DefinedLength>,
// Flexbox properies
@ -66,14 +81,12 @@ pub struct ElementStyle {
/// The fill color of this element
pub fill: Option<Fill>,
/// The fill color of this element when hovered
pub hover_fill: Option<Fill>,
/// The color of text within this element. Cascades to children unless overridden.
pub text_color: Option<Hsla>,
}
impl ElementStyle {
pub const DEFAULT: ElementStyle = ElementStyle {
impl Style {
pub const DEFAULT: Style = Style {
display: Display::DEFAULT,
overflow: Point {
x: Overflow::Visible,
@ -102,7 +115,6 @@ impl ElementStyle {
flex_shrink: 1.0,
flex_basis: Length::Auto,
fill: None,
hover_fill: None,
text_color: None,
};
@ -137,21 +149,20 @@ impl ElementStyle {
..Default::default() // Ignore grid properties for now
}
}
}
pub fn text_style(&self) -> Option<OptionalTextStyle> {
if self.text_color.is_some() {
Some(OptionalTextStyle {
color: self.text_color,
})
} else {
None
}
impl Default for Style {
fn default() -> Self {
Self::DEFAULT.clone()
}
}
impl Default for ElementStyle {
fn default() -> Self {
Self::DEFAULT.clone()
impl StyleRefinement {
pub fn text_style(&self) -> Option<TextStyleRefinement> {
self.text_color.map(|color| TextStyleRefinement {
color: Some(color.into()),
..Default::default()
})
}
}

View File

@ -1,6 +1,10 @@
use crate::element::{Element, ElementMetadata, EventHandler, IntoElement};
use crate::{
element::{Element, ElementMetadata, EventHandler, IntoElement},
style::Style,
};
use gpui::{geometry::Size, text_layout::LineLayout, RenderContext};
use parking_lot::Mutex;
use refineable::Refineable;
use std::sync::Arc;
impl<V: 'static, S: Into<ArcCow<'static, str>>> IntoElement<V> for S {
@ -22,7 +26,7 @@ pub struct Text<V> {
impl<V: 'static> Element<V> for Text<V> {
type Layout = Arc<Mutex<Option<TextLayout>>>;
fn style_mut(&mut self) -> &mut crate::style::ElementStyle {
fn declared_style(&mut self) -> &mut crate::style::StyleRefinement {
&mut self.metadata.style
}
@ -39,7 +43,8 @@ impl<V: 'static> Element<V> for Text<V> {
let text = self.text.clone();
let layout = Arc::new(Mutex::new(None));
let node_id = layout_engine.add_measured_node(self.metadata.style.to_taffy(rem_size), {
let style: Style = Style::default().refine(&self.metadata.style);
let node_id = layout_engine.add_measured_node(style.to_taffy(rem_size), {
let layout = layout.clone();
move |params| {
let line_layout = fonts.layout_line(

View File

@ -79,7 +79,7 @@ pub fn derive_element(input: TokenStream) -> TokenStream {
{
type Layout = #crate_name::element::AnyElement<V>;
fn style_mut(&mut self) -> &mut #crate_name::style::ElementStyle {
fn declared_style(&mut self) -> &mut #crate_name::style::StyleRefinement {
&mut self.metadata.style
}

View File

@ -29,7 +29,6 @@ pub fn derive_into_element(input: TokenStream) -> TokenStream {
}
})
.unwrap_or_else(|| String::from("playground"));
let crate_name = format_ident!("{}", crate_name);
let placeholder_view_generics: Generics = parse_quote! { <V: 'static> };

View File

@ -1,95 +0,0 @@
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, Expr, Ident, Token};
struct Args {
method_name: Ident,
method_suffix: Option<Ident>,
field_name: Ident,
value: Expr,
}
impl syn::parse::Parse for Args {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let method_name = input.parse()?;
let method_suffix = if input.peek(Token![::]) {
input.parse::<Token![::]>()?;
Some(input.parse()?)
} else {
None
};
input.parse::<Token![,]>()?;
let field_name = input.parse()?;
input.parse::<Token![,]>()?;
let value = input.parse()?;
Ok(Self {
method_name,
method_suffix,
field_name,
value,
})
}
}
fn fixed_lengths() -> Vec<(&'static str, proc_macro2::TokenStream)> {
vec![
("0", quote! { DefinedLength::Pixels(0.) }),
("px", quote! { DefinedLength::Pixels(1.) }),
("0_5", quote! { DefinedLength::Rems(0.125) }),
// ...
]
}
pub fn style_methods(input: TokenStream) -> TokenStream {
let Args {
method_name,
method_suffix,
field_name,
value,
} = parse_macro_input!(input as Args);
let hover_method_name = format!("hover_{}", method_name);
let hover_method_ident = syn::Ident::new(&hover_method_name, method_name.span());
let mut result = quote! {
fn #method_name(mut self) -> Self
where
Self: Sized,
{
self.metadata().style.#field_name = #value;
self
}
fn #hover_method_ident(mut self) -> Self
where
Self: Sized,
{
self.metadata().hover_style.#field_name = Some(#value);
self
}
};
if let Some(suffix_ident) = method_suffix {
if suffix_ident == "_" {
let fixed_lengths = fixed_lengths();
for (suffix, value) in fixed_lengths {
let method_ident =
syn::Ident::new(&format!("{}_{}", method_name, suffix), method_name.span());
let method = quote! {
fn #method_ident(mut self) -> Self
where
Self: Sized,
{
self.metadata().style.#field_name = #value;
self
}
};
result.extend(method);
}
}
}
result.into()
}

View File

@ -1648,6 +1648,9 @@ impl AppContext {
subscription_id,
callback,
),
Effect::RepaintWindow { window } => {
self.handle_repaint_window_effect(window)
}
}
self.pending_notifications.clear();
} else {
@ -1885,6 +1888,14 @@ impl AppContext {
});
}
fn handle_repaint_window_effect(&mut self, window: AnyWindowHandle) {
self.update_window(window, |cx| {
if let Some(scene) = cx.paint().log_err() {
cx.window.platform_window.present_scene(scene);
}
});
}
fn handle_window_activation_effect(&mut self, window: AnyWindowHandle, active: bool) -> bool {
self.update_window(window, |cx| {
if cx.window.is_active == active {
@ -2244,6 +2255,9 @@ pub enum Effect {
window: AnyWindowHandle,
is_active: bool,
},
RepaintWindow {
window: AnyWindowHandle,
},
WindowActivationObservation {
window: AnyWindowHandle,
subscription_id: usize,
@ -2437,6 +2451,10 @@ impl Debug for Effect {
.debug_struct("Effect::ActiveLabeledTasksObservation")
.field("subscription_id", subscription_id)
.finish(),
Effect::RepaintWindow { window } => f
.debug_struct("Effect::RepaintWindow")
.field("window_id", &window.id())
.finish(),
}
}
}
@ -3617,7 +3635,7 @@ pub struct EventContext<'a, 'b, 'c, V> {
pub(crate) handled: bool,
}
impl<'a, 'b, 'c, V> EventContext<'a, 'b, 'c, V> {
impl<'a, 'b, 'c, V: 'static> EventContext<'a, 'b, 'c, V> {
pub fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
EventContext {
view_context,
@ -3628,6 +3646,12 @@ impl<'a, 'b, 'c, V> EventContext<'a, 'b, 'c, V> {
pub fn propagate_event(&mut self) {
self.handled = false;
}
pub fn repaint(&mut self) {
let window = self.window();
self.pending_effects
.push_back(Effect::RepaintWindow { window });
}
}
impl<'a, 'b, 'c, V> Deref for EventContext<'a, 'b, 'c, V> {

View File

@ -252,6 +252,10 @@ impl<'a> WindowContext<'a> {
self.window.platform_window.content_size()
}
pub fn mouse_position(&self) -> Vector2F {
self.window.mouse_position
}
pub fn text_layout_cache(&self) -> &TextLayoutCache {
&self.window.text_layout_cache
}
@ -892,7 +896,7 @@ impl<'a> WindowContext<'a> {
mouse_event,
window_cx,
region.view_id,
)
);
});
}
}
@ -1347,6 +1351,7 @@ pub struct MeasureParams {
pub available_space: Size<AvailableSpace>,
}
#[derive(Clone)]
pub enum AvailableSpace {
/// The amount of space available is the specified number of pixels
Pixels(f32),

View File

@ -11,6 +11,7 @@ pub use font_kit::{
properties::{Properties, Stretch, Style, Weight},
};
use ordered_float::OrderedFloat;
use refineable::Refineable;
use schemars::JsonSchema;
use serde::{de, Deserialize, Serialize};
use serde_json::Value;
@ -59,7 +60,7 @@ pub struct Features {
pub zero: Option<bool>,
}
#[derive(Clone, Debug, JsonSchema)]
#[derive(Clone, Debug, JsonSchema, Refineable)]
pub struct TextStyle {
pub color: Color,
pub font_family_name: Arc<str>,
@ -72,18 +73,6 @@ pub struct TextStyle {
pub soft_wrap: bool,
}
#[derive(Clone, Debug)]
pub struct TextStyleRefinement {
pub color: Option<Color>,
pub font_family_name: Option<Arc<str>>,
pub font_family_id: Option<FamilyId>,
pub font_id: Option<FontId>,
pub font_size: Option<f32>,
pub font_properties: Option<Properties>,
pub underline: Option<Underline>,
pub soft_wrap: Option<bool>,
}
impl TextStyle {
pub fn refine(self, refinement: TextStyleRefinement) -> TextStyle {
TextStyle {

View File

@ -2,6 +2,7 @@ use super::scene::{Path, PathVertex};
use crate::{color::Color, json::ToJson};
pub use pathfinder_geometry::*;
use rect::RectF;
use refineable::Refineable;
use serde::{Deserialize, Deserializer};
use serde_json::json;
use vector::{vec2f, Vector2F};
@ -132,13 +133,22 @@ impl ToJson for RectF {
}
}
#[derive(Clone)]
pub struct Point<T> {
#[derive(Refineable)]
pub struct Point<T: Clone> {
pub x: T,
pub y: T,
}
impl<T> Into<taffy::geometry::Point<T>> for Point<T> {
impl<T: Clone> Clone for Point<T> {
fn clone(&self) -> Self {
Self {
x: self.x.clone(),
y: self.y.clone(),
}
}
}
impl<T: Clone> Into<taffy::geometry::Point<T>> for Point<T> {
fn into(self) -> taffy::geometry::Point<T> {
taffy::geometry::Point {
x: self.x,
@ -147,13 +157,13 @@ impl<T> Into<taffy::geometry::Point<T>> for Point<T> {
}
}
#[derive(Clone)]
pub struct Size<T> {
#[derive(Clone, Refineable)]
pub struct Size<T: Clone> {
pub width: T,
pub height: T,
}
impl<S, T> From<taffy::geometry::Size<S>> for Size<T>
impl<S, T: Clone> From<taffy::geometry::Size<S>> for Size<T>
where
S: Into<T>,
{
@ -165,7 +175,7 @@ where
}
}
impl<S, T> Into<taffy::geometry::Size<S>> for Size<T>
impl<S, T: Clone> Into<taffy::geometry::Size<S>> for Size<T>
where
T: Into<S>,
{
@ -212,8 +222,8 @@ impl Size<Length> {
}
}
#[derive(Clone)]
pub struct Edges<T> {
#[derive(Clone, Default, Refineable)]
pub struct Edges<T: Clone> {
pub top: T,
pub right: T,
pub bottom: T,
@ -292,6 +302,12 @@ impl DefinedLength {
}
}
impl Default for DefinedLength {
fn default() -> Self {
Self::Pixels(0.)
}
}
/// A length that can be defined in pixels, rems, percent of parent, or auto.
#[derive(Clone, Copy)]
pub enum Length {
@ -329,3 +345,9 @@ impl From<DefinedLength> for Length {
Length::Defined(value)
}
}
impl Default for Length {
fn default() -> Self {
Self::Defined(DefinedLength::default())
}
}

View File

@ -0,0 +1,14 @@
[package]
name = "refineable"
version = "0.1.0"
edition = "2021"
[lib]
path = "src/refineable.rs"
doctest = false
[dependencies]
syn = "1.0.72"
quote = "1.0.9"
proc-macro2 = "1.0.66"
derive_refineable = { path = "./derive_refineable" }

View File

@ -0,0 +1,14 @@
[package]
name = "derive_refineable"
version = "0.1.0"
edition = "2021"
[lib]
path = "src/derive_refineable.rs"
proc-macro = true
doctest = false
[dependencies]
syn = "1.0.72"
quote = "1.0.9"
proc-macro2 = "1.0.66"

View File

@ -0,0 +1,162 @@
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
parse_macro_input, parse_quote, DeriveInput, Field, FieldsNamed, PredicateType, TraitBound,
Type, TypeParamBound, WhereClause, WherePredicate,
};
#[proc_macro_derive(Refineable, attributes(refineable))]
pub fn derive_refineable(input: TokenStream) -> TokenStream {
let DeriveInput {
ident,
data,
generics,
..
} = parse_macro_input!(input);
let refinement_ident = format_ident!("{}Refinement", ident);
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let fields = match data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(FieldsNamed { named, .. }),
..
}) => named.into_iter().collect::<Vec<Field>>(),
_ => panic!("This derive macro only supports structs with named fields"),
};
let field_names: Vec<_> = fields.iter().map(|f| f.ident.as_ref().unwrap()).collect();
let field_visibilities: Vec<_> = fields.iter().map(|f| &f.vis).collect();
let wrapped_types: Vec<_> = fields.iter().map(|f| get_wrapper_type(f, &f.ty)).collect();
// Create trait bound that each wrapped type must implement Clone & Default
let type_param_bounds: Vec<_> = wrapped_types
.iter()
.map(|ty| {
WherePredicate::Type(PredicateType {
lifetimes: None,
bounded_ty: ty.clone(),
colon_token: Default::default(),
bounds: {
let mut punctuated = syn::punctuated::Punctuated::new();
punctuated.push_value(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: syn::TraitBoundModifier::None,
lifetimes: None,
path: parse_quote!(std::clone::Clone),
}));
punctuated.push_punct(syn::token::Add::default());
punctuated.push_value(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: syn::TraitBoundModifier::None,
lifetimes: None,
path: parse_quote!(std::default::Default),
}));
punctuated
},
})
})
.collect();
// Append to where_clause or create a new one if it doesn't exist
let where_clause = match where_clause.cloned() {
Some(mut where_clause) => {
where_clause
.predicates
.extend(type_param_bounds.into_iter());
where_clause.clone()
}
None => WhereClause {
where_token: Default::default(),
predicates: type_param_bounds.into_iter().collect(),
},
};
let field_initializations: Vec<TokenStream2> = fields
.iter()
.map(|field| {
let name = &field.ident;
let is_refineable = is_refineable_field(field);
let is_optional = is_optional_field(field);
if is_refineable {
quote! {
clone.#name = self.#name.refine(&refinement.#name);
}
} else if is_optional {
quote! {
if let Some(ref value) = &refinement.#name {
clone.#name = Some(value.clone());
}
}
} else {
quote! {
if let Some(ref value) = &refinement.#name {
clone.#name = value.clone();
}
}
}
})
.collect();
let gen = quote! {
#[derive(Default, Clone)]
pub struct #refinement_ident #impl_generics {
#( #field_visibilities #field_names: #wrapped_types ),*
}
impl #impl_generics Refineable for #ident #ty_generics
#where_clause
{
type Refinement = #refinement_ident #ty_generics;
fn refine(&self, refinement: &Self::Refinement) -> Self {
let mut clone = self.clone();
#( #field_initializations )*
clone
}
}
};
println!("{}", gen);
gen.into()
}
fn is_refineable_field(f: &Field) -> bool {
f.attrs.iter().any(|attr| attr.path.is_ident("refineable"))
}
fn is_optional_field(f: &Field) -> bool {
if let Type::Path(typepath) = &f.ty {
if typepath.qself.is_none() {
let segments = &typepath.path.segments;
if segments.len() == 1 && segments.iter().any(|s| s.ident == "Option") {
return true;
}
}
}
false
}
fn get_wrapper_type(field: &Field, ty: &Type) -> syn::Type {
if is_refineable_field(field) {
let struct_name = if let Type::Path(tp) = ty {
tp.path.segments.last().unwrap().ident.clone()
} else {
panic!("Expected struct type for a refineable field");
};
let refinement_struct_name = format_ident!("{}Refinement", struct_name);
let generics = if let Type::Path(tp) = ty {
&tp.path.segments.last().unwrap().arguments
} else {
&syn::PathArguments::None
};
parse_quote!(#refinement_struct_name #generics)
} else if is_optional_field(field) {
ty.clone()
} else {
parse_quote!(Option<#ty>)
}
}

View File

@ -0,0 +1,13 @@
pub use derive_refineable::Refineable;
pub trait Refineable {
type Refinement;
fn refine(&self, refinement: &Self::Refinement) -> Self;
fn from_refinement(refinement: &Self::Refinement) -> Self
where
Self: Sized + Default,
{
Self::default().refine(refinement)
}
}

5670
test.rs Normal file

File diff suppressed because it is too large Load Diff