use std::sync::Arc;
use super::{
Accessible, AnyElement, Interactive,
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) {
let props = &mut node.attrs.props;
match props.iter_mut().find(|p| same_kind(p, &prop)) {
Some(p) => *p = prop,
None => props.push(prop),
}
}
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 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 Into<Painter>) -> CanvasView {
let painter = painter.into();
let mut node = ElNode::new(Tag::Canvas);
node.attrs.drawing = Some(Arc::new(painter.drawing));
node.attrs.bound = painter.nodes;
CanvasView(node)
}
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: &str, 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 Into<String>) -> Self {
self.set(Prop::Value(text.into()))
}
pub fn default_value(self, text: impl Into<String>) -> Self {
self.set(Prop::DefaultValue(text.into()))
}
pub fn placeholder(self, text: impl Into<String>) -> Self {
self.set(Prop::Placeholder(text.into()))
}
pub fn placeholder_color(self, color: Color) -> Self {
self.set(Prop::PlaceholderColor(Some(color)))
}
pub fn selection_color(self, color: Color) -> Self {
self.set(Prop::SelectionColor(Some(color)))
}
pub fn secure(self, secure: bool) -> Self {
self.set(Prop::Secure(secure))
}
pub fn keyboard_type(self, kind: KeyboardType) -> Self {
self.set(Prop::KeyboardType(kind))
}
pub fn keyboard_appearance(self, appearance: KeyboardAppearance) -> Self {
self.set(Prop::KeyboardAppearance(appearance))
}
pub fn return_key_type(self, kind: ReturnKeyType) -> Self {
self.set(Prop::ReturnKeyType(kind))
}
pub fn auto_capitalize(self, mode: AutoCapitalize) -> Self {
self.set(Prop::AutoCapitalize(mode))
}
pub fn auto_correct(self, on: bool) -> Self {
self.set(Prop::AutoCorrect(on))
}
pub fn auto_fill(self, kind: AutoFill) -> Self {
self.set(Prop::AutoFill(kind))
}
pub fn multiline(self, multiline: bool) -> Self {
self.set(Prop::Multiline(multiline))
}
pub fn max_length(self, length: u32) -> Self {
self.set(Prop::MaxLength(Some(length)))
}
pub fn editable(self, editable: bool) -> Self {
self.set(Prop::Editable(editable))
}
pub fn blur_on_submit(self, blur: bool) -> Self {
self.set(Prop::BlurOnSubmit(blur))
}
pub fn submit_behavior(self, behavior: SubmitBehavior) -> Self {
self.set(Prop::SubmitBehavior(Some(behavior)))
}
pub fn auto_focus(self, focus: bool) -> Self {
self.set(Prop::AutoFocus(focus))
}
pub fn caret_hidden(self, hidden: bool) -> Self {
self.set(Prop::CaretHidden(hidden))
}
pub fn input_accessory(self, native_id: &str) -> Self {
self.set(Prop::InputAccessoryViewId(Some(native_id.into())))
}
pub fn selection(self, start: u32, end: u32) -> Self {
self.set(Prop::Selection(start, end))
}
pub fn on_change_text(self, listener: Listener<str>) -> Self {
self.listen(EventKind::ChangeText, listener, events::text)
}
pub fn on_submit_editing(self, listener: Listener<str>) -> Self {
self.listen(EventKind::SubmitEditing, listener, events::text)
}
pub fn on_focus(self, listener: Listener<()>) -> Self {
self.listen(EventKind::Focus, listener, events::unit)
}
pub fn on_blur(self, listener: Listener<()>) -> Self {
self.listen(EventKind::Blur, listener, events::unit)
}
pub fn on_selection_change(self, listener: Listener<Selection>) -> Self {
self.listen(EventKind::SelectionChange, listener, events::selection)
}
pub fn on_key_press(self, listener: Listener<str>) -> Self {
self.listen(EventKind::KeyPress, listener, events::key)
}
pub fn on_content_size_change(self, listener: Listener<Size>) -> Self {
self.listen(EventKind::ContentSizeChange, listener, events::size)
}
}
impl Scroll {
pub fn horizontal(self) -> Self {
self.set(Prop::Horizontal(true))
}
pub fn shows_indicator(self, shows: bool) -> Self {
self.set(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: f32) -> Self {
self.set(Prop::Scroll(ScrollProp::Zoom(scale)))
}
pub fn bounces_zoom(self, bounces: bool) -> Self {
self.set(Prop::Scroll(ScrollProp::BouncesZoom(bounces)))
}
pub fn pinch_gesture_enabled(self, enabled: bool) -> Self {
self.set(Prop::Scroll(ScrollProp::Pinch(enabled)))
}
pub fn center_content(self, center: bool) -> Self {
self.set(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
}
fn screen(self, prop: ScreenProp) -> Self {
self.set(Prop::Screen(prop))
}
pub fn title(self, title: impl Into<Arc<str>>) -> Self {
self.screen(ScreenProp::Title(Some(title.into())))
}
pub fn header_shown(self, shown: bool) -> Self {
self.screen(ScreenProp::HeaderShown(shown))
}
pub fn header_large_title(self, large: bool) -> Self {
self.screen(ScreenProp::HeaderLargeTitle(large))
}
pub fn header_transparent(self, transparent: bool) -> Self {
self.screen(ScreenProp::HeaderTransparent(transparent))
}
pub fn header_tint_color(self, color: impl Into<Color>) -> Self {
self.screen(ScreenProp::HeaderTintColor(Some(color.into())))
}
pub fn header_background_color(self, color: impl Into<Color>) -> Self {
self.screen(ScreenProp::HeaderBackgroundColor(Some(color.into())))
}
pub fn header_title_color(self, color: impl Into<Color>) -> Self {
self.screen(ScreenProp::HeaderTitleColor(Some(color.into())))
}
pub fn header_back_title(self, title: impl Into<Arc<str>>) -> Self {
self.screen(ScreenProp::HeaderBackTitle(Some(title.into())))
}
pub fn header_back_visible(self, visible: bool) -> Self {
self.screen(ScreenProp::HeaderBackVisible(visible))
}
pub fn gesture_enabled(self, enabled: bool) -> Self {
self.screen(ScreenProp::GestureEnabled(enabled))
}
pub fn prevent_back(self, prevent: bool) -> Self {
self.screen(ScreenProp::PreventBack(prevent))
}
pub fn animation(self, animation: ScreenAnimation) -> Self {
self.screen(ScreenProp::Animation(animation))
}
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: Listener<()>) -> Self {
self.listen(EventKind::Dismiss, listener, events::unit)
}
pub fn on_back_request(self, listener: Listener<()>) -> Self {
self.listen(EventKind::BackRequest, listener, events::unit)
}
}
impl Modal {
pub fn animation(self, animation: ModalAnimation) -> Self {
self.set(Prop::Modal(ModalProp::Animation(animation)))
}
pub fn presentation(self, presentation: ModalPresentation) -> Self {
self.set(Prop::Modal(ModalProp::Presentation(presentation)))
}
pub fn transparent(self, transparent: bool) -> Self {
self.set(Prop::Modal(ModalProp::Transparent(transparent)))
}
pub fn status_bar_translucent(self, translucent: bool) -> Self {
self.set(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: bool) -> Self {
self.set(Prop::Modal(ModalProp::Dismissible(dismissible)))
}
pub fn on_request_close(self, listener: Listener<()>) -> Self {
self.listen(EventKind::RequestClose, listener, events::unit)
}
pub fn on_show(self, listener: Listener<()>) -> Self {
self.listen(EventKind::Show, listener, events::unit)
}
pub fn on_dismiss(self, listener: Listener<()>) -> Self {
self.listen(EventKind::Dismiss, listener, 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: &str, base_url: Option<&str>) -> Self {
self.set(Prop::Native(NativeProp::Source(WebSource::Html {
html: html.into(),
base_url: base_url.map(Into::into),
})))
}
pub fn injected_java_script(self, script: &str) -> Self {
self.set(Prop::Native(NativeProp::InjectedJavaScript(Some(
script.into(),
))))
}
pub fn injected_java_script_before_content(self, script: &str) -> Self {
self.set(Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(
script.into(),
))))
}
pub fn user_agent(self, agent: &str) -> Self {
self.set(Prop::Native(NativeProp::UserAgent(Some(agent.into()))))
}
pub fn scroll_enabled(self, enabled: bool) -> Self {
self.set(Prop::Native(NativeProp::ScrollEnabled(enabled)))
}
pub fn java_script_enabled(self, enabled: bool) -> Self {
self.set(Prop::Native(NativeProp::JavaScriptEnabled(enabled)))
}
pub fn back_forward_gestures(self, enabled: bool) -> Self {
self.set(Prop::Native(NativeProp::BackForwardGestures(enabled)))
}
pub fn on_load_start(self, listener: Listener<WebNavigation>) -> Self {
self.listen(EventKind::LoadStart, listener, events::navigation)
}
pub fn on_load(self, listener: Listener<WebNavigation>) -> Self {
self.listen(EventKind::Load, listener, events::navigation)
}
pub fn on_error(self, listener: Listener<str>) -> Self {
self.listen(EventKind::Error, listener, events::message)
}
pub fn on_message(self, listener: Listener<str>) -> Self {
self.listen(EventKind::Message, listener, events::data)
}
pub fn on_navigation_state_change(self, listener: Listener<WebNavigation>) -> Self {
self.listen(
EventKind::NavigationStateChange,
listener,
events::navigation,
)
}
}
impl Video {
pub fn paused(self, paused: bool) -> Self {
self.set(Prop::Native(NativeProp::Paused(paused)))
}
pub fn muted(self, muted: bool) -> Self {
self.set(Prop::Native(NativeProp::Muted(muted)))
}
pub fn volume(self, volume: f32) -> Self {
self.set(Prop::Native(NativeProp::Volume(volume)))
}
pub fn rate(self, rate: f32) -> Self {
self.set(Prop::Native(NativeProp::Rate(rate)))
}
pub fn repeat(self, repeat: bool) -> Self {
self.set(Prop::Native(NativeProp::Repeat(repeat)))
}
pub fn resize_mode(self, mode: ResizeMode) -> Self {
self.set(Prop::Native(NativeProp::VideoResizeMode(mode)))
}
pub fn controls(self, controls: bool) -> Self {
self.set(Prop::Native(NativeProp::Controls(controls)))
}
pub fn progress_interval(self, ms: f32) -> Self {
self.set(Prop::Native(NativeProp::ProgressInterval(ms)))
}
pub fn on_load_start(self, listener: Listener<()>) -> Self {
self.listen(EventKind::LoadStart, listener, events::unit)
}
pub fn on_load(self, listener: Listener<VideoInfo>) -> Self {
self.listen(EventKind::Load, listener, events::video)
}
pub fn on_progress(self, listener: Listener<VideoProgress>) -> Self {
self.listen(EventKind::Progress, listener, events::progress)
}
pub fn on_end(self, listener: Listener<()>) -> Self {
self.listen(EventKind::End, listener, events::unit)
}
pub fn on_buffer(self, listener: Listener<bool>) -> Self {
self.listen(EventKind::Buffer, listener, events::buffering)
}
pub fn on_error(self, listener: Listener<str>) -> Self {
self.listen(EventKind::Error, listener, 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: Listener<NativeEvent>) -> Self {
self.listen(EventKind::NativeEvent, listener, 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(),
}
}
}