use std::fmt;
use std::rc::Rc;
use waft_embedder::{Canvas, Color, Matrix4, Offset};
use waft_foundation::{
App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listener, OptionRetained, Ref,
};
use waft_painting::{
BoxDecoration, BoxPainter, DecorationRef, EdgeInsets, EdgeInsetsGeometry, ImageConfiguration,
get_as_translation,
};
use waft_rendering::{AnyRenderBox, BoxConstraints};
use waft_widgets::{
BuildContext, Builder, ConstrainedBox, GlobalKey, IntoWidget, KeyRef, Padding, SizedBox, State,
StateData, StatefulWidget, Visibility, WidgetRef, create_local_image_configuration,
};
use crate::debug::debug_check_has_material;
use crate::material::{
AnyMaterialInkController, InkFeature, InkFeatureData, InkFeatureLeaf, InkFeatureLeafData,
Material,
};
pub struct Ink {
pub key: Option<KeyRef>,
pub child: Option<WidgetRef>,
pub padding: Option<EdgeInsetsGeometry>,
pub color: Option<Color>,
pub decoration: Option<DecorationRef>,
pub width: Option<f64>,
pub height: Option<f64>,
}
impl fmt::Debug for Ink {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ink")
.field("padding", &self.padding)
.field("bg", &self.effective_decoration())
.finish_non_exhaustive()
}
}
impl Ink {
pub fn new() -> Ink {
Ink {
key: None,
child: None,
padding: None,
color: None,
decoration: None,
width: None,
height: None,
}
}
pub fn key(mut self, key: KeyRef) -> Ink {
self.key = Some(key);
self
}
pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Ink {
let padding = padding.into();
debug_assert!(padding.is_non_negative());
self.padding = Some(padding);
self
}
pub fn color(mut self, color: Color) -> Ink {
self.color = Some(color);
self.debug_assert_color_or_decoration();
self
}
pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> Ink {
let decoration = decoration.into();
debug_assert!(decoration.debug_assert_is_valid());
self.decoration = Some(decoration);
self.debug_assert_color_or_decoration();
self
}
pub fn width(mut self, width: f64) -> Ink {
self.width = Some(width);
self
}
pub fn height(mut self, height: f64) -> Ink {
self.height = Some(height);
self
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Ink {
self.child = Some(child.into_widget());
self
}
fn debug_assert_color_or_decoration(&self) {
debug_assert!(
self.color.is_none() || self.decoration.is_none(),
"Cannot provide both a color and a decoration\nThe color argument is just a \
shorthand for \"decoration: BoxDecoration(color: color)\"."
);
}
pub fn effective_decoration(&self) -> Option<DecorationRef> {
match (&self.decoration, self.color) {
(Some(decoration), _) => Some(decoration.clone()),
(None, Some(color)) => Some(DecorationRef::new(BoxDecoration::new().color(color))),
(None, None) => None,
}
}
fn padding_including_decoration(&self) -> EdgeInsetsGeometry {
let decoration_padding = self
.effective_decoration()
.map(|decoration| decoration.padding());
match (self.padding, decoration_padding) {
(None, None) => EdgeInsets::ZERO.into(),
(None, Some(padding)) => padding,
(Some(padding), None) => padding,
(Some(padding), Some(decoration_padding)) => padding.add(decoration_padding),
}
}
}
impl Default for Ink {
fn default() -> Ink {
Ink::new()
}
}
impl StatefulWidget for Ink {
type State = InkState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
properties.add(
DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
.default_value(None),
);
properties.add(
DiagnosticsProperty::<DecorationRef>::new("bg", self.decoration.clone())
.default_value(None),
);
}
fn create_state(&self) -> InkState {
InkState {
state: StateData::new(),
box_key: GlobalKey::new(),
ink: None,
}
}
}
pub struct InkState {
state: StateData<Ink>,
box_key: GlobalKey,
ink: Option<Ref<InkDecoration>>,
}
impl InkState {
fn handle_removed(self: Handle<Self>, app: &mut App) {
app.get_mut(self).ink = None;
}
fn build_child(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let decoration = self.widget(app).effective_decoration();
let is_visible = Visibility::of(app, context);
let configuration = create_local_image_configuration(app, context, None);
match app.get(self).ink.clone() {
None => {
let controller = Material::of(app, context);
let box_key = app.get(self).box_key.clone();
let reference_box = box_key
.current_context(app)
.expect("the padding is mounted")
.find_render_object(app)
.and_then(|render_object| render_object.as_box())
.expect("the padding is a render box");
let ink = InkDecoration::new(
app,
decoration,
is_visible,
configuration,
controller,
reference_box,
Some(Listener::handle_method(self, Self::handle_removed)),
);
app.get_mut(self).ink = Some(ink);
}
Some(ink) => {
ink.set_decoration(app, decoration);
ink.set_is_visible(app, is_visible);
ink.set_configuration(app, configuration);
}
}
self.widget(app).child.clone().unwrap_or_else(|| {
ConstrainedBox::new(BoxConstraints::expand(None, None)).into_widget()
})
}
}
impl State for InkState {
type Widget = Ink;
waft_widgets::state_accessors!();
fn deactivate(self: Handle<Self>, app: &mut App) {
if let Some(ink) = app.get(self).ink.handle() {
InkFeatureLeaf::dispose(ink, app);
}
debug_assert!(app.get(self).ink.is_none());
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
debug_assert!(debug_check_has_material(app, context));
let widget = self.widget(app);
let padding = widget.padding_including_decoration();
let (width, height) = (widget.width, widget.height);
let box_key = app.get(self).box_key.clone();
let mut result = Padding::new(padding)
.key(box_key.into())
.child(Builder::new(move |app, context| {
self.build_child(app, context)
}))
.into_widget();
if width.is_some() || height.is_some() {
let mut sized = SizedBox::new();
if let Some(width) = width {
sized = sized.width(width);
}
if let Some(height) = height {
sized = sized.height(height);
}
result = sized.child(result).into_widget();
}
result
}
}
pub struct InkDecoration {
ink_feature: InkFeatureData,
painter: Option<Box<dyn BoxPainter>>,
decoration: Option<DecorationRef>,
is_visible: bool,
configuration: ImageConfiguration,
}
impl InkDecoration {
pub fn new(
app: &mut App,
decoration: Option<DecorationRef>,
is_visible: bool,
configuration: ImageConfiguration,
controller: AnyMaterialInkController,
reference_box: AnyRenderBox,
on_removed: Option<Listener>,
) -> Ref<InkDecoration> {
let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
let this = app.create(InkDecoration {
ink_feature,
painter: None,
decoration: None,
is_visible: true,
configuration,
});
this.set_decoration(app, decoration);
this.set_is_visible(app, is_visible);
controller.add_ink_feature(app, this.erase());
this
}
pub fn decoration(self: Handle<Self>, app: &App) -> Option<&DecorationRef> {
app.get(self).decoration.as_ref()
}
pub fn set_decoration(self: Handle<Self>, app: &mut App, value: Option<DecorationRef>) {
if value == app.get(self).decoration {
return;
}
let controller = InkFeature::controller(self, app);
let painter = value.as_ref().map(|decoration| {
decoration.create_box_painter(Some(Rc::new(move |app: &mut App| {
controller.mark_needs_paint(app)
})))
});
let ink = app.get_mut(self);
ink.decoration = value;
if let Some(mut old_painter) = std::mem::replace(&mut ink.painter, painter) {
old_painter.dispose();
}
controller.mark_needs_paint(app);
}
pub fn is_visible(self: Handle<Self>, app: &App) -> bool {
app.get(self).is_visible
}
pub fn set_is_visible(self: Handle<Self>, app: &mut App, value: bool) {
if value == app.get(self).is_visible {
return;
}
app.get_mut(self).is_visible = value;
InkFeature::controller(self, app).mark_needs_paint(app);
}
pub fn configuration(self: Handle<Self>, app: &App) -> &ImageConfiguration {
&app.get(self).configuration
}
pub fn set_configuration(self: Handle<Self>, app: &mut App, value: ImageConfiguration) {
if value == app.get(self).configuration {
return;
}
app.get_mut(self).configuration = value;
InkFeature::controller(self, app).mark_needs_paint(app);
}
}
impl InkFeatureLeafData for InkDecoration {
fn ink_feature(&self) -> &InkFeatureData {
&self.ink_feature
}
fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
&mut self.ink_feature
}
}
impl InkFeatureLeaf for InkDecoration {
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(mut painter) = app.get_mut(self).painter.take() {
painter.dispose();
}
InkFeature::dispose(self, app);
}
fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
if app.get(self).painter.is_none() || !self.is_visible(app) {
return;
}
let origin_offset = get_as_translation(*transform);
let size = InkFeature::reference_box(self, app).size(app);
let sized_configuration =
self.configuration(app)
.copy_with(None, None, None, None, Some(size), None);
let painter = app.get_mut(self).painter.as_mut().expect("checked above");
match origin_offset {
None => {
canvas.save();
canvas.concat(transform);
painter.paint(canvas, Offset::ZERO, &sized_configuration);
canvas.restore();
}
Some(origin_offset) => {
painter.paint(canvas, origin_offset, &sized_configuration);
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use waft_embedder::{Rect, Size};
use waft_widgets::Center;
use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
use super::*;
use crate::colors::Colors;
use crate::ink_well::InkWell;
use crate::test_support::{PaintInspection, path_like};
use crate::theme::Theme;
use crate::theme_data::ThemeData;
use waft_rendering::testing::RecordedCall;
#[test]
fn the_ink_widget_expands_when_no_dimensions_are_set() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(
Material::new()
.child(Ink::new().key(key.clone().into()))
.into_widget(),
);
assert_eq!(tester.get_size(&key), Size::new(800.0, 600.0));
});
}
#[test]
fn the_ink_widget_fits_the_specified_size() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(
Material::new()
.child(
Center::new().child(
Ink::new()
.key(key.clone().into())
.height(150.0)
.width(200.0),
),
)
.into_widget(),
);
tester.pump_and_settle();
assert_eq!(tester.get_size(&key), Size::new(200.0, 150.0));
});
}
#[test]
fn the_ink_widget_expands_on_a_unspecified_dimension() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(
Material::new()
.child(
Center::new().child(Ink::new().key(key.clone().into()).height(150.0)),
)
.into_widget(),
);
tester.pump_and_settle();
assert_eq!(tester.get_size(&key), Size::new(800.0, 150.0));
});
}
fn m2_ink_frame(tester: &WidgetTester, ink: Option<Color>) -> WidgetRef {
let ink_well = InkWell::new()
.splash_color(Colors::GREEN.primary())
.on_tap(Listener::new(|_app| {}));
let child = match ink {
Some(color) => Ink::new()
.color(color)
.width(200.0)
.height(200.0)
.child(ink_well)
.into_widget(),
None => ink_well.into_widget(),
};
let data = ThemeData::builder()
.use_material3(false)
.build(&tester.cell.borrow());
Theme::new(
data,
waft_widgets::Directionality::new(
waft_embedder::TextDirection::Ltr,
Material::new().child(Center::new().child(child)),
),
)
.into_widget()
}
fn paints_rect_then_circle(
tester: &WidgetTester,
rect_color: Color,
rect: Rect,
circle_color: Color,
) -> bool {
use waft_rendering::testing::{PaintCall, paints};
paints(
tester.ink_list().ops(),
&[
PaintCall::rect_at(rect, Some(rect_color)),
PaintCall::circle(Some(circle_color)),
],
)
.is_ok()
}
#[test]
fn material2_does_the_ink_widget_render_anything() {
test_widgets(|tester| {
let blue = Colors::BLUE.primary();
let red = Colors::RED.primary();
let green = Colors::GREEN.primary();
let ink_rect = Rect::from_ltrb(300.0, 200.0, 500.0, 400.0);
let widget = m2_ink_frame(tester, Some(blue));
tester.pump_widget(widget);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, WidgetTester::SIZE.center(Offset::ZERO));
tester.pump(); tester.pump_by(Duration::from_millis(200));
let box_ = tester.first::<crate::material::RenderInkFeatures>();
assert!(
paints_rect_then_circle(tester, blue, ink_rect, green),
"{:?}",
tester.ink_calls()
);
let widget = m2_ink_frame(tester, Some(red));
tester.pump_widget(widget);
assert_eq!(tester.first::<crate::material::RenderInkFeatures>(), box_);
assert!(
paints_rect_then_circle(tester, red, ink_rect, green),
"{:?}",
tester.ink_calls()
);
let widget = m2_ink_frame(tester, None);
tester.pump_widget(widget);
assert_eq!(tester.first::<crate::material::RenderInkFeatures>(), box_);
let drawn = tester.ink_calls();
assert!(
!drawn
.iter()
.any(|drawn| matches!(drawn, RecordedCall::Rect { .. }))
);
assert!(!drawn.iter().any(|drawn| path_like(drawn).is_some()));
tester.up(&gesture);
});
}
#[test]
fn ink_with_is_visible_false_does_not_paint() {
test_widgets(|tester| {
let test_color = Color::new(0xffff1234);
let ink_widget = |is_visible: bool| {
Material::new()
.child(
Visibility::maintain(
Ink::new().decoration(BoxDecoration::new().color(test_color)),
)
.visible(is_visible),
)
.into_widget()
};
let has_test_color = |drawn: &[RecordedCall]| {
drawn
.iter()
.any(|drawn| matches!(drawn, RecordedCall::Rect { color, .. } if color.to_argb32() == test_color.to_argb32()))
};
tester.pump_widget(ink_widget(true));
assert!(has_test_color(&tester.ink_calls()));
tester.pump_widget(ink_widget(false));
assert!(!has_test_color(&tester.ink_calls()));
});
}
}