egui-charts 0.2.0

High-performance financial charting engine for egui — candlesticks, 95 drawing tools, 130+ indicators, and a full design-token theme system
Documentation
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
//! Drawing manager -- thin coordinator that delegates to specialized services.
//!
//! `DrawingManager` is the primary entry point for managing drawings on a
//! chart. It owns the drawing list, delegates selection to
//! `SelectionService`, undo/redo to `HistoryService`, snapping to
//! `SnapService`, and handle manipulation to `HandleService`.
//!
//! At the start of each frame, call [`DrawingManager::sync_from_app_state`] to
//! synchronize the active tool, magnet mode, and selection from the central
//! application state. Then call [`DrawingManager::update_all_screen_coords`] to
//! recompute screen positions from chart coordinates before rendering.

use crate::drawings::domain::{Drawing, DrawingToolType, HandlePos};
use crate::drawings::services::{
    DrawingInteraction, HandleConfig, HandleService, HistoryService, SelectionService, SnapOptions,
    SnapService,
};
use crate::tokens::DESIGN_TOKENS;
use egui::{Pos2, Rect};
use std::sync::{Arc, Mutex};

/// Actions queued for backend/cloud synchronization.
///
/// These are produced by [`DrawingManager`] operations (create, update, delete)
/// and consumed by the platform integration layer to persist changes to a
/// remote backend or local storage.
#[derive(Debug, Clone)]
pub enum DrawingSyncAction {
    /// A new drawing was created and should be saved. Carries the drawing ID.
    SaveDrawing(usize),
    /// An existing drawing was modified (moved, resized, styled). Carries the drawing ID.
    UpdateDrawing(usize),
    /// A drawing was deleted. Carries the stored drawing ID as a string.
    Delete(String),
    /// A batch of drawings should be restored from backend storage.
    RestoreDrawings(Vec<crate::drawings::persistence::StoredDrawing>),
}

/// Snapshot of drawing-related state from the central application state.
///
/// This struct is passed to [`DrawingManager::sync_from_app_state`] at the start
/// of each frame to ensure the manager stays in sync with toolbar selections,
/// keyboard shortcuts, and other UI actions that modify drawing state.
#[derive(Debug, Clone, Default)]
pub struct DrawingState {
    /// Currently selected drawing tool. `None` means selection/pointer mode.
    pub active_tool: Option<DrawingToolType>,
    /// ID of the currently selected (highlighted) drawing on the chart.
    pub sel_drawing: Option<usize>,
    /// Whether magnet mode is enabled (snap to OHLC prices and existing drawing points).
    pub magnet_mode: bool,
    /// Whether to stay in drawing mode after completing a drawing (lock mode).
    pub stay_in_drawing_mode: bool,
    /// Current default drawing color as RGBA bytes.
    pub curr_color: [u8; 4],
    /// Whether eraser mode is active (click to delete drawings).
    pub eraser_mode: bool,
}

/// Configuration options for the [`DrawingManager`].
///
/// Controls default colors, snapping behavior, magnet mode thresholds, and
/// selection handle appearance.
#[derive(Clone, Debug)]
pub struct DrawingManagerOptions {
    /// Default color for new drawings as RGBA bytes.
    pub default_color: [u8; 4],
    /// Enable snap-to-price (Y-axis snapping to OHLC levels).
    pub snap_to_price: bool,
    /// Enable snap-to-time (X-axis snapping to candle timestamps).
    pub snap_to_time: bool,
    /// Snap distance threshold in screen pixels.
    pub snap_distance: f32,
    /// Enable magnet mode (snap to existing drawing anchor points).
    pub magnet_mode: bool,
    /// Magnet snap distance threshold in screen pixels.
    pub magnet_distance: f32,
    /// Configuration for selection handle appearance and hit testing.
    pub handle_config: HandleConfig,
}

impl Default for DrawingManagerOptions {
    fn default() -> Self {
        Self {
            default_color: [41, 98, 255, 255],
            snap_to_price: true,
            snap_to_time: true,
            snap_distance: DESIGN_TOKENS.spacing.lg + DESIGN_TOKENS.spacing.xs,
            magnet_mode: false,
            magnet_distance: DESIGN_TOKENS.sizing.drawing.magnet_distance,
            handle_config: HandleConfig::default(),
        }
    }
}

