aumate 0.2.8

Cross-platform desktop automation library with GUI support
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
//! ScreenshotMode - main state machine for screenshot functionality
//!
//! Coordinates selection, toolbar, and action execution.

use image::{ImageBuffer, Rgba};
use winit::event::{ElementState, MouseButton, WindowEvent};
use xcap::Monitor;

use super::action::{ActionContext, ActionResult, DrawingContext, RenderContext, ToolCategory};
use super::action_bar::ActionBar;
use super::history::History;
use super::options_panel::OptionsPanel;
use super::registry::{ActionRegistry, create_default_registry};
use super::selection::Selection;
use super::settings::ScreenshotSettings;
use super::stroke::{Annotations, StrokeSettings};
use super::ui::{SettingsButton, SettingsToolbar};
use crate::error::{AumateError, Result};

/// Screenshot mode state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModeState {
    /// Waiting for user to start selection
    Idle,
    /// User is dragging to select region
    Selecting,
    /// Selection complete, showing toolbar
    ToolbarVisible,
    /// Screenshot mode should exit
    Exiting,
}

/// Handle positions for selection resizing
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HandlePosition {
    TopLeft,
    TopCenter,
    TopRight,
    MiddleLeft,
    MiddleRight,
    BottomLeft,
    BottomCenter,
    BottomRight,
}

impl HandlePosition {
    /// Returns all 8 handle positions
    pub fn all() -> [HandlePosition; 8] {
        [
            Self::TopLeft,
            Self::TopCenter,
            Self::TopRight,
            Self::MiddleLeft,
            Self::MiddleRight,
            Self::BottomLeft,
            Self::BottomCenter,
            Self::BottomRight,
        ]
    }
}

/// Handle size in pixels
const HANDLE_SIZE: f32 = 10.0;

/// Main screenshot mode controller
pub struct ScreenshotMode {
    /// Current state
    state: ModeState,
    /// Selection state
    selection: Selection,
    /// New Snipaste-style action bar
    action_bar: Option<ActionBar>,
    /// Options panel for tool settings
    options_panel: Option<OptionsPanel>,
    /// History for undo/redo
    history: History,
    /// Action registry
    registry: ActionRegistry,
    /// Captured screenshot image
    screenshot: Option<ImageBuffer<Rgba<u8>, Vec<u8>>>,
    /// Monitor used for capture
    monitor: Option<Monitor>,
    /// Scale factor for DPI
    scale_factor: f64,
    /// Screen size in logical coordinates
    screen_size: (f32, f32),
    /// Currently hovered button ID
    hovered_button: Option<String>,
    /// Whether annotation mode is active
    annotate_active: bool,
    /// Stroke settings for drawing (synced from options panel)
    stroke_settings: StrokeSettings,
    /// Annotations drawn on screenshot
    annotations: Annotations,
    /// Last cursor position (for drawing)
    last_cursor_pos: Option<(f32, f32)>,
    /// Currently hovered handle (for cursor change)
    hovered_handle: Option<HandlePosition>,
    /// Handle being dragged for resize
    dragging_handle: Option<HandlePosition>,
    /// Screenshot appearance settings
    settings: ScreenshotSettings,
    /// Top-left settings toolbar
    settings_toolbar: SettingsToolbar,
    /// Whether the action bar is being dragged
    action_bar_dragging: bool,
}

impl ScreenshotMode {
    /// Create a new screenshot mode with specified enabled actions
    ///
    /// Captures the current screen and initializes the registry.
    pub fn new(enabled_actions: Vec<String>, scale_factor: f64) -> Result<Self> {
        // Get monitors
        let monitors = Monitor::all()
            .map_err(|e| AumateError::Screenshot(format!("Failed to get monitors: {}", e)))?;

        if monitors.is_empty() {
            return Err(AumateError::Screenshot("No monitors found".to_string()));
        }

        // Use primary monitor
        let monitor = monitors.into_iter().next().unwrap();

        // Capture screenshot
        let screenshot = monitor
            .capture_image()
            .map_err(|e| AumateError::Screenshot(format!("Failed to capture screen: {}", e)))?;

        let screen_width = monitor
            .width()
            .map_err(|e| AumateError::Screenshot(format!("Failed to get width: {}", e)))?;
        let screen_height = monitor
            .height()
            .map_err(|e| AumateError::Screenshot(format!("Failed to get height: {}", e)))?;

        // Create and configure registry
        let mut registry = create_default_registry();
        registry.enable_all(&enabled_actions);

        let screen_size =
            (screen_width as f32 / scale_factor as f32, screen_height as f32 / scale_factor as f32);

        log::info!(
            "ScreenshotMode: xcap physical={}x{}, scale_factor={}, logical screen_size=({}, {})",
            screen_width,
            screen_height,
            scale_factor,
            screen_size.0,
            screen_size.1
        );

        Ok(Self {
            state: ModeState::Idle,
            selection: Selection::new(),
            action_bar: None,
            options_panel: None,
            history: History::new(),
            registry,
            screenshot: Some(screenshot),
            monitor: Some(monitor),
            scale_factor,
            screen_size,
            hovered_button: None,
            annotate_active: false,
            stroke_settings: StrokeSettings::default(),
            annotations: Annotations::new(),
            last_cursor_pos: None,
            hovered_handle: None,
            dragging_handle: None,
            settings: ScreenshotSettings::default(),
            settings_toolbar: SettingsToolbar::new(),
            action_bar_dragging: false,
        })
    }

