1mod advanced;
15mod manager;
16mod tools;
17
18use core::fmt;
19
20use crate::data::{TimeIndex, Timestamp};
21use crate::format::NumberFormat;
22use crate::frame::{
23 DrawCmd, FontId, FontStyleRef, Frame, IconInst, LabelBg, LayerId, LineDash, LineInst, RectInst,
24 StrokeStyle, TextAlign, TextRun,
25};
26use crate::geom::{Css, PointPx, Px, RectPx, Rgba, Span};
27use crate::price_scale::{Normalize, PriceScale};
28use crate::text::{TextMeasurer, text_width};
29use crate::time_scale::TimeScale;
30
31pub(crate) use manager::LocalChange;
32pub use manager::{DrawingFactory, DrawingManager};
33pub const BUILTIN_KINDS: [&str; 29] = [
36 "trend_line",
37 "ray",
38 "extended_line",
39 "horizontal_line",
40 "horizontal_ray",
41 "vertical_line",
42 "parallel_channel",
43 "rectangle",
44 "ellipse",
45 "text",
46 "price_range",
47 "date_range",
48 "fib_retracement",
49 "fib_extension",
50 "long_position",
51 "short_position",
52 "pitchfork",
53 "schiff_pitchfork",
54 "modified_schiff_pitchfork",
55 "gann_fan",
56 "fib_time_zones",
57 "xabcd_pattern",
58 "head_and_shoulders",
59 "elliott_impulse",
60 "elliott_correction",
61 "path",
62 "brush",
63 "arrow",
64 "callout",
65];
66
67pub(crate) fn builtin(data: &DrawingData) -> crate::error::Result<Box<dyn DrawingTool>> {
69 if advanced::SECOND_KINDS.contains(&data.kind.as_str()) {
70 advanced::build(data)
71 } else {
72 tools::builtin(data)
73 }
74}
75
76const DEFAULT_STEP_MS: f64 = 60_000.0;
78pub(crate) const HIT_CSS: f32 = 4.0;
80
81pub const MAX_ANCHORS: usize = 4096;
83
84pub(crate) const FREEHAND_STEP_CSS: f32 = 3.0;
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum AnchorCount {
102 Fixed(usize),
105 Open {
108 min: usize,
110 },
111 Freehand,
114}
115
116impl AnchorCount {
117 pub fn min(self) -> usize {
119 match self {
120 Self::Fixed(n) | Self::Open { min: n } => n,
121 Self::Freehand => 2,
122 }
123 }
124
125 pub(crate) fn max(self) -> usize {
127 match self {
128 Self::Fixed(n) => n,
129 Self::Open { .. } | Self::Freehand => MAX_ANCHORS,
130 }
131 }
132}
133
134#[derive(Clone, Copy, Debug, PartialEq)]
136#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
137pub struct Anchor {
138 pub time: Timestamp,
140 pub price: f64,
142}
143
144#[derive(Clone, Copy, Debug, PartialEq)]
146#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
147pub struct DrawingStyle {
148 pub line: Rgba,
150 pub line_width: Css,
152 pub line_dash: LineDash,
154 pub fill: Rgba,
156 pub text: Rgba,
158 pub font_size: Css,
160}
161
162impl Default for DrawingStyle {
163 fn default() -> Self {
164 let blue = Rgba::hex(0x0029_62FF);
165 Self {
166 line: blue,
167 line_width: Css(1.0),
168 line_dash: LineDash::Solid,
169 fill: blue.with_alpha(40),
170 text: blue,
171 font_size: Css(12.0),
172 }
173 }
174}
175
176#[derive(Clone, Debug, PartialEq)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
179pub enum Param {
180 Number(f64),
182 Bool(bool),
184 Text(String),
186 Numbers(Vec<f64>),
188}
189
190#[derive(Clone, Debug, PartialEq)]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
204pub struct DrawingData {
205 pub kind: String,
207 pub anchors: Vec<Anchor>,
209 pub style: DrawingStyle,
211 pub params: Vec<(String, Param)>,
213}
214
215impl DrawingData {
216 pub fn new(kind: &str, anchors: Vec<Anchor>) -> Self {
218 Self {
219 kind: kind.into(),
220 anchors,
221 style: DrawingStyle::default(),
222 params: Vec::new(),
223 }
224 }
225
226 pub fn param(&self, key: &str) -> Option<&Param> {
228 self.params.iter().find(|(k, _)| k == key).map(|(_, v)| v)
229 }
230
231 pub fn set(&mut self, key: &str, value: Param) {
233 match self.params.iter_mut().find(|(k, _)| k == key) {
234 Some((_, v)) => *v = value,
235 None => self.params.push((key.into(), value)),
236 }
237 }
238
239 pub fn number(&self, key: &str) -> Option<f64> {
241 match self.param(key)? {
242 Param::Number(x) => Some(*x),
243 _ => None,
244 }
245 }
246
247 pub fn text(&self, key: &str) -> Option<&str> {
249 match self.param(key)? {
250 Param::Text(s) => Some(s),
251 _ => None,
252 }
253 }
254
255 pub fn numbers(&self, key: &str) -> Option<&[f64]> {
257 match self.param(key)? {
258 Param::Numbers(v) => Some(v),
259 _ => None,
260 }
261 }
262}
263
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum HitPart {
267 Handle(usize),
269 Body,
271}
272
273pub trait DrawingTool: Send {
280 fn kind(&self) -> &'static str;
282 fn anchors(&self) -> &[Anchor];
284 fn anchors_mut(&mut self) -> &mut Vec<Anchor>;
286 fn anchor_count(&self) -> AnchorCount;
288 fn build(&self, ctx: &DrawingCtx<'_>, out: &mut FrameBuilder<'_>);
290 fn hit_test(&self, ctx: &DrawingCtx<'_>, p: PointPx) -> Option<HitPart>;
293 fn handles(&self, ctx: &DrawingCtx<'_>, out: &mut Vec<PointPx>);
297 fn style(&self) -> &DrawingStyle;
299 fn save(&self) -> DrawingData;
301 fn move_handle(&mut self, handle: usize, to: Anchor) {
303 if let Some(a) = self.anchors_mut().get_mut(handle) {
304 *a = to;
305 }
306 }
307 fn finish(&mut self) {}
311}
312
313pub struct DrawingCtx<'a> {
315 pub(crate) index: &'a TimeIndex,
316 pub(crate) time_scale: &'a TimeScale,
317 pub(crate) price_scale: &'a PriceScale,
318 pub(crate) norm: Normalize,
319 pub(crate) plot: RectPx,
320 pub(crate) dpr: f32,
321 pub(crate) labels: NumberFormat,
322 pub(crate) text: &'a dyn TextMeasurer,
323}
324
325impl DrawingCtx<'_> {
326 pub fn plot(&self) -> RectPx {
328 self.plot
329 }
330
331 pub fn dpr(&self) -> f32 {
333 self.dpr
334 }
335
336 pub fn px(&self, v: Css) -> Px {
338 v.to_px(self.dpr)
339 }
340
341 pub fn hit_tolerance(&self) -> f32 {
343 HIT_CSS * self.dpr
344 }
345
346 pub fn bar_spacing(&self) -> Px {
348 Px(self.time_scale.bar_spacing() as f32)
349 }
350
351 pub fn index_of_time(&self, time: Timestamp) -> Option<f64> {
354 index_of_time(self.index, time)
355 }
356
357 pub(crate) fn x_of_index(&self, i: f64) -> Option<f32> {
359 let x = f64::from(self.plot.x) + self.time_scale.index_to_x_f64(i);
360 x.is_finite().then_some(x.clamp(-1e7, 1e7) as f32)
361 }
362
363 pub fn x_of(&self, time: Timestamp) -> Option<f32> {
365 let i = self.index_of_time(time)?;
366 let x = f64::from(self.plot.x) + self.time_scale.index_to_x_f64(i);
367 x.is_finite().then_some(x as f32)
368 }
369
370 pub fn y_of(&self, price: f64) -> Option<f32> {
372 let (top, h) = (f64::from(self.plot.y), f64::from(self.plot.h));
373 let y = self.price_scale.price_to_y(self.norm.apply(price), top, h);
374 y.is_finite().then_some(y.clamp(-1e7, 1e7) as f32)
376 }
377
378 pub fn price_at(&self, y: f32) -> f64 {
380 let (top, h) = (f64::from(self.plot.y), f64::from(self.plot.h));
381 self.norm
382 .invert(self.price_scale.y_to_price(f64::from(y), top, h))
383 }
384
385 pub fn time_at(&self, x: f32) -> Option<Timestamp> {
435 let i = self.time_scale.x_to_index(Px(x - self.plot.x));
436 time_of_index(self.index, i)
437 }
438
439 pub fn point(&self, a: Anchor) -> Option<PointPx> {
441 Some(PointPx {
442 x: self.x_of(a.time)?.clamp(-1e7, 1e7),
443 y: self.y_of(a.price)?,
444 })
445 }
446
447 pub fn stroke(&self, style: &DrawingStyle) -> StrokeStyle {
449 StrokeStyle {
450 width: Px(style.line_width.to_px(self.dpr).0.round().max(1.0)),
451 color: style.line,
452 dash: style.line_dash,
453 }
454 }
455
456 pub fn font(&self, size: Css) -> FontStyleRef {
458 FontStyleRef {
459 font: FontId(0),
460 size: size.to_px(self.dpr).0,
461 }
462 }
463
464 pub fn text_width(&self, text: &str, font: FontStyleRef) -> f32 {
466 text_width(self.text, text, font)
467 }
468
469 pub fn line_height(&self, font: FontStyleRef) -> f32 {
471 self.text.line_height(font)
472 }
473
474 pub fn write_price(&self, out: &mut impl fmt::Write, price: f64) {
476 match self.labels {
477 f @ (NumberFormat::Fixed(_) | NumberFormat::Auto(_)) => f,
478 NumberFormat::Percent(_) | NumberFormat::Compact => NumberFormat::Fixed(2),
479 }
480 .write(out, price);
481 }
482}
483
484pub struct FrameBuilder<'a> {
487 pub(crate) frame: &'a mut Frame,
488 pub(crate) layer: LayerId,
489}
490
491impl<'a> FrameBuilder<'a> {
492 pub fn new(frame: &'a mut Frame, layer: LayerId) -> Self {
507 Self { frame, layer }
508 }
509
510 pub fn line(&mut self, from: PointPx, to: PointPx, stroke: StrokeStyle) {
512 self.frame
513 .push_line(self.layer, LineInst { from, to, stroke });
514 }
515
516 fn points(&mut self, pts: impl IntoIterator<Item = PointPx>) -> Span {
517 let start = self.frame.pools.points.len();
518 self.frame.pools.points.extend(pts);
519 let len = self.frame.pools.points.len() - start;
520 Span {
521 start: u32::try_from(start).unwrap_or(u32::MAX),
522 len: u32::try_from(len).unwrap_or(0),
523 }
524 }
525
526 pub fn polyline(&mut self, pts: impl IntoIterator<Item = PointPx>, style: StrokeStyle) {
528 let points = self.points(pts);
529 if points.len >= 2 {
530 self.frame
531 .push_cmd(self.layer, DrawCmd::Polyline { points, style });
532 }
533 }
534
535 pub fn polygon(&mut self, pts: impl IntoIterator<Item = PointPx>, fill: Rgba) {
537 let points = self.points(pts);
538 if points.len >= 3 && fill.a > 0 {
539 self.frame
540 .push_cmd(self.layer, DrawCmd::Polygon { points, fill });
541 }
542 }
543
544 pub fn rect(&mut self, rect: RectPx, color: Rgba) {
546 if color.a > 0 && rect.w > 0.0 && rect.h > 0.0 {
547 self.frame.push_rect(self.layer, RectInst { rect, color });
548 }
549 }
550
551 pub fn text(&mut self, pos: PointPx, text: &str, label: Label) {
553 let span = self.frame.push_str(text);
554 self.push_run(pos, span, label);
555 }
556
557 pub fn text_fmt(&mut self, pos: PointPx, args: fmt::Arguments<'_>, label: Label) {
559 let start = self.frame.pools.text.len();
560 let _ = fmt::Write::write_fmt(&mut self.frame.pools.text, args);
561 let len = self.frame.pools.text.len() - start;
562 let span = Span {
563 start: u32::try_from(start).unwrap_or(u32::MAX),
564 len: u32::try_from(len).unwrap_or(0),
565 };
566 self.push_run(pos, span, label);
567 }
568
569 fn push_run(&mut self, pos: PointPx, text: Span, label: Label) {
570 self.frame.push_text(
571 self.layer,
572 TextRun {
573 pos,
574 text,
575 style: label.font,
576 color: label.color,
577 align: label.align,
578 bg: label.bg,
579 },
580 );
581 }
582
583 pub fn icon(&mut self, icon: IconInst) {
585 self.frame.push_icon(self.layer, icon);
586 }
587}
588
589#[derive(Clone, Copy, Debug, PartialEq)]
591pub struct Label {
592 pub font: FontStyleRef,
594 pub color: Rgba,
596 pub align: TextAlign,
598 pub bg: Option<LabelBg>,
600}
601
602pub fn distance_to_segment(p: PointPx, a: PointPx, b: PointPx) -> f32 {
615 let (dx, dy) = (b.x - a.x, b.y - a.y);
616 let len2 = dx * dx + dy * dy;
617 let t = if len2 > 0.0 {
618 (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0)
619 } else {
620 0.0
621 };
622 (p.x - (a.x + t * dx)).hypot(p.y - (a.y + t * dy))
623}
624
625pub fn clip_line(
641 a: PointPx,
642 b: PointPx,
643 rect: RectPx,
644 back: bool,
645 forward: bool,
646) -> Option<(PointPx, PointPx)> {
647 let (dx, dy) = (b.x - a.x, b.y - a.y);
648 if dx == 0.0 && dy == 0.0 {
649 return Some((a, b));
650 }
651 let mut t0 = if back { f32::NEG_INFINITY } else { 0.0 };
652 let mut t1 = if forward { f32::INFINITY } else { 1.0 };
653 for (p, q) in [
655 (-dx, a.x - rect.x),
656 (dx, rect.right() - a.x),
657 (-dy, a.y - rect.y),
658 (dy, rect.bottom() - a.y),
659 ] {
660 if p == 0.0 {
661 if q < 0.0 {
662 return None;
663 }
664 continue;
665 }
666 let r = q / p;
667 if p < 0.0 {
668 t0 = t0.max(r);
669 } else {
670 t1 = t1.min(r);
671 }
672 }
673 if t0 > t1 || !t0.is_finite() || !t1.is_finite() {
674 return None;
675 }
676 let at = |t: f32| PointPx {
677 x: a.x + t * dx,
678 y: a.y + t * dy,
679 };
680 Some((at(t0), at(t1)))
681}
682
683pub fn point_in_polygon(p: PointPx, pts: &[PointPx]) -> bool {
685 let mut inside = false;
686 let mut j = pts.len().wrapping_sub(1);
687 for (i, a) in pts.iter().enumerate() {
688 let Some(b) = pts.get(j) else {
689 return false;
690 };
691 if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
692 inside = !inside;
693 }
694 j = i;
695 }
696 inside
697}
698
699fn step(index: &TimeIndex, at_end: bool) -> f64 {
701 let (first, end) = (index.first_index(), index.end_index());
702 let pair = if at_end {
703 (index.time_at(end - 2), index.time_at(end - 1))
704 } else {
705 (index.time_at(first), index.time_at(first + 1))
706 };
707 match pair {
708 (Some(a), Some(b)) if b > a => (b - a) as f64,
709 _ => DEFAULT_STEP_MS,
710 }
711}
712
713pub(crate) fn index_of_time(index: &TimeIndex, time: Timestamp) -> Option<f64> {
716 if index.is_empty() {
717 return None;
718 }
719 let (first, last) = (index.first_index(), index.end_index() - 1);
720 let (t0, t1) = (index.time_at(first)?, index.time_at(last)?);
721 if time > t1 {
722 return Some(last as f64 + (time - t1) as f64 / step(index, true));
723 }
724 if time < t0 {
725 return Some(first as f64 - (t0 - time) as f64 / step(index, false));
726 }
727 let j = index.lower_bound(time);
728 let tj = index.time_at(j)?;
729 if tj == time {
730 return Some(j as f64);
731 }
732 let tp = index.time_at(j - 1)?;
733 Some((j - 1) as f64 + (time - tp) as f64 / (tj - tp) as f64)
734}
735
736pub(crate) fn time_of_index(index: &TimeIndex, i: f64) -> Option<Timestamp> {
738 if index.is_empty() || !i.is_finite() {
739 return None;
740 }
741 let (first, last) = (index.first_index(), index.end_index() - 1);
742 let (t0, t1) = (index.time_at(first)?, index.time_at(last)?);
743 let t = if i >= last as f64 {
744 t1 as f64 + (i - last as f64) * step(index, true)
745 } else if i <= first as f64 {
746 t0 as f64 - (first as f64 - i) * step(index, false)
747 } else {
748 let j = i.floor() as i64;
749 let (a, b) = (index.time_at(j)?, index.time_at(j + 1)?);
750 a as f64 + (i - j as f64) * (b - a) as f64
751 };
752 Some(t.round().clamp(-9.0e18, 9.0e18) as i64)
753}
754
755pub(crate) fn crisp(v: f32, width: Px) -> f32 {
757 if (width.0 as i32) % 2 == 1 {
758 v.floor() + 0.5
759 } else {
760 v.round()
761 }
762}
763
764#[cfg(test)]
765mod tests {
766 use super::*;
767
768 #[test]
769 fn times_map_to_indices_and_back() {
770 let index = TimeIndex::from_times(vec![100, 200, 400]).unwrap_or_default();
771 assert_eq!(index_of_time(&index, 200), Some(1.0));
772 assert_eq!(index_of_time(&index, 300), Some(1.5));
773 assert_eq!(index_of_time(&index, 800), Some(4.0));
775 assert_eq!(index_of_time(&index, 0), Some(-1.0));
776 for i in [-3.0, -0.5, 0.0, 1.25, 2.0, 7.0] {
777 let t = time_of_index(&index, i).unwrap_or_default();
778 let back = index_of_time(&index, t).unwrap_or_default();
779 assert!((back - i).abs() < 1e-9, "{i} -> {t} -> {back}");
780 }
781 assert_eq!(index_of_time(&TimeIndex::default(), 5), None);
782 }
783
784 #[test]
785 fn lines_are_clipped_to_the_plot() {
786 let r = RectPx {
787 x: 0.0,
788 y: 0.0,
789 w: 100.0,
790 h: 50.0,
791 };
792 let (a, b) = (PointPx { x: 10.0, y: 10.0 }, PointPx { x: 20.0, y: 20.0 });
793 let (p, q) = clip_line(a, b, r, true, true).unwrap_or((a, a));
794 assert_eq!(
795 (p, q),
796 (PointPx { x: 0.0, y: 0.0 }, PointPx { x: 50.0, y: 50.0 })
797 );
798 assert_eq!(clip_line(a, b, r, false, false), Some((a, b)));
799 let outside = PointPx { x: 200.0, y: 10.0 };
800 assert_eq!(
801 clip_line(outside, PointPx { x: 300.0, y: 10.0 }, r, false, true),
802 None
803 );
804 }
805
806 #[test]
807 fn polygons_contain_points() {
808 let sq = [
809 PointPx { x: 0.0, y: 0.0 },
810 PointPx { x: 10.0, y: 0.0 },
811 PointPx { x: 10.0, y: 10.0 },
812 PointPx { x: 0.0, y: 10.0 },
813 ];
814 assert!(point_in_polygon(PointPx { x: 5.0, y: 5.0 }, &sq));
815 assert!(!point_in_polygon(PointPx { x: 15.0, y: 5.0 }, &sq));
816 assert!(!point_in_polygon(PointPx { x: 5.0, y: 5.0 }, &[]));
817 }
818}