/// Central coordinator for chart drawings.
///
/// `DrawingManager` owns the list of completed drawings and the in-progress
/// drawing, and delegates business logic to specialized services:
///
/// - **Selection** via [`SelectionService`]
/// - **Undo/redo** via [`HistoryService`]
/// - **Snapping** via [`SnapService`]
/// - **Handle manipulation** via [`HandleService`]
///
/// # Frame loop integration
///
/// ```ignore
/// // 1. Sync state from app
/// manager.sync_from_app_state(&drawing_state);
///
/// // 2. Update screen coordinates from chart coordinates
/// manager.update_all_screen_coords(bar_to_x, price_to_y);
///
/// // 3. Handle user input (clicks, drags, keyboard)
/// // ... (start_drawing_with_coords, add_point_with_coords, etc.)
///
/// // 4. Render
/// manager.render_all(&painter, price_rect);
/// ```
pub struct DrawingManager {
    /// All completed drawings on the chart.
    pub drawings: Vec<Drawing>,
    /// Currently active drawing tool, or `None` for selection/pointer mode.
    pub active_tool: Option<DrawingToolType>,
    /// The drawing currently being created (not yet completed).
    pub curr_drawing: Option<Drawing>,
    /// Next available drawing ID (monotonically increasing).
    next_id: usize,

    // Services
    selection: SelectionService,
    history: HistoryService,
    snap_service: SnapService,

    /// Manager configuration (colors, snapping, handles).
    pub options: DrawingManagerOptions,

    /// Currently dragged handle, if any: `(drawing_id, handle_position)`.
    pub dragging_handle: Option<(usize, HandlePos)>,
    /// Snapshot of the drawing state before the current drag began (for undo).
    drag_old_state: Option<Drawing>,

    /// Whether to stay in drawing mode after completing a drawing.
    pub stay_in_drawing_mode: bool,
    /// Current chart timeframe string (e.g., `"1D"`, `"1h"`), used for
    /// per-timeframe drawing visibility filtering.
    pub curr_timeframe: String,
    /// Whether eraser mode is active.
    pub eraser_mode: bool,
    /// Drawing ID currently hovered by the eraser cursor (for visual feedback).
    pub eraser_hover_drawing: Option<usize>,

    /// Queue of sync actions for backend/cloud persistence.
    pub pending_sync: Arc<Mutex<Vec<DrawingSyncAction>>>,
}

impl Default for DrawingManager {
    fn default() -> Self {
        Self::new()
    }
}