    /// Get current state
    pub fn state(&self) -> ModeState {
        self.state
    }

    /// Check if screenshot mode should exit
    pub fn should_exit(&self) -> bool {
        self.state == ModeState::Exiting
    }

    /// Get the captured screenshot
    pub fn screenshot(&self) -> Option<&ImageBuffer<Rgba<u8>, Vec<u8>>> {
        self.screenshot.as_ref()
    }

    /// Get the selection bounds in logical coordinates
    pub fn selection_bounds(&self) -> Option<((f32, f32), (f32, f32))> {
        self.selection.bounds()
    }

    /// Update the screen size (call this with the actual window size in logical pixels)
    pub fn set_screen_size(&mut self, width: f32, height: f32) {
        log::info!(
            "ScreenshotMode: updating screen_size from ({}, {}) to ({}, {})",
            self.screen_size.0,
            self.screen_size.1,
            width,
            height
        );
        self.screen_size = (width, height);
    }

    /// Sync stroke settings from options panel
    fn sync_stroke_settings(&mut self) {
        if let Some(ref panel) = self.options_panel {
            self.stroke_settings.color = panel.common.color;
            self.stroke_settings.width = panel.common.stroke_width;
            // Map line style
            use super::options_panel::LineStyle;
            self.stroke_settings.style = match panel.common.line_style {
                LineStyle::Solid => super::stroke::StrokeStyle::Solid,
                LineStyle::Dashed => super::stroke::StrokeStyle::Dashed,
                LineStyle::Dotted => super::stroke::StrokeStyle::Dotted,
                LineStyle::DashDot => super::stroke::StrokeStyle::DashDot,
                LineStyle::DashDotDot => super::stroke::StrokeStyle::DashDotDot,
            };
        }
    }

    /// Get currently hovered button
    pub fn hovered_button(&self) -> Option<&str> {
        self.hovered_button.as_deref()
    }

    /// Handle a window event
    ///
    /// Returns Some(ActionResult) if an action was executed.
    /// Note: CursorMoved events should be handled separately via `handle_cursor_move()`
    /// with pre-converted logical coordinates.
    pub fn handle_event(&mut self, event: &WindowEvent) -> Option<ActionResult> {
        match event {
            WindowEvent::MouseInput { state, button, .. } => {
                self.handle_mouse_button(*button, *state)
            }
            WindowEvent::KeyboardInput { event, .. } => self.handle_keyboard(event),
            _ => None,
        }
    }

