Repository navigation
Expand file tree
/
Copy pathprimitives.rs
More file actions
1290 lines (1243 loc) · 50.9 KB
/
Copy pathprimitives.rs
File metadata and controls
1290 lines (1243 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Host primitives attached to series, and custom series drawn by them.
use super::{Chart, ChartElementId, PointerTarget, SeriesId};
use crate::chart::coords::ChartMapping;
use crate::chart::primitives::{
Primitive, PrimitiveHit, PrimitiveId, PrimitivePass, PrimitiveView,
};
use crate::model::Bar;
use crate::studies::Indicator;
use egui::{Painter, Pos2};
use std::sync::{Arc, Mutex, MutexGuard};
/// A primitive and the series it is attached to.
#[derive(Clone)]
pub(super) struct Attached {
pub(super) id: PrimitiveId,
pub(super) series: SeriesId,
/// Shared with image exports, which draw the same primitives.
primitive: Arc<Mutex<dyn Primitive>>,
/// Draws the study `series` in place of its plots.
pub(super) replaces: bool,
/// The series' bars last reported; `None` until `attached` ran.
pub(super) seen: Option<Seen>,
}
/// What identifies the bars of a series: a revision that changes with any bar but the last, the
/// number of bars and the last bar, bitwise.
pub(super) type Seen = (
u64,
usize,
Option<(chrono::DateTime<chrono::Utc>, [u64; 5])>,
);
fn seen(revision: u64, bars: &[Bar]) -> Seen {
let last = bars.last().map(|bar| {
(
bar.time,
[bar.open, bar.high, bar.low, bar.close, bar.volume].map(f64::to_bits),
)
});
(revision, bars.len(), last)
}
impl Attached {
pub(super) fn draw_background(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
factor: usize,
) {
self.get()
.draw_background_merged(painter, view, pass, factor);
}
pub(super) fn draw(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
factor: usize,
) {
self.get().draw_merged(painter, view, pass, factor);
}
pub(super) fn get(&self) -> MutexGuard<'_, dyn Primitive + 'static> {
// A primitive that panicked in a hook keeps the state it had.
self.primitive
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
}
/// A primitive under the pointer and the cursor it asks for.
#[derive(Clone)]
pub(super) struct Hit {
/// The custom series a renderer draws, or the primitive itself.
pub(super) target: PointerTarget,
pub(super) result: PrimitiveHit,
}
impl Chart {
/// Attaches `primitive` to `series`, the main series, an added bar series or a study, to
/// draw in the pane of the series on its price scale from the next [`show`](Self::show); see
/// [`Primitive`]. Several primitives draw in the order they were attached.
///
/// Returns `None`, dropping `primitive`, when `series` is not present.
pub fn attach_primitive(
&mut self,
series: SeriesId,
primitive: impl Primitive + 'static,
) -> Option<PrimitiveId> {
self.attach(series, Arc::new(Mutex::new(primitive)), false)
}
/// Detaches a primitive, calling its [`detached`](Primitive::detached) hook if it was
/// attached in a frame. Returns `false` for an unknown or already detached id.
pub fn detach_primitive(&mut self, id: PrimitiveId) -> bool {
let Some(at) = self.primitives.iter().position(|item| item.id == id) else {
return false;
};
let item = self.primitives.remove(at);
if item.seen.is_some() {
item.get().detached();
}
true
}
/// Adds a series type the host defines, and returns its id. `study` supplies its values,
/// which the legend, the crosshair, the last-value tag and the autoscale of its pane read as
/// for any study, in its own pane unless it is an overlay. `renderer` draws its points in
/// place of the study's plots and hit tests them: a hit selects the series and is reported
/// as [`ChartElementId::Indicator`]. The series is shown, hidden and removed like a study.
pub fn add_custom_series(
&mut self,
study: Box<dyn Indicator>,
renderer: impl Primitive + 'static,
) -> SeriesId {
let id = self.add_indicator(study);
self.attach(id, Arc::new(Mutex::new(renderer)), true);
id
}
fn attach(
&mut self,
series: SeriesId,
primitive: Arc<Mutex<dyn Primitive>>,
replaces: bool,
) -> Option<PrimitiveId> {
self.primitive_source(series)?;
let id = PrimitiveId(self.next_primitive);
self.next_primitive += 1;
self.primitives.push(Attached {
id,
series,
primitive,
replaces,
seen: None,
});
Some(id)
}
/// The bars reported to the primitives of `series` and what identifies them, `None` when the
/// series is not present. Studies follow the main bars they are computed from.
fn primitive_source(&self, series: SeriesId) -> Option<(Seen, &[Bar])> {
let bars = self.state.data().bars.as_slice();
let main = (seen(self.state.revision(), bars), bars);
if series == SeriesId::MAIN {
self.main_series_present.then_some(main)
} else if let Some(item) = self.price_series.iter().find(|item| item.id == series) {
Some((seen(item.revision, &item.bars), &item.bars))
} else {
self.study_ids.contains(&series).then_some(main)
}
}
/// Runs the lifecycle hooks before a frame is drawn: `detached` for the primitives of
/// removed series, `attached` for new ones and `data_changed` when their bars changed.
pub(super) fn sync_primitives(&mut self, ctx: &egui::Context) {
let mut primitives = std::mem::take(&mut self.primitives);
primitives.retain_mut(|item| {
let Some((current, bars)) = self.primitive_source(item.series) else {
if item.seen.is_some() {
item.get().detached();
}
return false;
};
if item.seen != Some(current) {
let mut primitive = item.get();
if item.seen.is_none() {
primitive.attached(ctx, item.series);
}
primitive.data_changed(bars);
drop(primitive);
item.seen = Some(current);
}
true
});
// The hooks have no access to the chart, so no primitive was attached meanwhile.
self.primitives = primitives;
}
/// Marks every primitive as up to date with this chart's bars, so that an image export
/// draws them without running their hooks again.
pub(super) fn settle_primitives(&mut self) {
for at in 0..self.primitives.len() {
let current = self
.primitive_source(self.primitives[at].series)
.map(|(current, _)| current);
self.primitives[at].seen = current;
}
}
pub(super) fn primitive_view(
&self,
series: SeriesId,
mapping: ChartMapping,
) -> PrimitiveView<'_> {
let (start, end) = self.state.visible_range();
PrimitiveView {
series,
study: self
.study_ids
.iter()
.position(|id| *id == series)
.and_then(|idx| self.rendered_studies().indicators().get(idx))
.map(|study| study.as_ref()),
mapping,
bars: self.state.shown(),
visible: start..end,
}
}
/// The view of a primitive drawn in the main pane, from the main pane's mapping. `None`
/// when its series is hidden or a study in a pane of its own.
fn main_view(&self, series: SeriesId, coords: &ChartMapping) -> Option<PrimitiveView<'_>> {
if self.in_pane(series) {
return None;
}
let mapping = if series == SeriesId::MAIN {
self.main_series_visible.then_some(coords.clone())?
} else if let Some(item) = self.price_series.iter().find(|item| item.id == series) {
item.visible.then(|| ChartMapping {
price: self.series_map(item, coords.rect),
..coords.clone()
})?
} else {
let idx = self.study_ids.iter().position(|id| *id == series)?;
let study = self.rendered_studies().indicators().get(idx)?;
(study.is_visible()
&& study.is_overlay()
&& (!study.is_volume()
|| matches!(study.scale(), crate::studies::StudyScale::Shared(_))))
.then(|| crate::chart::rendering::study_mapping(study.as_ref(), coords))?
};
Some(self.primitive_view(series, mapping))
}
/// The primitives drawn in the main pane, with their views.
pub(super) fn main_primitives<'a>(
&'a self,
coords: &'a ChartMapping,
) -> impl DoubleEndedIterator<Item = (&'a Attached, PrimitiveView<'a>)> + Clone {
self.primitives
.iter()
.filter_map(move |item| Some((item, self.main_view(item.series, coords)?)))
}
/// The primitives of every visible series, for the time axis the panes share. Those in a
/// study pane get the main pane's mapping.
pub(super) fn time_axis_primitives<'a>(
&'a self,
coords: &'a ChartMapping,
) -> impl Iterator<Item = (&'a Attached, PrimitiveView<'a>)> {
self.primitives.iter().filter_map(move |item| {
let view = self.main_view(item.series, coords).or_else(|| {
self.is_series_visible(item.series)
.then(|| self.primitive_view(item.series, coords.clone()))
})?;
Some((item, view))
})
}
/// The primitives attached to `series`.
pub(super) fn primitives_of(
&self,
series: SeriesId,
) -> impl DoubleEndedIterator<Item = &Attached> {
self.primitives
.iter()
.filter(move |item| item.series == series)
}
/// The prices the primitives of `series` add to the fit of its scale.
pub(super) fn primitive_prices(&self, series: SeriesId) -> impl Iterator<Item = f64> + '_ {
let (start, end) = self.state.visible_range();
self.primitives_of(series)
.filter_map(move |item| item.get().autoscale(self.state.shown(), start..end))
.flat_map(|(min, max)| [min, max])
}
/// The prices the primitives of the main series and of the overlay studies on the main
/// scale add to its fit.
pub(super) fn main_primitive_prices(&self) -> Vec<f64> {
let studies = self.rendered_studies().indicators();
let mut prices = Vec::new();
if self.main_series_visible {
prices.extend(self.primitive_prices(SeriesId::MAIN));
}
for (idx, id) in self.study_ids.iter().enumerate() {
if studies.get(idx).is_some_and(|study| {
study.is_visible()
&& study.is_overlay()
&& study.scale() == crate::studies::StudyScale::Main
}) && self.study_autoscale[idx]
&& !self.config.scale_price_chart_only
{
prices.extend(self.primitive_prices(*id));
}
}
prices
}
/// Whether a renderer draws the study `series` in place of its plots.
pub(super) fn has_renderer(&self, series: SeriesId) -> bool {
self.primitives_of(series).any(|item| item.replaces)
}
/// Draws the main pane's primitives in `pass`, clipped to the plot.
pub(super) fn paint_primitives(
&self,
painter: &Painter,
coords: &ChartMapping,
pass: PrimitivePass,
) {
let painter = painter.with_clip_rect(painter.clip_rect().intersect(coords.rect));
let shapes = backgrounds(
&painter,
self.main_pass_primitives(coords),
pass,
self.merge_groups.factor(),
);
let grouped = !shapes.is_empty();
paint_backgrounds(&painter, shapes);
if grouped {
for (item, view) in self.main_pass_primitives(coords) {
item.draw(&painter, &view, pass, self.merge_groups.factor());
}
} else {
for (item, view) in self.main_primitives(coords) {
item.draw(&painter, &view, pass, self.merge_groups.factor());
}
}
}
/// Includes renderers of volume overlays, whose foregrounds normally draw with the series.
pub(super) fn main_pass_primitives<'a>(
&'a self,
coords: &'a ChartMapping,
) -> impl DoubleEndedIterator<Item = (&'a Attached, PrimitiveView<'a>)> + Clone {
self.primitives.iter().filter_map(move |item| {
let view = self.main_view(item.series, coords).or_else(|| {
if !item.replaces || self.in_pane(item.series) {
return None;
}
let mut view = self.primitive_view(item.series, coords.clone());
let study = view.study?;
if !study.is_visible() || !study.is_overlay() {
return None;
}
view.mapping = crate::chart::rendering::study_mapping(study, coords);
Some(view)
})?;
Some((item, view))
})
}
/// The visible primitives of a secondary pane, in attachment order, on their own scales.
pub(super) fn pane_primitives<'a>(
&'a self,
members: &'a [SeriesId],
coords: &'a ChartMapping,
) -> impl DoubleEndedIterator<Item = (&'a Attached, PrimitiveView<'a>)> + Clone {
self.primitives.iter().filter_map(move |item| {
if !members.contains(&item.series) || !self.is_series_visible(item.series) {
return None;
}
let mut view = self.primitive_view(item.series, coords.clone());
if let Some(series) = self
.price_series
.iter()
.find(|series| series.id == item.series)
{
view.mapping.price = self.series_map(series, coords.rect);
} else if let Some(study) = view.study
&& matches!(study.scale(), crate::studies::StudyScale::Shared(_))
{
view.mapping = crate::chart::rendering::study_mapping(study, coords);
}
Some((item, view))
})
}
}
/// Defers background shapes until the series have drawn, retaining their clip rectangles.
/// An empty result keeps the existing series foreground order.
pub(super) fn backgrounds<'a>(
painter: &Painter,
primitives: impl Iterator<Item = (&'a Attached, PrimitiveView<'a>)>,
pass: PrimitivePass,
factor: usize,
) -> Vec<egui::epaint::ClippedShape> {
let start = painter
.ctx()
.graphics_mut(|graphics| graphics.entry(painter.layer_id()).next_idx());
for (item, view) in primitives {
item.draw_background(painter, &view, pass, factor);
}
painter.ctx().graphics_mut(|graphics| {
let list = graphics.entry(painter.layer_id());
let end = list.next_idx();
let mut shapes = Vec::new();
for index in start.0..end.0 {
list.mutate_shape(egui::layers::ShapeIdx(index), |shape| {
let empty = egui::epaint::ClippedShape::new(shape.clip_rect, egui::Shape::Noop);
shapes.push(std::mem::replace(shape, empty));
});
}
shapes
})
}
/// Inserts deferred backgrounds without applying the painter's opacity a second time.
pub(super) fn paint_backgrounds(painter: &Painter, shapes: Vec<egui::epaint::ClippedShape>) {
painter.ctx().graphics_mut(|graphics| {
let list = graphics.entry(painter.layer_id());
for shape in shapes {
let index = list.add(shape.clip_rect, egui::Shape::Noop);
list.mutate_shape(index, |entry| *entry = shape);
}
});
}
/// Draws one complete pane pass, with every background before any foreground.
pub(super) fn paint_pass<'a>(
painter: &Painter,
primitives: impl Iterator<Item = (&'a Attached, PrimitiveView<'a>)> + Clone,
pass: PrimitivePass,
factor: usize,
) {
for (item, view) in primitives.clone() {
item.draw_background(painter, &view, pass, factor);
}
for (item, view) in primitives {
item.draw(painter, &view, pass, factor);
}
}
/// Chooses by pass, then distance, keeping `first` on a tie.
pub(super) fn best_hit(first: Option<Hit>, second: Option<Hit>) -> Option<Hit> {
match (first, second) {
(Some(first), Some(second)) => {
if second.result.pass > first.result.pass
|| (second.result.pass == first.result.pass
&& second.result.distance < first.result.distance)
{
Some(second)
} else {
Some(first)
}
}
(first, second) => first.or(second),
}
}
/// The best hit under `pos`, with the latest attached primitive winning ties.
pub(super) fn primitive_at<'a>(
primitives: impl DoubleEndedIterator<Item = (&'a Attached, PrimitiveView<'a>)>,
pos: Pos2,
) -> Option<Hit> {
primitives.rev().fold(None, |best, (item, view)| {
let Some(result) = item.get().hit_test_result(pos, &view) else {
return best;
};
if !result.distance.is_finite() || result.distance < 0.0 {
return best;
}
best_hit(
best,
Some(Hit {
target: if item.replaces {
PointerTarget::Element(ChartElementId::Indicator(item.series))
} else {
PointerTarget::Primitive(item.id)
},
result,
}),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chart::primitives::{PriceAxisLabel, TimeAxisLabel};
use crate::model::Bar;
use crate::studies::{CustomIndicator, IndicatorValue};
use crate::widget::test_frames::{chart, frame, shapes};
use crate::widget::{ChartEvent, SeriesOptions};
use egui::{Color32, CursorIcon, Event, Shape};
type Log = Arc<Mutex<Vec<String>>>;
struct Probe(&'static str, Log);
impl Primitive for Probe {
fn attached(&mut self, _: &egui::Context, _: SeriesId) {
self.1.lock().unwrap().push(format!("{} attached", self.0));
}
fn data_changed(&mut self, bars: &[Bar]) {
let line = format!("{} data {}", self.0, bars.len());
self.1.lock().unwrap().push(line);
}
fn detached(&mut self) {
self.1.lock().unwrap().push(format!("{} detached", self.0));
}
}
#[test]
fn hooks_follow_attachment_bar_changes_and_removal() {
let ctx = egui::Context::default();
let mut chart = chart(&[10.0], &[20.0]);
let bars = chart.bars(SeriesId::MAIN).to_vec();
let line = chart.add_series(SeriesOptions::default());
chart.set_data(line, bars[..50].to_vec());
let log = Log::default();
let main = chart.attach_primitive(SeriesId::MAIN, Probe("main", log.clone()));
chart.attach_primitive(line, Probe("line", log.clone()));
assert!(
chart
.attach_primitive(SeriesId(99), Probe("absent", log.clone()))
.is_none()
);
let take = || std::mem::take(&mut *log.lock().unwrap());
frame(&ctx, &mut chart, 0.0, vec![]);
frame(&ctx, &mut chart, 0.1, vec![]);
assert_eq!(
take(),
[
"main attached",
"main data 100",
"line attached",
"line data 50"
]
);
chart.update(line, bars[50].clone());
frame(&ctx, &mut chart, 0.2, vec![]);
assert_eq!(take(), ["line data 51"]);
let mut corrected = bars[10].clone();
corrected.close = 15.0;
chart.update(line, corrected);
frame(&ctx, &mut chart, 0.25, vec![]);
assert_eq!(take(), ["line data 51"], "a correction before the last bar");
let mut last = bars[99].clone();
last.close = 15.0;
chart.update(SeriesId::MAIN, last);
frame(&ctx, &mut chart, 0.3, vec![]);
assert_eq!(take(), ["main data 100"]);
chart.remove_series(line);
frame(&ctx, &mut chart, 0.4, vec![]);
assert_eq!(take(), ["line detached"]);
assert!(chart.detach_primitive(main.unwrap()));
assert!(!chart.detach_primitive(main.unwrap()));
assert_eq!(take(), ["main detached"]);
}
const BELOW: Color32 = Color32::from_rgb(1, 2, 3);
const SERIES: Color32 = Color32::from_rgb(4, 5, 6);
const ABOVE: Color32 = Color32::from_rgb(7, 8, 9);
#[test]
fn backgrounds_precede_foregrounds_in_every_pass_and_pane() {
struct Ordered {
id: u8,
merged: bool,
log: Log,
}
impl Ordered {
fn record(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
background: bool,
) {
self.log
.lock()
.unwrap()
.push(format!("{pass:?} {background} {}", self.id));
painter.rect_filled(
egui::Rect::from_min_size(view.mapping.rect.min, egui::vec2(8.0, 8.0)),
0.0,
Color32::from_rgb(self.id, background as u8, pass as u8),
);
}
}
impl Primitive for Ordered {
fn draw_background(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
) {
self.record(painter, view, pass, true);
}
fn draw(&self, painter: &Painter, view: &PrimitiveView<'_>, pass: PrimitivePass) {
self.record(painter, view, pass, false);
}
fn draw_background_merged(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
factor: usize,
) {
if self.merged {
assert_eq!(factor, 4);
self.record(painter, view, pass, true);
} else {
self.draw_background(painter, view, pass);
}
}
fn draw_merged(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
factor: usize,
) {
if self.merged {
assert_eq!(factor, 4);
self.record(painter, view, pass, false);
} else {
self.draw(painter, view, pass);
}
}
}
for pane in [false, true] {
for kind in ["main", "bars", "study", "custom", "custom_volume"] {
for merged in [false, true] {
if (pane && kind == "main")
|| (kind == "custom_volume" && !cfg!(feature = "studies"))
{
continue;
}
let ctx = egui::Context::default();
let mut chart = chart(&[10.0], &[20.0]);
let other = chart.add_indicator(Box::new(
CustomIndicator::new("Other", |bars| {
vec![IndicatorValue::Single(15.0); bars.len()]
})
.with_overlay(!pane),
));
let log = Log::default();
let probe = |id| Ordered {
id,
merged,
log: log.clone(),
};
let study = || -> Box<dyn Indicator> {
#[cfg(feature = "studies")]
if kind == "custom_volume" {
let mut volume = crate::studies::Volume::default();
volume.set_overlay(!pane);
return Box::new(volume);
}
Box::new(
CustomIndicator::new("Ordered", |bars| {
bars.iter()
.map(|bar| IndicatorValue::Single(bar.close))
.collect()
})
.with_overlay(!pane),
)
};
let id = match kind {
"main" => SeriesId::MAIN,
"bars" => {
let id = chart.add_series(SeriesOptions::default());
chart.set_data(id, chart.bars(SeriesId::MAIN).to_vec());
if pane {
let destination = chart.add_pane();
chart.move_series_to_pane(id, destination);
}
id
}
"study" => chart.add_indicator(study()),
"custom" | "custom_volume" => chart.add_custom_series(study(), probe(1)),
_ => unreachable!(),
};
if !kind.starts_with("custom") {
chart.attach_primitive(id, probe(1));
}
if pane {
let destination = chart.series_pane(id).unwrap();
assert!(chart.move_series_to_pane(other, destination));
}
chart.attach_primitive(other, probe(2));
if merged {
let mut options = chart.chart_options().clone();
options.time_scale.min_bar_spacing = 0.0;
chart.set_chart_options(options);
chart.apply_synced_time_scale(0.25, 0.0);
}
frame(&ctx, &mut chart, 0.0, vec![]);
log.lock().unwrap().clear();
let painted = shapes(&ctx, &mut chart, 0.1, vec![]);
let mut expected = Vec::new();
let mut colors = Vec::new();
for pass in [
PrimitivePass::Below,
PrimitivePass::Series,
PrimitivePass::Above,
] {
for background in [true, false] {
for id in [1, 2] {
expected.push(format!("{pass:?} {background} {id}"));
colors.push(Color32::from_rgb(id, background as u8, pass as u8));
}
}
}
assert_eq!(
*log.lock().unwrap(),
expected,
"{kind}, pane={pane}, merged={merged}"
);
let actual: Vec<_> = painted
.iter()
.filter_map(|shape| match shape {
Shape::Rect(rect) if colors.contains(&rect.fill) => Some(rect.fill),
_ => None,
})
.collect();
assert_eq!(actual, colors, "paint order: {kind}, pane={pane}");
chart.set_series_visible(id, false);
chart.set_series_visible(other, false);
log.lock().unwrap().clear();
frame(&ctx, &mut chart, 0.2, vec![]);
assert!(log.lock().unwrap().is_empty(), "hidden {kind}");
}
}
}
}
/// Fills a corner of the plot in each pass and asks for prices 0 to 500.
struct Layers;
impl Primitive for Layers {
fn draw(&self, painter: &Painter, view: &PrimitiveView<'_>, pass: PrimitivePass) {
let fill = match pass {
PrimitivePass::Below => BELOW,
PrimitivePass::Series => SERIES,
PrimitivePass::Above => ABOVE,
};
let corner = egui::Rect::from_min_size(view.mapping.rect.min, egui::vec2(9.0, 9.0));
painter.rect_filled(corner, 0.0, fill);
}
fn autoscale(&self, _: &[Bar], _: std::ops::Range<usize>) -> Option<(f64, f64)> {
Some((0.0, 500.0))
}
fn price_axis_labels(&self, _: &PrimitiveView<'_>) -> Vec<PriceAxisLabel> {
vec![PriceAxisLabel {
price: 250.0,
text: "Level".into(),
color: SERIES,
}]
}
fn time_axis_labels(&self, view: &PrimitiveView<'_>) -> Vec<TimeAxisLabel> {
vec![TimeAxisLabel {
time: view.bars[90].time,
text: "A session label much wider than any price on the axis".into(),
color: ABOVE,
}]
}
}
#[test]
fn passes_layer_around_series_and_studies_and_widen_the_scale() {
let ctx = egui::Context::default();
let mut chart = chart(&[10.0], &[20.0]);
let study = Color32::from_rgb(10, 11, 12);
let study_id = chart.add_indicator(Box::new(
CustomIndicator::new("Mid", |bars| {
bars.iter()
.map(|bar| IndicatorValue::Single((bar.high + bar.low) / 2.0))
.collect()
})
.with_color(study),
));
let primitive = chart.attach_primitive(SeriesId::MAIN, Layers).unwrap();
frame(&ctx, &mut chart, 0.0, vec![]);
let shapes = shapes(&ctx, &mut chart, 0.1, vec![]);
let first = |found: &dyn Fn(&Shape) -> bool| shapes.iter().position(found).unwrap();
let fill =
|color| move |shape: &Shape| matches!(shape, Shape::Rect(rect) if rect.fill == color);
let candle = first(&fill(chart.config.bullish_color));
let line = first(&|shape| match shape {
Shape::Path(path) => path.stroke.color == egui::epaint::ColorMode::Solid(study),
Shape::LineSegment { stroke, .. } => stroke.color == study,
_ => false,
});
let (below, series, above) = (
first(&fill(BELOW)),
first(&fill(SERIES)),
first(&fill(ABOVE)),
);
assert!(below < candle && candle < line && line < series && series < above);
let range = chart.state().price_scale().range();
assert!(range.min <= 0.0 && range.max >= 500.0, "{range:?}");
let text = |label: &str| {
shapes
.iter()
.any(|shape| matches!(shape, Shape::Text(text) if text.galley.text() == label))
};
assert!(text("Level") && text("A session label much wider than any price on the axis"));
// A time label is on the time axis and does not size the price axis.
assert!(
chart.measured_axis_width < 120.0,
"{}",
chart.measured_axis_width
);
chart.detach_primitive(primitive);
for (owner, price_only, expected) in [
(SeriesId::MAIN, true, (-62.5, 562.5)),
(study_id, true, (8.75, 21.25)),
(study_id, false, (-62.5, 562.5)),
] {
let primitive = chart.attach_primitive(owner, Layers).unwrap();
chart.config_mut().scale_price_chart_only = price_only;
let painted = super::super::test_frames::shapes(&ctx, &mut chart, 0.2, vec![]);
let range = chart.state().price_scale().range();
assert_eq!((range.min, range.max), expected);
assert!(
painted.iter().any(fill(ABOVE)),
"the primitive still paints"
);
chart.detach_primitive(primitive);
}
}
#[test]
fn bar_series_primitives_follow_pane_moves_and_layer_around_the_bars() {
use crate::model::ChartType;
use crate::widget::PaneId;
let ctx = egui::Context::default();
let mut chart = chart(&[10.0], &[20.0]);
let color = Color32::from_rgb(10, 11, 12);
let id = chart.add_series(SeriesOptions {
chart_type: ChartType::Candles,
up_color: color,
..Default::default()
});
chart.set_data(id, chart.bars(SeriesId::MAIN).to_vec());
chart.attach_primitive(id, Layers);
let pane = chart.add_pane();
assert!(chart.set_preserve_empty_pane(pane, true));
for destination in [pane, PaneId::MAIN, pane] {
assert!(chart.move_series_to_pane(id, destination));
let painted = shapes(&ctx, &mut chart, 0.0, vec![]);
let map = chart.series_price_map(id).unwrap();
assert!(map.range().contains(map.transform().to_scale(500.0)));
if destination != PaneId::MAIN {
assert!(chart.last_price_map.range().max < 100.0);
}
let rects = |fill| {
painted
.iter()
.enumerate()
.filter_map(move |(at, shape)| match shape {
Shape::Rect(rect)
if rect.fill == fill
&& (fill == color || rect.rect.size() == egui::vec2(9.0, 9.0)) =>
{
Some((at, rect.rect))
}
_ => None,
})
};
let (below, rect) = rects(BELOW).next().unwrap();
assert_eq!(rects(BELOW).count(), 1, "drawn only in its own pane");
let candle = rects(color).next().unwrap().0;
let series = rects(SERIES).next().unwrap().0;
let above = rects(ABOVE).next().unwrap().0;
assert!(
below < candle && candle < series && series < above,
"{destination:?}: {below} < {candle} < {series} < {above}"
);
let pane_rect = chart
.pane_layout
.panes
.iter()
.find(|item| item.id == destination)
.unwrap()
.rect;
assert!(pane_rect.contains_rect(rect));
}
chart.set_series_visible(id, false);
assert!(
!shapes(&ctx, &mut chart, 0.2, vec![])
.iter()
.any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == BELOW))
);
}
/// Draws a dot at each value of its study, fills a corner of the plot above everything, and
/// claims the whole plot for the pointer.
struct Dots;
impl Primitive for Dots {
fn draw(&self, painter: &Painter, view: &PrimitiveView<'_>, pass: PrimitivePass) {
if pass == PrimitivePass::Above {
let corner = egui::Rect::from_min_size(view.mapping.rect.min, egui::vec2(9.0, 9.0));
painter.rect_filled(corner, 0.0, ABOVE);
}
for index in view
.visible
.clone()
.filter(|_| pass == PrimitivePass::Series)
{
if let Some(value) = view.study.and_then(|study| study.plot_value(0, index)) {
let centre = Pos2::new(
view.index_to_x(index as f64),
view.mapping.price_to_y(value),
);
painter.circle_filled(centre, 2.0, SERIES);
}
}
}
fn hit_test(&self, pos: Pos2, view: &PrimitiveView<'_>) -> Option<CursorIcon> {
view.mapping
.rect
.contains(pos)
.then_some(CursorIcon::PointingHand)
}
}
#[test]
fn object_hits_rank_by_pass_distance_and_paint_order_in_every_pane() {
struct Objects(Arc<Mutex<Vec<(egui::Vec2, PrimitiveHit)>>>, bool);
impl Primitive for Objects {
fn draw_background(
&self,
painter: &Painter,
view: &PrimitiveView<'_>,
pass: PrimitivePass,
) {
if self.1 && pass == PrimitivePass::Series {
painter.rect_filled(view.mapping.rect, 0.0, BELOW);
}
}
fn hit_test_result(&self, pos: Pos2, view: &PrimitiveView<'_>) -> Option<PrimitiveHit> {
self.0
.lock()
.unwrap()
.iter()
.map(|(offset, hit)| {
let mut hit = hit.clone();
hit.distance = pos.distance(view.mapping.rect.center() + *offset);
hit
})
.filter(|hit| hit.distance <= 20.0)
.max_by(|left, right| {
left.pass
.cmp(&right.pass)
.then_with(|| right.distance.total_cmp(&left.distance))
})
}
}
struct Invalid(f32);
impl Primitive for Invalid {
fn hit_test_result(&self, _: Pos2, _: &PrimitiveView<'_>) -> Option<PrimitiveHit> {
Some(PrimitiveHit {
distance: self.0,
pass: PrimitivePass::Above,
..PrimitiveHit::new(CursorIcon::Wait)
})
}
}
let object = |id: &str, cursor, offset| {
(
offset,
PrimitiveHit {
object_id: Some(id.into()),
data: Some(Arc::new(serde_json::json!({ "object": id }))),
..PrimitiveHit::new(cursor)
},
)
};
for (secondary, backgrounds) in [false, true]
.into_iter()
.flat_map(|secondary| [false, true].map(|backgrounds| (secondary, backgrounds)))
{
let ctx = egui::Context::default();
let mut chart = chart(&[10.0], &[20.0]);
chart.config.show_volume = false;
let objects = Arc::new(Mutex::new(vec![
object("upper", CursorIcon::ResizeVertical, egui::vec2(0.0, -8.0)),
object("lower", CursorIcon::Grab, egui::vec2(0.0, 8.0)),
]));
let series = chart.add_custom_series(
Box::new(
CustomIndicator::new("Objects", |bars| {
vec![IndicatorValue::Single(15.0); bars.len()]
})
.with_overlay(!secondary),
),
Objects(objects.clone(), backgrounds),
);
let first = Arc::new(Mutex::new(vec![object(