impl DrawingManager {
    /// Creates a new `DrawingManager` with default options and empty drawing list.
    pub fn new() -> Self {
        Self {
            drawings: Vec::new(),
            active_tool: None,
            curr_drawing: None,
            next_id: 0,
            selection: SelectionService::new(),
            history: HistoryService::new(),
            snap_service: SnapService::new(),
            options: DrawingManagerOptions::default(),
            dragging_handle: None,
            drag_old_state: None,
            stay_in_drawing_mode: false,
            curr_timeframe: String::from("1D"),
            eraser_mode: false,
            eraser_hover_drawing: None,
            pending_sync: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Sync drawing manager state from central AppState
    /// Called at the start of each frame to ensure consistency
    pub fn sync_from_app_state(&mut self, drawing_state: &DrawingState) {
        self.active_tool = drawing_state.active_tool;
        self.options.magnet_mode = drawing_state.magnet_mode;
        self.options.default_color = drawing_state.curr_color;
        self.stay_in_drawing_mode = drawing_state.stay_in_drawing_mode;
        self.eraser_mode = drawing_state.eraser_mode;

        // Sync selection
        match (drawing_state.sel_drawing, self.selection.primary()) {
            (Some(id), current) if current != Some(id) => {
                self.selection.select(id);
            }
            (None, Some(_)) => {
                self.selection.deselect_all();
            }
            _ => {} // Already in sync
        }
    }

    // === Selection delegation ===

    /// Returns the ID of the currently selected (primary) drawing, if any.
    pub fn sel_drawing(&self) -> Option<usize> {
        self.selection.primary()
    }

    /// Selects the drawing with the given ID (deselects all others).
    pub fn select(&mut self, id: usize) {
        self.selection.select(id);
    }

    /// Deselects all drawings.
    pub fn deselect(&mut self) {
        self.selection.deselect_all();
    }

    /// Hit-tests at `point` and selects the topmost drawing found.
    ///
    /// Returns `true` if a drawing was selected, `false` if the click hit empty space
    /// (which deselects all drawings).
    pub fn select_at(&mut self, point: Pos2) -> bool {
        if let Some(id) = self.hit_test(point) {
            self.selection.select(id);
            true
        } else {
            self.selection.deselect_all();
            false
        }
    }

    // === History delegation ===

    /// Undoes the last drawing operation. Returns `true` if an operation was undone.
    pub fn undo(&mut self) -> bool {
        self.history.undo(&mut self.drawings).is_some()
    }

    /// Redoes the last undone operation. Returns `true` if an operation was redone.
    pub fn redo(&mut self) -> bool {
        self.history.redo(&mut self.drawings).is_some()
    }

    /// Returns `true` if there are operations available to undo.
    pub fn can_undo(&self) -> bool {
        self.history.can_undo()
    }

    /// Returns `true` if there are operations available to redo.
    pub fn can_redo(&self) -> bool {
        self.history.can_redo()
    }

    // === Snap delegation ===

    /// Rebuilds the internal [`SnapService`] from the current manager options.
    /// Call this after changing snap-related options.
    pub fn update_snap_options(&mut self) {
        self.snap_service = SnapService::with_options(SnapOptions {
            snap_to_price: self.options.snap_to_price,
            snap_to_time: self.options.snap_to_time,
            snap_distance: self.options.snap_distance,
            magnet_mode: self.options.magnet_mode,
            magnet_distance: self.options.magnet_distance,
        });
    }

    /// Applies snap behavior to a screen point, returning the snapped position.
    ///
    /// Snaps to price levels, time markers, and existing drawing anchor points
    /// depending on the current snap/magnet configuration. Magnet targets are
    /// borrowed directly from `drawings`, so no per-pointer-move allocation of
    /// the flattened point set occurs during a drag.
    pub fn snap_point(&self, point: Pos2, drawings: &[Drawing]) -> Pos2 {
        // Prices/times would be populated from the chart; magnet points are
        // borrowed from the live drawings without cloning.
        self.snap_service.snap_point_with_drawing_points(
            point,
            &[],
            &[],
            drawings.iter().flat_map(|d| d.points.iter().copied()),
        )
    }

    // === Handle delegation ===

    /// Returns the selection handle positions for a drawing (tool-type-aware).
    pub fn get_handles(&self, drawing: &Drawing) -> Vec<(HandlePos, Pos2)> {
        HandleService::get_handles(drawing)
    }

    /// Hit-tests a point against the handles of a drawing.
    ///
    /// Returns the [`HandlePos`] if a handle was hit, `None` otherwise.
    pub fn hit_test_handle(&self, drawing: &Drawing, point: Pos2) -> Option<HandlePos> {
        HandleService::hit_test_handle(drawing, point, self.options.handle_config.size)
    }

    /// Begins a handle drag operation, saving the drawing's current state for undo.
    pub fn start_drag_handle(&mut self, drawing_id: usize, handle: HandlePos) {
        if let Some(drawing) = self.drawings.iter().find(|d| d.id == drawing_id) {
            self.dragging_handle = Some((drawing_id, handle));
            self.drag_old_state = Some(drawing.clone());
        }
    }

    /// Updates the position of the currently dragged handle to `new_pos`,
    /// applying snap behavior and coordinate conversion.
    pub fn update_drag_handle<F, G>(&mut self, new_pos: Pos2, x_to_bar: F, y_to_price: G)
    where
        F: Fn(f32) -> f32,
        G: Fn(f32) -> f64,
    {
        if let Some((id, handle)) = self.dragging_handle {
            // Compute snapped position before mutable borrow
            let snapped = self.snap_point(new_pos, &[]);
            if let Some(drawing) = self.drawings.iter_mut().find(|d| d.id == id) {
                HandleService::update_handle(drawing, handle, snapped, x_to_bar, y_to_price);
            }
        }
    }

    /// Ends the current handle drag operation, pushing a modify command to the
    /// undo history and queuing a cloud sync update.
    pub fn end_drag_handle(&mut self) {
        if let Some(old_state) = self.drag_old_state.take() {
            let drawing_id = old_state.id;
            self.history.push_modify(old_state.id, old_state);

            // Queue cloud sync for the updated drawing
            if let Ok(mut sync) = self.pending_sync.lock() {
                sync.push(DrawingSyncAction::UpdateDrawing(drawing_id));
            }
        }
        self.dragging_handle = None;
    }

    /// Renders selection handles for a drawing, highlighting the currently
    /// dragged handle (if any).
    pub fn render_handles(&self, painter: &egui::Painter, drawing: &Drawing) {
        let dragging = self
            .dragging_handle
            .filter(|(id, _)| *id == drawing.id)
            .map(|(_, h)| h);
        HandleService::render_handles(painter, drawing, &self.options.handle_config, dragging);
    }

    // === Tool management ===

    /// Sets the active drawing tool. Pass `None` to exit drawing mode and
    /// return to selection/pointer mode. Cancels any in-progress drawing.
    pub fn set_active_tool(&mut self, tool: Option<DrawingToolType>) {
        self.active_tool = tool;
        if tool.is_some() {
            self.curr_drawing = None;
        }
    }

    /// Start text annotation mode
    ///
    /// Activates the Note drawing tool, allowing the user to click
    /// on the chart to place a text note annotation.
    pub fn start_text_annotation(&mut self) {
        self.set_active_tool(Some(DrawingToolType::Note));
    }

    /// Start icon/emoji insertion mode
    ///
    /// Prepares a FontIcon drawing with the specified icon name,
    /// allowing the user to click on the chart to place it.
    pub fn start_icon_insertion(&mut self, icon_name: String) {
        self.set_active_tool(Some(DrawingToolType::FontIcon));

        // Create a new drawing with the icon name
        let mut drawing = Drawing::with_color(
            self.next_id,
            DrawingToolType::FontIcon,
            self.options.default_color,
        );
        self.next_id += 1;

        // Store the icon name in the text field
        drawing.text = Some(icon_name);
        drawing.font_size = 32.0; // Larger size for icons/emojis
        drawing.completed = false; // Not complete until user clicks

        // Set as current drawing (will be placed on next click)
        self.curr_drawing = Some(drawing);
    }

    // === Drawing lifecycle ===

    /// Starts a new drawing of the given tool type at the given screen position.
    ///
    /// The coordinate conversion closures (`x_to_bar`, `y_to_price`) convert
    /// screen coordinates to chart coordinates for persistent storage. If the
    /// tool requires only one point, the drawing is immediately completed and
    /// added to the drawing list.
    pub fn start_drawing_with_coords<F, G>(
        &mut self,
        tool_type: DrawingToolType,
        point: Pos2,
        x_to_bar: F,
        y_to_price: G,
    ) where
        F: Fn(f32) -> f32,
        G: Fn(f32) -> f64,
    {
        let mut drawing = Drawing::with_color(self.next_id, tool_type, self.options.default_color);
        let drawing_id = self.next_id;
        self.next_id += 1;
        drawing.add_point_with_chart_coords(point, x_to_bar, y_to_price);

        if drawing.completed {
            self.history.push_add(drawing.clone());
            self.drawings.push(drawing);

            // Queue cloud sync
            if let Ok(mut sync) = self.pending_sync.lock() {
                sync.push(DrawingSyncAction::SaveDrawing(drawing_id));
            }

            self.curr_drawing = None;
            if !self.stay_in_drawing_mode {
                self.active_tool = None;
            }
        } else {
            self.curr_drawing = Some(drawing);
        }
    }

    /// Adds a subsequent point to the in-progress drawing.
    ///
    /// If the added point completes the drawing (based on
    /// [`DrawingToolType::required_points`]), the drawing is finalized, pushed
    /// to the drawing list, and a cloud sync action is queued.
    pub fn add_point_with_coords<F, G>(&mut self, point: Pos2, x_to_bar: F, y_to_price: G)
    where
        F: Fn(f32) -> f32,
        G: Fn(f32) -> f64,
    {
        if let Some(ref mut drawing) = self.curr_drawing {
            let drawing_id = drawing.id;
            drawing.add_point_with_chart_coords(point, &x_to_bar, &y_to_price);

            if drawing.completed {
                self.history.push_add(drawing.clone());
                self.drawings.push(drawing.clone());

                // Queue cloud sync
                if let Ok(mut sync) = self.pending_sync.lock() {
                    sync.push(DrawingSyncAction::SaveDrawing(drawing_id));
                }

                self.curr_drawing = None;
                if !self.stay_in_drawing_mode {
                    self.active_tool = None;
                }
            }
        }
    }

    /// Updates the last point of the in-progress drawing (used for live preview
    /// as the cursor moves between the first click and the final placement).
    pub fn update_last_point_with_coords<F, G>(&mut self, point: Pos2, x_to_bar: F, y_to_price: G)
    where
        F: Fn(f32) -> f32,
        G: Fn(f32) -> f64,
    {
        if let Some(ref mut drawing) = self.curr_drawing
            && !drawing.points.is_empty()
            && !drawing.completed
        {
            if drawing.points.len() == 1 {
                drawing.add_point_with_chart_coords(point, &x_to_bar, &y_to_price);
                drawing.completed = false;
            } else if drawing.points.len() >= 2 {
                drawing.update_last_point_with_chart_coords(point, x_to_bar, y_to_price);
            }
        }
    }

    /// Manually completes the in-progress drawing (e.g., on double-click or Enter
    /// for multi-point tools). Requires at least 2 points.
    pub fn complete_curr_drawing(&mut self) {
        if let Some(ref mut drawing) = self.curr_drawing
            && drawing.points.len() >= 2
        {
            drawing.completed = true;
            self.history.push_add(drawing.clone());
            self.drawings.push(drawing.clone());
            self.curr_drawing = None;
            if !self.stay_in_drawing_mode {
                self.active_tool = None;
            }
        }
    }

    /// Cancels the in-progress drawing without adding it to the drawing list.
    pub fn cancel_curr_drawing(&mut self) {
        self.curr_drawing = None;
    }

    // === Drawing CRUD ===

    /// Deletes the drawing with the given ID from the drawing list.
    ///
    /// The deleted drawing is pushed to the undo history and a cloud sync
    /// delete action is queued. If the deleted drawing was selected, the
    /// selection is cleared.
    pub fn delete_drawing(&mut self, id: usize) {
        if let Some(drawing) = self.drawings.iter().find(|d| d.id == id).cloned() {
            self.drawings.retain(|d| d.id != id);
            self.history.push_delete(drawing);
            if let Ok(mut sync) = self.pending_sync.lock() {
                sync.push(DrawingSyncAction::Delete(id.to_string()));
            }
        }
        if self.selection.primary() == Some(id) {
            self.selection.deselect_all();
        }
    }

    /// Deletes the currently selected drawing (if any).
    pub fn delete_selected(&mut self) {
        if let Some(id) = self.selection.primary() {
            self.delete_drawing(id);
        }
    }

    /// Removes all drawings and clears the current drawing and selection.
    ///
    /// Note: This does not push to the undo history (it is a destructive reset).
    pub fn clear_all(&mut self) {
        self.drawings.clear();
        self.curr_drawing = None;
        self.selection.deselect_all();
    }

    // === Layer ordering ===

    /// Bring a drawing to the front (rendered last, on top)
    pub fn bring_to_front(&mut self, id: usize) {
        if let Some(idx) = self.drawings.iter().position(|d| d.id == id) {
            let drawing = self.drawings.remove(idx);
            self.drawings.push(drawing);
        }
    }

    /// Send a drawing to the back (rendered first, behind others)
    pub fn send_to_back(&mut self, id: usize) {
        if let Some(idx) = self.drawings.iter().position(|d| d.id == id) {
            let drawing = self.drawings.remove(idx);
            self.drawings.insert(0, drawing);
        }
    }

    // === Coordinate updates ===

    /// Recomputes screen coordinates for all drawings (completed and in-progress)
    /// from their persistent chart coordinates using the current pan/zoom transforms.
    ///
    /// Must be called each frame before rendering.
    pub fn update_all_screen_coords<F, G>(&mut self, bar_to_x: F, price_to_y: G)
    where
        F: Fn(f32) -> f32 + Copy,
        G: Fn(f64) -> f32 + Copy,
    {
        for drawing in &mut self.drawings {
            drawing.update_screen_coords(bar_to_x, price_to_y);
        }
        if let Some(ref mut drawing) = self.curr_drawing {
            drawing.update_screen_coords(bar_to_x, price_to_y);
        }
    }

    /// Shifts all bar indices by `shift` across all drawings, the in-progress
    /// drawing, and the undo history.
    ///
    /// This is called when historical data is prepended to the chart, causing
    /// existing bar indices to shift right.
    pub fn shift_bar_indices(&mut self, shift: f32) {
        if shift.abs() < 0.001 {
            return;
        }
        for drawing in &mut self.drawings {
            for cp in &mut drawing.chart_points {
                cp.bar_idx += shift;
            }
        }
        if let Some(ref mut curr) = self.curr_drawing {
            for cp in &mut curr.chart_points {
                cp.bar_idx += shift;
            }
        }
        self.history.shift_bar_indices(shift);
    }

    // === Hit testing ===

    /// Hit-tests a screen point against all visible drawings (back-to-front).
    ///
    /// Returns the ID of the topmost drawing at `point`, or `None` if no
    /// drawing was hit. Delegates to [`DrawingInteraction::hit_test`], the single
    /// source of truth for per-segment / per-level geometry hit testing, so that
    /// channels, Fibonacci levels, fans, and pitchforks are selectable along
    /// their drawn geometry rather than only near a control point. Honors the
    /// active timeframe so drawings hidden on the current timeframe are not hit.
    pub fn hit_test(&self, point: Pos2) -> Option<usize> {
        DrawingInteraction::new().hit_test(point, &self.drawings, &self.curr_timeframe)
    }

    // === Visibility ===

    /// Toggles the visibility of all drawings. If all are visible, hides them
    /// all; otherwise shows them all.
    pub fn toggle_visibility_all(&mut self) {
        let all_visible = self.drawings.iter().all(|d| d.visible);
        for drawing in &mut self.drawings {
            drawing.visible = !all_visible;
        }
    }

    /// Toggles the lock state of all drawings. If all are locked, unlocks them
    /// all; otherwise locks them all.
    pub fn toggle_lock_all(&mut self) {
        let all_locked = self.drawings.iter().all(|d| d.locked);
        for drawing in &mut self.drawings {
            drawing.locked = !all_locked;
        }
    }

    // === Compatibility methods for old DrawingManager API ===

    /// Complete a drag-to-draw drawing (same as complete_curr_drawing)
    pub fn complete_drag_drawing(&mut self) {
        self.complete_curr_drawing();
    }

    /// Update drag handle with coordinate conversion functions
    /// Alias for update_drag_handle for API compatibility
    pub fn update_drag_handle_with_coords<F, G>(
        &mut self,
        new_pos: Pos2,
        x_to_bar: F,
        y_to_price: G,
    ) where
        F: Fn(f32) -> f32,
        G: Fn(f32) -> f64,
    {
        self.update_drag_handle(new_pos, x_to_bar, y_to_price);
    }

    /// Hit test a handle by drawing ID
    /// Returns the handle position if hit, None otherwise
    pub fn hit_test_handle_by_id(&self, point: Pos2, drawing_id: usize) -> Option<HandlePos> {
        if let Some(drawing) = self.drawings.iter().find(|d| d.id == drawing_id) {
            self.hit_test_handle(drawing, point)
        } else {
            None
        }
    }

    /// Update real-time prices for position drawings (P&L calculation)
    pub fn update_pos_prices(&mut self, price: f64) {
        for drawing in &mut self.drawings {
            drawing.curr_price = Some(price);
        }
    }

    /// Add a drawing from another source (for multi-chart sync)
    pub fn add_synced_drawing(&mut self, mut drawing: Drawing) {
        // Assign a new ID to avoid conflicts
        drawing.id = self.next_id;
        self.next_id += 1;
        self.drawings.push(drawing);
    }

    /// Render all drawings
    pub fn render_all(&self, painter: &egui::Painter, price_rect: Rect) {
        // Render completed drawings
        for drawing in &self.drawings {
            if drawing.visible {
                drawing.render(painter, price_rect);
            }
        }

        // Render current drawing being created
        if let Some(ref drawing) = self.curr_drawing {
            drawing.render(painter, price_rect);
        }

        // Render handles for selected drawing
        if let Some(sel_id) = self.selection.primary()
            && let Some(drawing) = self.drawings.iter().find(|d| d.id == sel_id)
        {
            self.render_handles(painter, drawing);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_manager() {
        let manager = DrawingManager::new();
        assert!(manager.drawings.is_empty());
        assert!(manager.active_tool.is_none());
    }

    #[test]
    fn test_selection() {
        let mut manager = DrawingManager::new();
        manager.select(1);
        assert_eq!(manager.sel_drawing(), Some(1));
        manager.deselect();
        assert_eq!(manager.sel_drawing(), None);
    }

    /// A click on a Fibonacci level line, far from every control point, must
    /// select the drawing. This proves selection is routed through the unified
    /// per-level hit testing in the interaction service rather than the old
    /// vertex-proximity fallback that only matched near a control point.
    #[test]
    fn test_hit_test_fibonacci_level_off_control_point() {
        let mut manager = DrawingManager::new();
        let mut fib = Drawing::new(7, DrawingToolType::FibonacciRetracement);
        // Control points: Start (100,100), End (300,200), Middle (200,150).
        fib.points = vec![Pos2::new(100.0, 100.0), Pos2::new(300.0, 200.0)];
        fib.completed = true;
        manager.drawings.push(fib);

        // 0.236 level: y = 100 + (200-100)*0.236 = 123.6, sampled at x = 180.
        // This point is > 50px from Start, End, and Middle handles.
        let click = Pos2::new(180.0, 123.6);
        for handle in [
            Pos2::new(100.0, 100.0),
            Pos2::new(300.0, 200.0),
            Pos2::new(200.0, 150.0),
        ] {
            let d = ((click.x - handle.x).powi(2) + (click.y - handle.y).powi(2)).sqrt();
            assert!(d > 20.0, "click must be off control points, was {d}px away");
        }

        assert_eq!(manager.hit_test(click), Some(7));
        assert!(manager.select_at(click));
        assert_eq!(manager.sel_drawing(), Some(7));
    }

    /// A click on a parallel-channel segment, far from every control point,
    /// must select the drawing -- again proving per-segment hit testing.
    #[test]
    fn test_hit_test_channel_segment_off_control_point() {
        let mut manager = DrawingManager::new();
        let mut channel = Drawing::new(11, DrawingToolType::ParallelChannel);
        // Main line p1 (100,100) -> p2 (300,100); offset point p3 (200,200).
        channel.points = vec![
            Pos2::new(100.0, 100.0),
            Pos2::new(300.0, 100.0),
            Pos2::new(200.0, 200.0),
        ];
        channel.completed = true;
        manager.drawings.push(channel);

        // Midway along the main line, 50px+ from p1, p2, and p3.
        let click = Pos2::new(150.0, 100.0);
        for handle in [
            Pos2::new(100.0, 100.0),
            Pos2::new(300.0, 100.0),
            Pos2::new(200.0, 200.0),
        ] {
            let d = ((click.x - handle.x).powi(2) + (click.y - handle.y).powi(2)).sqrt();
            assert!(d > 20.0, "click must be off control points, was {d}px away");
        }

        assert_eq!(manager.hit_test(click), Some(11));
    }

    /// Snapping must borrow magnet targets from the live drawings without
    /// allocating a flattened point set on each call.
    #[test]
    fn test_snap_point_borrows_magnet_targets() {
        let mut manager = DrawingManager::new();
        manager.options.magnet_mode = true;
        manager.update_snap_options();

        let mut d = Drawing::new(1, DrawingToolType::TrendLine);
        d.points = vec![Pos2::new(100.0, 100.0), Pos2::new(200.0, 200.0)];
        let drawings = vec![d];

        // A pointer near the first anchor snaps to it under magnet mode.
        let snapped = manager.snap_point(Pos2::new(103.0, 102.0), &drawings);
        assert_eq!(snapped, Pos2::new(100.0, 100.0));
    }
}