    fn handle_mouse_button(
        &mut self,
        button: MouseButton,
        state: ElementState,
    ) -> Option<ActionResult> {
        if button != MouseButton::Left {
            return None;
        }

        match state {
            ElementState::Pressed => {
                match self.state {
                    ModeState::Idle => {
                        // Start selection - position will be set by cursor move
                        self.state = ModeState::Selecting;
                    }
                    ModeState::ToolbarVisible => {
                        // Check if clicking on a resize handle
                        if let Some(pos) = self.last_cursor_pos {
                            if let Some(handle) = self.handle_at_pos(pos) {
                                self.dragging_handle = Some(handle);
                                return None; // Handle drag started
                            }
                        }

                        // Check if clicking on drag handle of action bar
                        if let Some(ref mut bar) = self.action_bar {
                            if let Some(pos) = self.last_cursor_pos {
                                let egui_pos = egui::pos2(pos.0, pos.1);
                                if bar.is_in_drag_handle(egui_pos) {
                                    bar.start_drag(egui_pos);
                                    self.action_bar_dragging = true;
                                    return None;
                                }
                            }
                        }

                        // Check if clicking an action bar button
                        if let Some(ref bar) = self.action_bar {
                            if let Some(pos) = self.last_cursor_pos {
                                if let Some(id) = bar.check_click(egui::pos2(pos.0, pos.1)) {
                                    let id_owned = id.to_string();
                                    return self.execute_action(&id_owned);
                                }
                            }
                        }

                        // Check if clicking on options panel (egui widgets handle interaction)
                        if let Some(ref panel) = self.options_panel {
                            if let Some(pos) = self.last_cursor_pos {
                                let click_pos = egui::pos2(pos.0, pos.1);
                                if panel.contains(click_pos) {
                                    return None; // Let egui handle the click
                                }
                            }
                        }

                        // If any drawing tool is active and clicking in selection area, start drawing
                        // Use the new action-based drawing lifecycle
                        if self.registry.has_active_drawing_tool() {
                            if let Some(pos) = self.last_cursor_pos {
                                if self.is_inside_selection(pos) {
                                    // Sync stroke settings from options panel
                                    self.sync_stroke_settings();

                                    // Record snapshot before starting draw for undo
                                    let snapshot = self.annotations.snapshot();
                                    self.history.record(snapshot);

                                    let egui_pos = egui::pos2(pos.0, pos.1);
                                    let selection_bounds = self.selection.bounds();
                                    let mut draw_ctx = DrawingContext::new(
                                        &mut self.annotations,
                                        &self.stroke_settings,
                                        selection_bounds,
                                        self.scale_factor as f32,
                                    );
                                    self.registry.on_draw_start(egui_pos, &mut draw_ctx);
                                    return None;
                                }
                            }
                        }

                        // Click outside action bar, options panel, and selection - reset
                        if !self.is_inside_selection(self.last_cursor_pos.unwrap_or((0.0, 0.0))) {
                            let click_pos = egui::pos2(
                                self.last_cursor_pos.unwrap_or((0.0, 0.0)).0,
                                self.last_cursor_pos.unwrap_or((0.0, 0.0)).1,
                            );
                            // Check if clicking inside action bar
                            let inside_action_bar = self
                                .action_bar
                                .as_ref()
                                .map(|bar| bar.contains(click_pos))
                                .unwrap_or(false);
                            // Check if clicking inside options panel
                            let inside_options_panel = self
                                .options_panel
                                .as_ref()
                                .map(|panel| panel.contains(click_pos))
                                .unwrap_or(false);
                            if !inside_action_bar && !inside_options_panel {
                                self.selection.reset();
                                self.action_bar = None;
                                self.options_panel = None;
                                self.annotate_active = false;
                                self.state = ModeState::Idle;
                            }
                        }
                    }
                    _ => {}
                }
                None
            }
            ElementState::Released => {
                // Finish handle dragging
                if self.dragging_handle.is_some() {
                    self.dragging_handle = None;
                    self.update_toolbar_position();
                }

                // Finish action bar dragging
                if self.action_bar_dragging {
                    if let Some(ref mut bar) = self.action_bar {
                        bar.stop_drag();
                        // Update options panel position to follow action bar
                        if let Some(ref mut panel) = self.options_panel {
                            panel.update_position(bar.position(), bar.size());
                        }
                    }
                    self.action_bar_dragging = false;
                }

                // Finish any ongoing drawing using the action-based lifecycle
                if self.registry.has_active_drawing_tool() {
                    let selection_bounds = self.selection.bounds();
                    let mut draw_ctx = DrawingContext::new(
                        &mut self.annotations,
                        &self.stroke_settings,
                        selection_bounds,
                        self.scale_factor as f32,
                    );
                    self.registry.on_draw_end(&mut draw_ctx);
                }

                if self.state == ModeState::Selecting {
                    self.selection.finish();

                    // Check if selection is large enough
                    if let Some((w, h)) = self.selection.size() {
                        if w > 5.0 && h > 5.0 {
                            // Create action bar
                            if let Some(bounds) = self.selection.bounds() {
                                let actions = self.registry.get_enabled();
                                // Create new ActionBar
                                let min_pos = egui::pos2(bounds.0.0, bounds.0.1);
                                let max_pos = egui::pos2(bounds.1.0, bounds.1.1);
                                let screen_size_vec =
                                    egui::vec2(self.screen_size.0, self.screen_size.1);
                                self.action_bar = Some(ActionBar::new(
                                    &actions,
                                    (min_pos, max_pos),
                                    screen_size_vec,
                                    self.scale_factor as f32,
                                ));
                                // Also create options panel
                                if let Some(ref bar) = self.action_bar {
                                    self.options_panel =
                                        Some(OptionsPanel::new(bar.position(), bar.size()));
                                }
                                self.state = ModeState::ToolbarVisible;
                            }
                        } else {
                            // Selection too small, reset
                            self.selection.reset();
                            self.state = ModeState::Idle;
                        }
                    } else {
                        self.selection.reset();
                        self.state = ModeState::Idle;
                    }
                }
                None
            }
        }
    }

