use std::sync::Arc;
use super::{
Accessible, AnyElement, Interactive, IntoReactive,
element::{ElNode, Element, IntoElement, Listener, ParentElement},
events::{self, NativeEvent, Selection, VideoInfo, VideoProgress, WebNavigation},
};
use crate::{
AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, JsonValue, KeyboardAppearance,
KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp, Prop, ResizeMode,
ReturnKeyType, ScreenAnimation, ScreenProp, ScrollProp, Size, SubmitBehavior, Tag, WebSource,
canvas::{
CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp,
},
js::host::HostProps,
};
pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
match (a, b) {
(Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
_ => HostProps::same_kind(a, b),
}
}
pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
match prop {
Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
_ => HostProps::reset(prop),
}
}
pub(crate) fn set(node: &mut ElNode, prop: Prop) {
set_in(&mut node.attrs.props, prop);
}
crate::static_reactive!(Color: Color);
crate::static_reactive!(AutoCapitalize: AutoCapitalize);
crate::static_reactive!(AutoFill: AutoFill);
crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
crate::static_reactive!(KeyboardType: KeyboardType);
crate::static_reactive!(ModalAnimation: ModalAnimation);
crate::static_reactive!(ModalPresentation: ModalPresentation);
crate::static_reactive!(ResizeMode: ResizeMode);
crate::static_reactive!(ReturnKeyType: ReturnKeyType);
crate::static_reactive!(SubmitBehavior: SubmitBehavior);
fn set_in(props: &mut Vec<Prop>, prop: Prop) {
match props.iter_mut().find(|p| same_kind(p, &prop)) {
Some(p) => *p = prop,
None => props.push(prop),
}
}
pub(crate) fn bind_prop<T: 'static>(
node: &mut ElNode,
value: impl IntoReactive<T>,
prop: impl Fn(T) -> Prop + 'static,
) {
node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
}
fn listen<T: ?Sized + ToOwned + 'static>(
node: &mut ElNode,
kind: EventKind,
listener: Listener<T>,
decode: events::Decode<T>,
) {
node.handlers.push((kind, events::typed(listener, decode)));
}
macro_rules! host_element {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone)]
pub struct $name(ElNode);
impl Element for $name {
fn node(&mut self) -> &mut ElNode {
&mut self.0
}
}
impl IntoElement for $name {
fn into_element(self) -> AnyElement {
AnyElement(self.0)
}
}
impl Accessible for $name {}
impl Interactive for $name {}
#[allow(dead_code)]
impl $name {
fn set(mut self, prop: Prop) -> Self {
set(&mut self.0, prop);
self
}
fn bind_prop<T: 'static>(
mut self,
value: impl IntoReactive<T>,
prop: impl Fn(T) -> Prop + 'static,
) -> Self {
bind_prop(&mut self.0, value, prop);
self
}
fn listen<T: ?Sized + ToOwned + 'static>(
mut self,
kind: EventKind,
listener: Listener<T>,
decode: events::Decode<T>,
) -> Self {
listen(&mut self.0, kind, listener, decode);
self
}
}
};
}
host_element! {
Input
}
host_element! {
Scroll
}
host_element! {
Stack
}
host_element! {
Screen
}
host_element! {
Modal
}
host_element! {
InputAccessoryView
}
host_element! {
CanvasView
}
host_element! {
WebView
}
host_element! {
Video
}
host_element! {
NativeView
}
impl ParentElement for Scroll {}
impl ParentElement for Stack {}
impl ParentElement for Screen {}
impl ParentElement for Modal {}
impl ParentElement for InputAccessoryView {
fn child(mut self, child: impl IntoElement) -> Self {
if !cfg!(target_os = "android") {
self.0.children.push(child.into_element().0);
}
self
}
fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
if !cfg!(target_os = "android") {
self.0
.children
.extend(children.into_iter().map(|c| c.into_element().0));
}
self
}
}
pub fn input() -> Input {
Input(ElNode::new(Tag::Input))
}
pub fn scroll() -> Scroll {
Scroll(ElNode::new(Tag::Scroll))
}
pub fn stack() -> Stack {
Stack(ElNode::new(Tag::Stack))
}
pub fn screen() -> Screen {
let mut node = ElNode::new(Tag::Screen);
node.handlers.push((EventKind::Insets, Listener::noop()));
Screen(node)
}
pub fn modal() -> Modal {
let mut node = ElNode::new(Tag::Modal);
node.handlers.push((EventKind::Insets, Listener::noop()));
Modal(node)
}
pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
let tag = if cfg!(target_os = "android") {
Tag::View
} else {
Tag::InputAccessory
};
let mut node = ElNode::new(tag);
if cfg!(target_os = "android") {
node.style.keyword(crate::StyleKey::Display, "none");
} else {
set(&mut node, Prop::NativeId(Some(native_id.into())));
}
InputAccessoryView(node)
}
pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
let mut node = ElNode::new(Tag::Canvas);
node.bind_attr(painter, |attrs, painter: Painter| {
attrs.drawing = Some(Arc::new(painter.drawing));
attrs.bound = painter.nodes;
});
CanvasView(node)
}
crate::static_reactive!(Painter: Painter, Drawing);
pub fn web_view(url: &str) -> WebView {
WebView(ElNode::new(Tag::WebView))
.set(Prop::Native(NativeProp::Source(WebSource::Uri(url.into()))))
}
pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
WebView(ElNode::new(Tag::WebView)).html(html, base_url)
}
pub fn video(url: &str) -> Video {
Video(ElNode::new(Tag::Video)).set(Prop::Native(NativeProp::Source(WebSource::Uri(url.into()))))
}
pub fn native(name: &str) -> NativeView {
NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
}
impl Input {
pub fn value(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::Value(text))
}
pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::DefaultValue(text))
}
pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::Placeholder(text))
}
pub fn placeholder_color(self, color: impl IntoReactive<Color>) -> Self {
self.bind_prop(color, |color: Color| Prop::PlaceholderColor(Some(color)))
}
pub fn selection_color(self, color: impl IntoReactive<Color>) -> Self {
self.bind_prop(color, |color: Color| Prop::SelectionColor(Some(color)))
}
pub fn secure(self, secure: impl IntoReactive<bool>) -> Self {
self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
}
pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
}
pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
self.bind_prop(appearance, |appearance: KeyboardAppearance| {
Prop::KeyboardAppearance(appearance)
})
}
pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
}
pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
}
pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
}
pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
}
pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
}
pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
}
pub fn editable(self, editable: impl IntoReactive<bool>) -> Self {
self.bind_prop(editable, |editable: bool| Prop::Editable(editable))
}
pub fn blur_on_submit(self, blur: impl IntoReactive<bool>) -> Self {
self.bind_prop(blur, |blur: bool| Prop::BlurOnSubmit(blur))
}
pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
self.bind_prop(behavior, |behavior: SubmitBehavior| {
Prop::SubmitBehavior(Some(behavior))
})
}
pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
}
pub fn caret_hidden(self, hidden: impl IntoReactive<bool>) -> Self {
self.bind_prop(hidden, |hidden: bool| Prop::CaretHidden(hidden))
}
pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
self.bind_prop(native_id, |id: String| {
Prop::InputAccessoryViewId(Some(id.into()))
})
}
pub fn selection(self, range: impl IntoReactive<(u32, u32)>) -> Self {
self.bind_prop(range, |(start, end): (u32, u32)| {
Prop::Selection(start, end)
})
}
pub fn on_change_text(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::ChangeText, listener.into(), events::text)
}
pub fn on_submit_editing(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::SubmitEditing, listener.into(), events::text)
}
pub fn on_focus(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::Focus, listener.into(), events::unit)
}
pub fn on_blur(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::Blur, listener.into(), events::unit)
}
pub fn on_selection_change(self, listener: impl Into<Listener<Selection>>) -> Self {
self.listen(
EventKind::SelectionChange,
listener.into(),
events::selection,
)
}
pub fn on_key_press(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::KeyPress, listener.into(), events::key)
}
pub fn on_content_size_change(self, listener: impl Into<Listener<Size>>) -> Self {
self.listen(EventKind::ContentSizeChange, listener.into(), events::size)
}
}
impl Scroll {
pub fn horizontal(self) -> Self {
self.set(Prop::Horizontal(true))
}
pub fn shows_indicator(self, shows: impl IntoReactive<bool>) -> Self {
self.bind_prop(shows, |shows: bool| Prop::ShowsIndicator(shows))
}
pub fn zoom_range(self, min: f32, max: f32) -> Self {
self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
.set(Prop::Scroll(ScrollProp::MaxZoom(max)))
}
pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
}
pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
self.bind_prop(bounces, |bounces: bool| {
Prop::Scroll(ScrollProp::BouncesZoom(bounces))
})
}
pub fn pinch_gesture_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Scroll(ScrollProp::Pinch(enabled))
})
}
pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
self.bind_prop(center, |center: bool| {
Prop::Scroll(ScrollProp::CenterContent(center))
})
}
}
impl super::Scrollable for Scroll {}
impl Screen {
fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
let mut node = ElNode::new(Tag::HeaderItem);
node.key = Some(key.into());
set(&mut node, Prop::HeaderSlot(slot));
node.children.push(item.into_element().0);
self.0.children.push(node);
self
}
pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(title, |t| {
Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
})
}
pub fn header_shown(self, shown: impl IntoReactive<bool>) -> Self {
self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderShown(v)))
}
pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
}
pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
self.bind_prop(transparent, |v| {
Prop::Screen(ScreenProp::HeaderTransparent(v))
})
}
pub fn header_tint_color(self, color: impl IntoReactive<Color>) -> Self {
self.bind_prop(color, |c| {
Prop::Screen(ScreenProp::HeaderTintColor(Some(c)))
})
}
pub fn header_background_color(self, color: impl IntoReactive<Color>) -> Self {
self.bind_prop(color, |c| {
Prop::Screen(ScreenProp::HeaderBackgroundColor(Some(c)))
})
}
pub fn header_title_color(self, color: impl IntoReactive<Color>) -> Self {
self.bind_prop(color, |c| {
Prop::Screen(ScreenProp::HeaderTitleColor(Some(c)))
})
}
pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(title, |t| {
Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
})
}
pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
}
pub fn gesture_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::GestureEnabled(v)))
}
pub fn prevent_back(self, prevent: impl IntoReactive<bool>) -> Self {
self.bind_prop(prevent, |v| Prop::Screen(ScreenProp::PreventBack(v)))
}
pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
}
pub fn header_left(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Left, "header-left", item)
}
pub fn header_right(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Right, "header-right", item)
}
pub fn header_title(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Title, "header-title", item)
}
pub fn on_dismiss(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::Dismiss, listener.into(), events::unit)
}
pub fn on_back_request(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::BackRequest, listener.into(), events::unit)
}
}
impl Modal {
pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
self.bind_prop(animation, |animation: ModalAnimation| {
Prop::Modal(ModalProp::Animation(animation))
})
}
pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
self.bind_prop(presentation, |presentation: ModalPresentation| {
Prop::Modal(ModalProp::Presentation(presentation))
})
}
pub fn transparent(self, transparent: impl IntoReactive<bool>) -> Self {
self.bind_prop(transparent, |transparent: bool| {
Prop::Modal(ModalProp::Transparent(transparent))
})
}
pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
self.bind_prop(translucent, |translucent: bool| {
Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
})
}
pub fn supported_orientations(
self,
orientations: impl IntoIterator<Item = Orientation>,
) -> Self {
let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
self.set(Prop::Modal(ModalProp::Orientations(bits)))
}
pub fn dismissible(self, dismissible: impl IntoReactive<bool>) -> Self {
self.bind_prop(dismissible, |dismissible: bool| {
Prop::Modal(ModalProp::Dismissible(dismissible))
})
}
pub fn on_request_close(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::RequestClose, listener.into(), events::unit)
}
pub fn on_show(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::Show, listener.into(), events::unit)
}
pub fn on_dismiss(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::Dismiss, listener.into(), events::unit)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
Portrait,
PortraitUpsideDown,
Landscape,
LandscapeLeft,
LandscapeRight,
}
impl Orientation {
fn bits(self) -> u8 {
use crate::ModalConfig as M;
match self {
Orientation::Portrait => M::PORTRAIT,
Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
}
}
}
impl WebView {
pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
let base_url: Option<Arc<str>> = base_url.map(Into::into);
self.bind_prop(html, move |html: String| {
Prop::Native(NativeProp::Source(WebSource::Html {
html: html.into(),
base_url: base_url.clone(),
}))
})
}
pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
self.bind_prop(script, |script: String| {
Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
})
}
pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
self.bind_prop(script, |script: String| {
Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
})
}
pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
self.bind_prop(agent, |agent: String| {
Prop::Native(NativeProp::UserAgent(Some(agent.into())))
})
}
pub fn scroll_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::ScrollEnabled(enabled))
})
}
pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::JavaScriptEnabled(enabled))
})
}
pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::BackForwardGestures(enabled))
})
}
pub fn on_load_start(self, listener: impl Into<Listener<WebNavigation>>) -> Self {
self.listen(EventKind::LoadStart, listener.into(), events::navigation)
}
pub fn on_load(self, listener: impl Into<Listener<WebNavigation>>) -> Self {
self.listen(EventKind::Load, listener.into(), events::navigation)
}
pub fn on_error(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::Error, listener.into(), events::message)
}
pub fn on_message(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::Message, listener.into(), events::data)
}
pub fn on_navigation_state_change(self, listener: impl Into<Listener<WebNavigation>>) -> Self {
self.listen(
EventKind::NavigationStateChange,
listener.into(),
events::navigation,
)
}
}
impl Video {
pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
self.bind_prop(paused, |paused: bool| {
Prop::Native(NativeProp::Paused(paused))
})
}
pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
}
pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
self.bind_prop(volume, |volume: f32| {
Prop::Native(NativeProp::Volume(volume))
})
}
pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
}
pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
self.bind_prop(repeat, |repeat: bool| {
Prop::Native(NativeProp::Repeat(repeat))
})
}
pub fn resize_mode(self, mode: impl IntoReactive<ResizeMode>) -> Self {
self.bind_prop(mode, |mode: ResizeMode| {
Prop::Native(NativeProp::VideoResizeMode(mode))
})
}
pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
self.bind_prop(controls, |controls: bool| {
Prop::Native(NativeProp::Controls(controls))
})
}
pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
}
pub fn on_load_start(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::LoadStart, listener.into(), events::unit)
}
pub fn on_load(self, listener: impl Into<Listener<VideoInfo>>) -> Self {
self.listen(EventKind::Load, listener.into(), events::video)
}
pub fn on_progress(self, listener: impl Into<Listener<VideoProgress>>) -> Self {
self.listen(EventKind::Progress, listener.into(), events::progress)
}
pub fn on_end(self, listener: impl Into<Listener<()>>) -> Self {
self.listen(EventKind::End, listener.into(), events::unit)
}
pub fn on_buffer(self, listener: impl Into<Listener<bool>>) -> Self {
self.listen(EventKind::Buffer, listener.into(), events::buffering)
}
pub fn on_error(self, listener: impl Into<Listener<str>>) -> Self {
self.listen(EventKind::Error, listener.into(), events::message)
}
}
impl NativeView {
pub fn prop(self, name: &str, value: JsonValue) -> Self {
self.set(Prop::ComponentProp(name.into(), Some(value)))
}
pub fn on_native_event(self, listener: impl Into<Listener<NativeEvent>>) -> Self {
self.listen(EventKind::NativeEvent, listener.into(), events::native)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasArg(pub(crate) CanvasArgKind);
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CanvasArgKind {
Const(f32),
Node(super::NativeNode),
}
impl From<f32> for CanvasArg {
fn from(n: f32) -> Self {
Self(CanvasArgKind::Const(n))
}
}
impl<A: super::Animated> From<&A> for CanvasArg {
fn from(a: &A) -> Self {
Self(CanvasArgKind::Node(a.native_node()))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasPaint(CanvasPaintKind);
#[derive(Debug, Clone, PartialEq)]
enum CanvasPaintKind {
Color(Color),
Gradient(Arc<CanvasGradient>),
Node(super::NativeNode),
}
impl From<Color> for CanvasPaint {
fn from(color: Color) -> Self {
Self(CanvasPaintKind::Color(color))
}
}
impl From<CanvasGradient> for CanvasPaint {
fn from(gradient: CanvasGradient) -> Self {
Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
}
}
impl From<Arc<CanvasGradient>> for CanvasPaint {
fn from(gradient: Arc<CanvasGradient>) -> Self {
Self(CanvasPaintKind::Gradient(gradient))
}
}
impl<A: super::Animated> From<&A> for CanvasPaint {
fn from(a: &A) -> Self {
Self(CanvasPaintKind::Node(a.native_node()))
}
}
#[derive(Debug, Clone, Default)]
pub struct Painter {
drawing: Drawing,
nodes: Vec<super::NativeNode>,
}
impl Painter {
pub fn new() -> Self {
Self::default()
}
pub fn finish(self) -> Drawing {
self.drawing
}
pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
match value.into().0 {
CanvasArgKind::Const(n) => Num::Const(n),
CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
}
}
pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
match paint.into().0 {
CanvasPaintKind::Color(color) => Paint::Color(color),
CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
}
}
fn slot(&mut self, node: super::NativeNode) -> u16 {
let slot = self.drawing.slot(node.id());
self.nodes.push(node);
slot
}
pub fn op(mut self, op: CanvasOp) -> Self {
self.drawing.ops.push(op);
self
}
fn path(self, op: PathOp) -> Self {
self.op(CanvasOp::Path(op))
}
pub fn is_point_in_path(&self, x: f32, y: f32, rule: FillRule) -> bool {
crate::canvas::point_in_path(&self.drawing.ops, None, rule, x, y, |_| 0.0)
}
pub fn is_point_in_stroke(&self, x: f32, y: f32) -> bool {
crate::canvas::point_in_stroke(&self.drawing.ops, None, x, y, |_| 0.0)
}
pub fn path_contains(&self, path: &Path, x: f32, y: f32, rule: FillRule) -> bool {
crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, x, y, |_| 0.0)
}
pub fn stroke_contains(&self, path: &Path, x: f32, y: f32) -> bool {
crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), x, y, |_| 0.0)
}
pub fn save(self) -> Self {
self.op(CanvasOp::Save)
}
pub fn restore(self) -> Self {
self.op(CanvasOp::Restore)
}
pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.op(CanvasOp::Translate(x, y))
}
pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.op(CanvasOp::Scale(x, y))
}
pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
let a = self.num(angle);
self.op(CanvasOp::Rotate(a))
}
pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
let m = m.map(|n| self.num(n));
self.op(CanvasOp::Transform(m))
}
pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
let m = m.map(|n| self.num(n));
self.op(CanvasOp::SetTransform(m))
}
pub fn reset_transform(self) -> Self {
self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
}
pub fn begin_path(self) -> Self {
self.op(CanvasOp::BeginPath)
}
pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.path(PathOp::MoveTo(x, y))
}
pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.path(PathOp::LineTo(x, y))
}
pub fn quadratic_curve_to(self, control: (f32, f32), to: (f32, f32)) -> Self {
let c = Num::Const;
self.path(PathOp::QuadTo([
c(control.0),
c(control.1),
c(to.0),
c(to.1),
]))
}
pub fn bezier_curve_to(self, c1: (f32, f32), c2: (f32, f32), to: (f32, f32)) -> Self {
let c = Num::Const;
self.path(PathOp::CubicTo([
c(c1.0),
c(c1.1),
c(c2.0),
c(c2.1),
c(to.0),
c(to.1),
]))
}
pub fn arc(
self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
) -> Self {
self.arc_in(x, y, radius, start, end, false)
}
pub fn arc_counterclockwise(
self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
) -> Self {
self.arc_in(x, y, radius, start, end, true)
}
fn arc_in(
mut self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
ccw: bool,
) -> Self {
let (x, y, radius, start, end) = (
self.num(x),
self.num(y),
self.num(radius),
self.num(start),
self.num(end),
);
self.path(PathOp::Arc {
x,
y,
radius,
start,
end,
ccw,
})
}
pub fn arc_to(self, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32) -> Self {
let c = Num::Const;
self.path(PathOp::ArcTo([c(x1), c(y1), c(x2), c(y2), c(radius)]))
}
#[allow(clippy::too_many_arguments)]
pub fn ellipse(
self,
x: f32,
y: f32,
radius: (f32, f32),
rotation: f32,
start: f32,
end: f32,
counterclockwise: bool,
) -> Self {
let c = Num::Const;
self.path(PathOp::Ellipse {
geometry: [c(x), c(y), c(radius.0), c(radius.1), c(rotation)],
start: c(start),
end: c(end),
ccw: counterclockwise,
})
}
pub fn rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
let c = Num::Const;
self.path(PathOp::Rect([c(x), c(y), c(w), c(h)]))
}
pub fn round_rect(self, x: f32, y: f32, w: f32, h: f32, radius: f32) -> Self {
self.round_rect_corners(x, y, w, h, [radius; 4])
}
pub fn round_rect_corners(self, x: f32, y: f32, w: f32, h: f32, radii: [f32; 4]) -> Self {
let c = Num::Const;
self.path(PathOp::RoundRect([c(x), c(y), c(w), c(h)], radii.map(c)))
}
pub fn close_path(self) -> Self {
self.path(PathOp::Close)
}
pub fn fill(self) -> Self {
self.fill_with(FillRule::NonZero)
}
pub fn fill_with(self, rule: FillRule) -> Self {
self.op(CanvasOp::Fill(None, rule))
}
pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
self.op(CanvasOp::Fill(Some(path.clone()), rule))
}
pub fn fill_svg(self, data: &str) -> Self {
self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
}
pub fn stroke(self) -> Self {
self.op(CanvasOp::Stroke(None))
}
pub fn stroke_path(self, path: &Path) -> Self {
self.op(CanvasOp::Stroke(Some(path.clone())))
}
pub fn stroke_svg(self, data: &str) -> Self {
self.stroke_path(&crate::canvas::svg_path(data))
}
pub fn clip(self) -> Self {
self.clip_with(FillRule::NonZero)
}
pub fn clip_with(self, rule: FillRule) -> Self {
self.op(CanvasOp::Clip(None, rule))
}
pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
self.op(CanvasOp::Clip(Some(path.clone()), rule))
}
pub fn fill_rect(
mut self,
x: f32,
y: f32,
w: impl Into<CanvasArg>,
h: impl Into<CanvasArg>,
) -> Self {
let (w, h) = (self.num(w), self.num(h));
self.op(CanvasOp::FillRect([Num::Const(x), Num::Const(y), w, h]))
}
pub fn stroke_rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
let c = Num::Const;
self.op(CanvasOp::StrokeRect([c(x), c(y), c(w), c(h)]))
}
pub fn clear_rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
let c = Num::Const;
self.op(CanvasOp::ClearRect([c(x), c(y), c(w), c(h)]))
}
pub fn fill_color(self, color: Color) -> Self {
self.fill_style(color)
}
pub fn stroke_color(self, color: Color) -> Self {
self.stroke_style(color)
}
pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
let paint = self.paint(paint);
self.op(CanvasOp::FillStyle(paint))
}
pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
let paint = self.paint(paint);
self.op(CanvasOp::StrokeStyle(paint))
}
pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
let w = self.num(width);
self.op(CanvasOp::LineWidth(w))
}
pub fn line_cap(self, cap: LineCap) -> Self {
self.op(CanvasOp::LineCap(cap))
}
pub fn line_join(self, join: LineJoin) -> Self {
self.op(CanvasOp::LineJoin(join))
}
pub fn miter_limit(self, limit: f32) -> Self {
self.op(CanvasOp::MiterLimit(limit.max(1.0)))
}
pub fn line_dash(self, segments: &[f32]) -> Self {
self.op(CanvasOp::LineDash(segments.into()))
}
pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
let o = self.num(offset);
self.op(CanvasOp::LineDashOffset(o))
}
pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
let a = self.num(alpha);
self.op(CanvasOp::GlobalAlpha(a))
}
pub fn composite(self, composite: Composite) -> Self {
self.op(CanvasOp::Composite(composite))
}
pub fn shadow(self, color: Color, blur: f32, offset: (f32, f32)) -> Self {
self.op(CanvasOp::ShadowColor(color))
.op(CanvasOp::ShadowBlur(blur.max(0.0)))
.op(CanvasOp::ShadowOffset(offset.0, offset.1))
}
pub fn font(self, font: &str) -> Self {
match CanvasFont::parse(font) {
Some(font) => self.op(CanvasOp::Font(font)),
None => self,
}
}
pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
)))
}
pub fn text_align(self, align: CanvasTextAlign) -> Self {
self.op(CanvasOp::TextAlign(align))
}
pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
self.op(CanvasOp::TextBaseline(baseline))
}
pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
self.text(text, x, y, None, false)
}
pub fn fill_text_max_width(
self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: f32,
) -> Self {
self.text(text, x, y, Some(max_width), false)
}
pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
self.text(text, x, y, None, true)
}
pub fn stroke_text_max_width(
self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: f32,
) -> Self {
self.text(text, x, y, Some(max_width), true)
}
fn text(
mut self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: Option<f32>,
stroke: bool,
) -> Self {
let (text, x, y) = (text.into(), self.num(x), self.num(y));
self.op(if stroke {
CanvasOp::StrokeText {
text,
x,
y,
max_width,
}
} else {
CanvasOp::FillText {
text,
x,
y,
max_width,
}
})
}
pub fn draw_image(self, uri: &str, x: f32, y: f32, w: f32, h: f32) -> Self {
self.draw_image_part(uri, None, [x, y, w, h])
}
pub fn draw_image_part(self, uri: &str, source: Option<[f32; 4]>, dest: [f32; 4]) -> Self {
self.op(CanvasOp::DrawImage {
image: CanvasImage { uri: uri.into() },
source,
dest: dest.map(Num::Const),
})
}
}
impl From<Drawing> for Painter {
fn from(drawing: Drawing) -> Self {
Self {
drawing,
nodes: Vec::new(),
}
}
}
crate::static_reactive!(ScreenAnimation: ScreenAnimation);