    /// Check if a position is inside the current selection
    fn is_inside_selection(&self, pos: (f32, f32)) -> bool {
        if let Some(((min_x, min_y), (max_x, max_y))) = self.selection.bounds() {
            pos.0 >= min_x && pos.0 <= max_x && pos.1 >= min_y && pos.1 <= max_y
        } else {
            false
        }
    }

    /// Get the rect for a handle at given position
    fn handle_rect(&self, handle: HandlePosition) -> Option<egui::Rect> {
        let ((min_x, min_y), (max_x, max_y)) = self.selection.bounds()?;
        let mid_x = (min_x + max_x) / 2.0;
        let mid_y = (min_y + max_y) / 2.0;

        let center = match handle {
            HandlePosition::TopLeft => egui::pos2(min_x, min_y),
            HandlePosition::TopCenter => egui::pos2(mid_x, min_y),
            HandlePosition::TopRight => egui::pos2(max_x, min_y),
            HandlePosition::MiddleLeft => egui::pos2(min_x, mid_y),
            HandlePosition::MiddleRight => egui::pos2(max_x, mid_y),
            HandlePosition::BottomLeft => egui::pos2(min_x, max_y),
            HandlePosition::BottomCenter => egui::pos2(mid_x, max_y),
            HandlePosition::BottomRight => egui::pos2(max_x, max_y),
        };

        Some(egui::Rect::from_center_size(center, egui::vec2(HANDLE_SIZE, HANDLE_SIZE)))
    }

    /// Check which handle (if any) is at the given position
    fn handle_at_pos(&self, pos: (f32, f32)) -> Option<HandlePosition> {
        let point = egui::pos2(pos.0, pos.1);
        for handle in HandlePosition::all() {
            if let Some(rect) = self.handle_rect(handle) {
                if rect.contains(point) {
                    return Some(handle);
                }
            }
        }
        None
    }

    /// Update toolbar position after selection resize
    fn update_toolbar_position(&mut self) {
        if let Some(bounds) = self.selection.bounds() {
            let actions = self.registry.get_enabled();
            // Update ActionBar position
            let min_pos = egui::pos2(bounds.0.0, bounds.0.1);
            let max_pos = egui::pos2(bounds.1.0, bounds.1.1);
            let screen_size_vec = egui::vec2(self.screen_size.0, self.screen_size.1);
            self.action_bar = Some(ActionBar::new(
                &actions,
                (min_pos, max_pos),
                screen_size_vec,
                self.scale_factor as f32,
            ));
            // Update options panel position
            if let Some(ref bar) = self.action_bar {
                self.options_panel = Some(OptionsPanel::new(bar.position(), bar.size()));
            }
        }
    }

    /// Handle cursor movement with logical coordinates
    ///
    /// This method expects coordinates already converted to logical pixels
    /// (i.e., physical pixels divided by scale factor).
    pub fn handle_cursor_move(&mut self, pos: (f32, f32)) {
        // Always track cursor position
        self.last_cursor_pos = Some(pos);

        match self.state {
            ModeState::Idle => {
                // Track position for when selection starts
            }
            ModeState::Selecting => {
                if !self.selection.has_selection() {
                    self.selection.start(pos);
                } else {
                    self.selection.update(pos);
                }
            }
            ModeState::ToolbarVisible => {
                // Handle resize drag
                if let Some(handle) = self.dragging_handle {
                    self.selection.resize(handle, pos);
                    return;
                }

                // Handle action bar dragging
                if self.action_bar_dragging {
                    if let Some(ref mut bar) = self.action_bar {
                        let screen_size = egui::vec2(self.screen_size.0, self.screen_size.1);
                        bar.update_drag(egui::pos2(pos.0, pos.1), screen_size);
                        // Update options panel position to follow action bar during drag
                        if let Some(ref mut panel) = self.options_panel {
                            panel.update_position(bar.position(), bar.size());
                        }
                    }
                    return;
                }

                // Update hovered handle for cursor
                self.hovered_handle = self.handle_at_pos(pos);

                // If any drawing tool is active, update the current drawing using action lifecycle
                if self.registry.has_active_drawing_tool() {
                    let egui_pos = egui::pos2(pos.0, pos.1);
                    let selection_bounds = self.selection.bounds();
                    let mut draw_ctx = DrawingContext::new(
                        &mut self.annotations,
                        &self.stroke_settings,
                        selection_bounds,
                        self.scale_factor as f32,
                    );
                    self.registry.on_draw_move(egui_pos, &mut draw_ctx);
                }

                // Update hovered button via action bar
                if let Some(ref mut bar) = self.action_bar {
                    bar.update_hover(egui::pos2(pos.0, pos.1));
                    self.hovered_button = bar.hovered_button().map(|s| s.to_string());
                }
            }
            _ => {}
        }
    }

    fn handle_keyboard(&mut self, event: &winit::event::KeyEvent) -> Option<ActionResult> {
        use winit::keyboard::{Key, NamedKey};

        if event.state != ElementState::Pressed {
            return None;
        }

        match &event.logical_key {
            Key::Named(NamedKey::Escape) => {
                self.state = ModeState::Exiting;
                Some(ActionResult::Exit)
            }
            _ => None,
        }
    }

    fn execute_action(&mut self, id: &str) -> Option<ActionResult> {
        // Create action context with both physical and logical selection bounds
        let selection_physical = self.selection.bounds_physical(self.scale_factor as f32);
        let selection_logical = self.selection.bounds();
        let ctx = ActionContext::new(
            selection_physical,
            selection_logical,
            self.screenshot.as_ref(),
            Some(&self.annotations),
            self.monitor.as_ref(),
            self.scale_factor,
        );

        // Execute action (registry handles mutual exclusion)
        let result = self.registry.execute(id, &ctx);

        // Handle result
        match &result {
            ActionResult::Exit => {
                self.state = ModeState::Exiting;
            }
            ActionResult::Undo => {
                // Perform undo operation
                let current = self.annotations.snapshot();
                if let Some(prev) = self.history.undo(current) {
                    self.annotations.restore(prev);
                    log::info!("Undo performed");
                }
            }
            ActionResult::Redo => {
                // Perform redo operation
                let current = self.annotations.snapshot();
                if let Some(next) = self.history.redo(current) {
                    self.annotations.restore(next);
                    log::info!("Redo performed");
                }
            }
            ActionResult::Continue => {
                // Update annotate_active based on registry state
                self.annotate_active = self.registry.is_tool_active("annotate");

                // Sync stroke settings when activating annotate tool
                if id == "annotate" && self.annotate_active {
                    self.sync_stroke_settings();
                }
            }
            _ => {}
        }

        Some(result)
    }

    /// Render the screenshot mode overlay
    pub fn render(&mut self, ctx: &egui::Context) {
        // Use egui's actual screen rect instead of calculated screen_size
        // This ensures the overlay covers the full window regardless of size differences
        #[allow(deprecated)]
        let screen_rect = ctx.input(|i| i.screen_rect());

        egui::Area::new(egui::Id::new("screenshot_overlay")).fixed_pos(egui::pos2(0.0, 0.0)).show(
            ctx,
            |ui| {
                // Draw semi-transparent overlay
                let overlay_color = egui::Color32::from_rgba_unmultiplied(0, 0, 0, 100);

                if let Some(((min_x, min_y), (max_x, max_y))) = self.selection.bounds() {
                    // Draw overlay around selection (4 rectangles)
                    let selection_rect = egui::Rect::from_min_max(
                        egui::pos2(min_x, min_y),
                        egui::pos2(max_x, max_y),
                    );

                    // Top
                    ui.painter().rect_filled(
                        egui::Rect::from_min_max(
                            screen_rect.min,
                            egui::pos2(screen_rect.max.x, selection_rect.min.y),
                        ),
                        egui::CornerRadius::ZERO,
                        overlay_color,
                    );
                    // Bottom
                    ui.painter().rect_filled(
                        egui::Rect::from_min_max(
                            egui::pos2(screen_rect.min.x, selection_rect.max.y),
                            screen_rect.max,
                        ),
                        egui::CornerRadius::ZERO,
                        overlay_color,
                    );
                    // Left
                    ui.painter().rect_filled(
                        egui::Rect::from_min_max(
                            egui::pos2(screen_rect.min.x, selection_rect.min.y),
                            egui::pos2(selection_rect.min.x, selection_rect.max.y),
                        ),
                        egui::CornerRadius::ZERO,
                        overlay_color,
                    );
                    // Right
                    ui.painter().rect_filled(
                        egui::Rect::from_min_max(
                            egui::pos2(selection_rect.max.x, selection_rect.min.y),
                            egui::pos2(screen_rect.max.x, selection_rect.max.y),
                        ),
                        egui::CornerRadius::ZERO,
                        overlay_color,
                    );

                    // Draw selection border
                    ui.painter().rect_stroke(
                        selection_rect,
                        egui::CornerRadius::ZERO,
                        egui::Stroke::new(2.0, egui::Color32::from_rgb(0, 120, 255)),
                        egui::StrokeKind::Outside,
                    );

                    // Note: Size indicator moved to top-left settings toolbar

                    // Render annotations inside selection area
                    self.render_annotations(ui);

                    // Render resize handles when toolbar is visible
                    if self.state == ModeState::ToolbarVisible {
                        self.render_handles(ui);
                    }
                } else {
                    // No selection - full overlay
                    ui.painter().rect_filled(screen_rect, egui::CornerRadius::ZERO, overlay_color);
                }

                // Render new action bar if visible
                if let Some(ref mut bar) = self.action_bar {
                    // Get the active drawing/privacy tool from registry
                    let active_tool = self
                        .registry
                        .get_active_tool(ToolCategory::Drawing)
                        .or_else(|| self.registry.get_active_tool(ToolCategory::Privacy));
                    let can_undo = self.history.can_undo();
                    let can_redo = self.history.can_redo();
                    bar.render(ui, active_tool, can_undo, can_redo);
                }

                // Render options panel if a drawing tool is active
                if let Some(ref mut panel) = self.options_panel {
                    let active_tool = self
                        .registry
                        .get_active_tool(ToolCategory::Drawing)
                        .or_else(|| self.registry.get_active_tool(ToolCategory::Privacy));
                    if let Some(tool_id) = active_tool {
                        panel.set_tool(tool_id);
                        panel.render(ui);
                    }
                }
            },
        );

        // Render settings toolbar (top-left, above selection) with coords and resolution
        if self.state == ModeState::ToolbarVisible {
            if let Some(((min_x, min_y), (max_x, max_y))) = self.selection.bounds() {
                // Calculate start coordinates in physical pixels
                let start_x = (min_x * self.scale_factor as f32) as i32;
                let start_y = (min_y * self.scale_factor as f32) as i32;

                // Calculate resolution in physical pixels
                let width = ((max_x - min_x) * self.scale_factor as f32) as u32;
                let height = ((max_y - min_y) * self.scale_factor as f32) as u32;

                self.settings_toolbar.update_position((min_x, min_y));
                if let Some(button) = self.settings_toolbar.render(
                    ctx,
                    &mut self.settings,
                    (start_x, start_y),
                    (width, height),
                ) {
                    match button {
                        SettingsButton::Refresh => {
                            self.refresh_screenshot();
                        }
                    }
                }
            }
        }
    }

    /// Render all annotations using the action registry
    fn render_annotations(&self, ui: &egui::Ui) {
        let ctx = RenderContext::new(ui, &self.annotations, self.scale_factor as f32);
        self.registry.render_all_annotations(&ctx);
    }

    /// Re-capture the screen
    fn refresh_screenshot(&mut self) {
        if let Some(ref monitor) = self.monitor {
            if let Ok(new_screenshot) = monitor.capture_image() {
                self.screenshot = Some(new_screenshot);
                log::info!("Screenshot refreshed");
            } else {
                log::warn!("Failed to refresh screenshot");
            }
        }
    }

    /// Render resize handles at selection corners and edges
    fn render_handles(&self, ui: &egui::Ui) {
        for handle in HandlePosition::all() {
            if let Some(rect) = self.handle_rect(handle) {
                let is_hovered = self.hovered_handle == Some(handle);
                let fill = if is_hovered {
                    egui::Color32::from_rgb(0, 150, 255)
                } else {
                    egui::Color32::WHITE
                };
                ui.painter().rect_filled(rect, 2.0, fill);
                ui.painter().rect_stroke(
                    rect,
                    2.0,
                    egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 255)),
                    egui::StrokeKind::Outside,
                );
            }
        }
    }
}