term39 1.5.1

A modern, retro-styled terminal multiplexer with a classic MS-DOS aesthetic
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
use crate::app::{AppConfig, AppState};
use crate::input::mouse_handlers::{
    ModalMouseResult, SystemMenuResult, TopBarClickResult, handle_about_window_mouse,
    handle_auto_tiling_click, handle_calendar_mouse, handle_config_window_mouse,
    handle_context_menu_mouse, handle_error_dialog_mouse, handle_help_window_mouse,
    handle_pin_setup_mouse, handle_prompt_mouse, handle_selection_mouse, handle_system_menu_mouse,
    handle_taskbar_menu_mouse, handle_topbar_click, handle_winmode_help_window_mouse,
    show_context_menu, show_taskbar_menu, update_bar_button_hover_states,
};
use crate::lockscreen::PinSetupState;
use crate::rendering::RenderBackend;
use crate::ui::config_action_handler::{apply_config_result, process_config_action};
use crate::ui::config_window::ConfigWindow;
use crate::ui::prompt::{Prompt, PromptAction, PromptButton, PromptType};
use crate::ui::slight_input::SlightInput;
use crate::utils::{ClipboardManager, CommandHistory, CommandIndexer};
use crate::window::{FocusState, WindowManager};
use crossterm::{
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind},
    terminal::{self, ClearType},
};
use std::io;
use std::time::{Duration, Instant};

/// Windows: Dedicated input thread to prevent event loss
/// Reads events continuously and sends via channel
#[cfg(target_os = "windows")]
use std::sync::mpsc::{self, Receiver, TryRecvError};

#[cfg(target_os = "windows")]
fn spawn_input_thread() -> Receiver<Event> {
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        loop {
            // Block until event is available
            if event::poll(Duration::from_millis(100)).unwrap_or(false) {
                if let Ok(evt) = event::read() {
                    if tx.send(evt).is_err() {
                        break; // Channel closed, exit thread
                    }
                }
            }
        }
    });
    rx
}

#[allow(clippy::too_many_arguments)]
pub fn run(
    backend: &mut Box<dyn RenderBackend>,
    video_buffer: &mut crate::rendering::VideoBuffer,
    stdout: &mut io::Stdout,
    window_manager: &mut WindowManager,
    app_state: &mut AppState,
    app_config: &mut AppConfig,
    charset: &mut crate::rendering::Charset,
    theme: &mut crate::rendering::Theme,
    keybinding_profile: &mut crate::input::keybinding_profile::KeybindingProfile,
    mouse_input_manager: &mut crate::input::mouse::MouseInputManager,
    cli_args: &crate::app::cli::Cli,
    command_indexer: &CommandIndexer,
    command_history: &mut CommandHistory,
    clipboard_manager: &mut ClipboardManager,
    #[cfg(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    ))]
    #[allow(unused_variables)]
    _gpm_disable_connection: &Option<crate::input::gpm_control::GpmConnection>,
    #[cfg(not(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    )))]
    #[allow(unused_variables)]
    _gpm_disable_connection: &Option<()>,
) -> io::Result<()> {
    // Load framebuffer configuration (for swap_buttons, etc.)
    #[cfg(all(target_os = "linux", feature = "framebuffer-backend"))]
    #[allow(unused_variables)] // Only used on Linux with framebuffer
    let fb_config = crate::framebuffer::fb_config::FramebufferConfig::load();

    // Windows: spawn dedicated input thread to prevent event loss
    #[cfg(target_os = "windows")]
    let input_rx = spawn_input_thread();

    // Main loop
    loop {
        // Check for external lock request (via SIGUSR1 signal)
        if crate::lockscreen::signal_handler::check_and_clear() {
            if app_state.lockscreen.is_available() {
                app_state.lockscreen.lock();
            }
        }

        // Update lockscreen state (check lockout timer)
        app_state.lockscreen.update();
        // Check if backend was resized and recreate buffer if needed
        if let Some((new_cols, new_rows)) = backend.check_resize()? {
            // Clear the terminal screen to remove artifacts
            use crossterm::execute;
            execute!(stdout, terminal::Clear(ClearType::All))?;
            *video_buffer = crate::app::initialization::initialize_video_buffer(backend.as_ref());
            app_state.update_auto_tiling_button_position(new_rows);

            // Update mouse input manager bounds for the new size
            mouse_input_manager.set_bounds(new_cols, new_rows);

            // Reposition windows to fit the new screen dimensions
            if app_state.auto_tiling_enabled {
                window_manager.auto_position_windows(new_cols, new_rows, app_config.tiling_gaps);
            } else {
                // Clamp windows to new screen bounds
                window_manager.clamp_windows_to_bounds(new_cols, new_rows);
            }
        }

        // Get current dimensions from backend
        let (cols, _rows) = backend.dimensions();

        // Update clipboard buttons state and position
        let has_clipboard_content = clipboard_manager.has_content();
        let has_selection = window_manager.focused_window_has_meaningful_selection();
        app_state.update_button_states(cols, has_clipboard_content, has_selection);

        // Render the complete frame
        let windows_closed = crate::rendering::render_frame(
            video_buffer,
            backend,
            stdout,
            window_manager,
            app_state,
            charset,
            theme,
            app_config,
            has_clipboard_content,
            has_selection,
        )?;

        // Auto-reposition remaining windows if any were closed
        if windows_closed && app_state.auto_tiling_enabled {
            let (cols, rows) = backend.dimensions();
            window_manager.auto_position_windows(cols, rows, app_config.tiling_gaps);
        }

        // Poll unified mouse input manager for raw input events (TTY mode only)
        // Skip this for framebuffer mode - it has its own native mouse input
        let raw_mouse_event =
            if mouse_input_manager.uses_raw_input() && !backend.has_native_mouse_input() {
                if let Ok(Some(event)) = mouse_input_manager.poll_event() {
                    // Update TTY cursor position for display
                    let (cursor_col, cursor_row) = mouse_input_manager.cursor_position();
                    backend.set_tty_cursor(cursor_col, cursor_row);
                    Some(Event::Mouse(event))
                } else {
                    None
                }
            } else if !backend.has_native_mouse_input() {
                // In terminal emulator mode, clear any TTY cursor
                backend.clear_tty_cursor();
                None
            } else {
                // Framebuffer mode handles mouse input natively
                None
            };

        // Process raw mouse event if available (from MouseInputManager)
        #[cfg(target_os = "linux")]
        let mut injected_event: Option<Event> = raw_mouse_event;
        #[cfg(not(target_os = "linux"))]
        let _injected_event: Option<Event> = raw_mouse_event;

        // Process framebuffer mouse events if available
        #[cfg(all(target_os = "linux", feature = "framebuffer-backend"))]
        if injected_event.is_none() {
            if let Some((event_type, button_id, col, row)) = backend.get_mouse_button_event() {
                injected_event = Some(crate::input::mouse_handlers::map_fb_button_event(
                    event_type,
                    button_id,
                    col,
                    row,
                    fb_config.mouse.swap_buttons,
                ));
            }
        }

        #[cfg(all(target_os = "linux", feature = "framebuffer-backend"))]
        if injected_event.is_none() {
            if let Some((scroll_direction, col, row)) = backend.get_mouse_scroll_event() {
                injected_event = Some(crate::input::mouse_handlers::map_fb_scroll_event(
                    scroll_direction,
                    col,
                    row,
                ));
            }
        }

        // Process all available events before next frame (batch processing for responsiveness)
        const MAX_EVENTS_PER_FRAME: usize = 50;
        let mut events_processed = 0;
        let mut should_break_main_loop = false;

        while events_processed < MAX_EVENTS_PER_FRAME {
            // Windows: read from dedicated input thread via channel
            #[cfg(target_os = "windows")]
            let current_event = {
                if events_processed == 0 {
                    // First iteration: wait briefly for an event
                    match input_rx.recv_timeout(Duration::from_millis(16)) {
                        Ok(evt) => evt,
                        Err(_) => break, // No event within timeout
                    }
                } else {
                    // Subsequent: non-blocking check for more events
                    match input_rx.try_recv() {
                        Ok(evt) => evt,
                        Err(TryRecvError::Empty) => break,
                        Err(TryRecvError::Disconnected) => break,
                    }
                }
            };
            #[cfg(target_os = "windows")]
            let is_injected = false;
            #[cfg(target_os = "windows")]
            {
                events_processed += 1;
            }

            // Non-Windows: use standard poll/read
            #[cfg(not(target_os = "windows"))]
            let poll_timeout = if events_processed == 0 {
                Duration::from_millis(16) // ~60fps frame timing
            } else {
                Duration::from_millis(0) // Non-blocking for subsequent events
            };

            #[cfg(all(not(target_os = "windows"), target_os = "linux"))]
            let has_event = injected_event.is_some() || event::poll(poll_timeout)?;
            #[cfg(all(not(target_os = "windows"), not(target_os = "linux")))]
            let has_event = event::poll(poll_timeout)?;

            #[cfg(not(target_os = "windows"))]
            if !has_event {
                break; // No more events available
            }

            events_processed += 1;

            // Track whether this event is injected (raw/FB) to avoid double-scaling
            #[cfg(all(not(target_os = "windows"), target_os = "linux"))]
            let is_injected = injected_event.is_some();
            #[cfg(all(not(target_os = "windows"), not(target_os = "linux")))]
            let is_injected = false;

            #[cfg(all(not(target_os = "windows"), target_os = "linux"))]
            let current_event = if let Some(evt) = injected_event.take() {
                evt
            } else {
                event::read()?
            };
            #[cfg(all(not(target_os = "windows"), not(target_os = "linux")))]
            let current_event = event::read()?;

            match current_event {
                Event::Key(key_event) => {
                    // Always skip Release events on all platforms
                    if key_event.kind == KeyEventKind::Release {
                        continue;
                    }

                    // Windows: Don't filter any key events except Release
                    // ConPTY/crossterm behavior is inconsistent - better to pass all events
                    // and let duplicates happen than to drop legitimate keystrokes

                    // Non-Windows: filter Repeat events for character keys
                    #[cfg(not(target_os = "windows"))]
                    if key_event.kind == KeyEventKind::Repeat {
                        let is_navigation_key = matches!(
                            key_event.code,
                            KeyCode::Up
                                | KeyCode::Down
                                | KeyCode::Left
                                | KeyCode::Right
                                | KeyCode::PageUp
                                | KeyCode::PageDown
                                | KeyCode::Home
                                | KeyCode::End
                                | KeyCode::Backspace
                                | KeyCode::Delete
                        );
                        if !is_navigation_key {
                            continue;
                        }
                    }

                    let current_focus = window_manager.get_focus();

                    // Handle lockscreen keyboard events (highest priority - blocks all other input)
                    if crate::ui::dialog_handlers::handle_lockscreen_keyboard(app_state, key_event)
                    {
                        continue;
                    }

                    // F12 - Global lockscreen shortcut (works from anywhere, even in terminal)
                    if key_event.code == KeyCode::F(12) {
                        if app_config.lockscreen_enabled && app_state.lockscreen.is_available() {
                            app_state.lockscreen.lock();
                        } else {
                            // Show toast: "To lock the screen, configure in Settings"
                            app_state.active_toast = Some(crate::ui::toast::Toast::new(
                                "To lock the screen, configure in Settings",
                            ));
                        }
                        continue;
                    }

                    // Dismiss toast on any key press (if active and not just created)
                    // Check if toast was created more than 100ms ago to avoid dismissing
                    // toasts that were just created by the same key press
                    if let Some(ref toast) = app_state.active_toast {
                        if toast.created_at.elapsed() > std::time::Duration::from_millis(100) {
                            app_state.active_toast = None;
                        }
                    }

                    // Handle prompt keyboard navigation
                    if let Some(should_exit) =
                        crate::ui::dialog_handlers::handle_prompt_keyboard(app_state, key_event)
                    {
                        if should_exit {
                            should_break_main_loop = true;
                            break;
                        }
                        continue;
                    }

                    // Handle close confirmation keyboard events (window-specific modal)
                    if let FocusState::Window(window_id) = current_focus {
                        if let Some(should_close) =
                            window_manager.handle_close_confirmation_key(window_id, key_event)
                        {
                            if should_close {
                                // User confirmed close
                                window_manager.close_window(window_id);
                                if app_state.auto_tiling_enabled {
                                    let (cols, rows) = backend.dimensions();
                                    window_manager.auto_position_windows(
                                        cols,
                                        rows,
                                        app_config.tiling_gaps,
                                    );
                                }
                            }
                            continue; // Handled
                        }
                    }

                    // Handle error dialog keyboard events
                    if crate::ui::dialog_handlers::handle_error_dialog_keyboard(
                        app_state, key_event,
                    ) {
                        continue;
                    }

                    // Handle PIN setup dialog keyboard events
                    if let Some(ref mut pin_setup) = app_state.active_pin_setup {
                        pin_setup.handle_key(key_event);
                        match pin_setup.state().clone() {
                            PinSetupState::Complete { hash, salt } => {
                                // Save PIN to config
                                app_config.set_pin(hash, salt);
                                app_state.update_lockscreen_auth(app_config);
                                app_state.active_pin_setup = None;
                            }
                            PinSetupState::Cancelled => {
                                app_state.active_pin_setup = None;
                            }
                            _ => {}
                        }
                        continue;
                    }

                    // Handle Slight input keyboard events
                    if crate::ui::dialog_handlers::handle_slight_input_keyboard(
                        app_state,
                        key_event,
                        command_indexer,
                        command_history,
                        window_manager,
                        backend.as_ref(),
                        app_config.tiling_gaps,
                    ) {
                        continue;
                    }

                    // Handle calendar keyboard navigation
                    if crate::ui::dialog_handlers::handle_calendar_keyboard(app_state, key_event) {
                        continue;
                    }

                    // Handle help window keyboard events
                    if crate::ui::dialog_handlers::handle_help_window_keyboard(app_state, key_event)
                    {
                        continue;
                    }

                    // Handle about window keyboard events
                    if crate::ui::dialog_handlers::handle_about_window_keyboard(
                        app_state, key_event,
                    ) {
                        continue;
                    }

                    // Handle config window keyboard events
                    if let Some(action) = crate::ui::dialog_handlers::handle_config_window_keyboard(
                        app_state, key_event, app_config,
                    ) {
                        let (_, rows) = backend.dimensions();
                        let result = process_config_action(action, app_state, app_config, rows);
                        apply_config_result(&result, charset, theme, keybinding_profile);
                        continue;
                    }

                    // Handle Window Mode help window keyboard events
                    if crate::ui::dialog_handlers::handle_winmode_help_window_keyboard(
                        app_state, key_event,
                    ) {
                        continue;
                    }

                    // Handle Window Mode keyboard events (vim-like window control)
                    if crate::window::mode_handlers::handle_window_mode_keyboard(
                        app_state,
                        app_config,
                        key_event,
                        window_manager,
                        backend.as_ref(),
                        keybinding_profile,
                    ) {
                        continue;
                    }

                    // Handle CTRL+Space / Option+Space to open Slight input popup (needs inline access to command_indexer/history)
                    // Note: Ctrl+Space produces NUL character ('\0') in most terminals
                    // On macOS, Option+Space produces non-breaking space (U+00A0)
                    let is_launcher_shortcut = (key_event.code == KeyCode::Char(' ')
                        && (key_event.modifiers.contains(KeyModifiers::CONTROL)
                            || key_event.modifiers.contains(KeyModifiers::ALT)))
                        || key_event.code == KeyCode::Char('\0')
                        || key_event.code == KeyCode::Char('\u{00a0}'); // Non-breaking space from Option+Space on macOS
                    if is_launcher_shortcut {
                        let (cols, rows) = backend.dimensions();
                        let mut slight_input = SlightInput::new(cols, rows);
                        slight_input
                            .set_autocomplete(command_indexer.clone(), command_history.clone());
                        app_state.active_slight_input = Some(slight_input);
                        continue;
                    }

                    // Handle desktop keyboard shortcuts (F1-F7, ESC, 'q', 'h', 'l', 'c', 's', 't', 'T', copy/paste)
                    if crate::input::keyboard_handlers::handle_desktop_keyboard(
                        app_state,
                        key_event,
                        current_focus,
                        window_manager,
                        clipboard_manager,
                        backend.as_ref(),
                        app_config,
                        cli_args,
                        keybinding_profile,
                    ) {
                        // Check if exit was requested
                        if app_state.should_exit {
                            should_break_main_loop = true;
                            break;
                        }
                        continue;
                    }

                    // Forward input to terminal window if a window is focused
                    if matches!(current_focus, FocusState::Window(_)) {
                        crate::input::keyboard_handlers::forward_to_terminal(
                            key_event,
                            window_manager,
                        );
                    }
                }
                Event::Mouse(mut mouse_event) => {
                    // Scale mouse coordinates from TTY space to backend space
                    // Only scale crossterm mouse events, not injected GPM/FB events
                    // (injected events are already scaled at injection time)
                    if !is_injected {
                        let (scaled_col, scaled_row) =
                            backend.scale_mouse_coords(mouse_event.column, mouse_event.row);
                        mouse_event.column = scaled_col;
                        mouse_event.row = scaled_row;
                    }

                    let (_, rows) = backend.dimensions();
                    let bar_y = rows - 1;

                    let mut handled = false;

                    // Handle modal dialogs (prompt, PIN setup, error, config window)
                    match handle_prompt_mouse(app_state, &mouse_event, charset) {
                        ModalMouseResult::Exit => {
                            should_break_main_loop = true;
                            break;
                        }
                        ModalMouseResult::Handled => handled = true,
                        ModalMouseResult::NotHandled => {}
                    }

                    let (cols, rows) = backend.dimensions();
                    if !handled
                        && handle_pin_setup_mouse(
                            app_state,
                            app_config,
                            &mouse_event,
                            cols,
                            rows,
                            charset,
                        )
                    {
                        handled = true;
                    }

                    if !handled && handle_error_dialog_mouse(app_state, &mouse_event) {
                        handled = true;
                    }

                    if !handled
                        && handle_config_window_mouse(
                            app_state,
                            app_config,
                            &mouse_event,
                            rows,
                            charset,
                            theme,
                            keybinding_profile,
                        )
                    {
                        handled = true;
                    }

                    // Handle help window mouse events
                    if !handled && handle_help_window_mouse(app_state, &mouse_event) {
                        handled = true;
                    }

                    // Handle about window mouse events
                    if !handled && handle_about_window_mouse(app_state, &mouse_event) {
                        handled = true;
                    }

                    // Handle window mode help window mouse events
                    if !handled && handle_winmode_help_window_mouse(app_state, &mouse_event) {
                        handled = true;
                    }

                    // Handle calendar mouse events
                    if !handled && handle_calendar_mouse(app_state, &mouse_event, cols, rows) {
                        handled = true;
                    }

                    // Update button hover states (always active)
                    if !handled {
                        // Get clipboard and selection state for hover updates
                        let hover_clipboard = clipboard_manager.has_content();
                        let hover_selection =
                            window_manager.focused_window_has_meaningful_selection();
                        let focus = window_manager.get_focus();
                        update_bar_button_hover_states(
                            app_state,
                            mouse_event.column,
                            mouse_event.row,
                            cols,
                            rows,
                            app_config.show_date_in_clock,
                            hover_clipboard,
                            hover_selection,
                            focus,
                            charset,
                        );
                    }

                    // Handle top bar button clicks (if no prompt active)
                    if !handled && app_state.active_prompt.is_none() {
                        match handle_topbar_click(
                            app_state,
                            window_manager,
                            clipboard_manager,
                            &mouse_event,
                            cols,
                            rows,
                            app_config.tiling_gaps,
                            cli_args.no_exit,
                            app_config.show_date_in_clock,
                        ) {
                            TopBarClickResult::Handled => handled = true,
                            TopBarClickResult::NotHandled => {}
                        }
                    }

                    // Handle auto-tiling toggle button click
                    if !handled
                        && app_state.active_prompt.is_none()
                        && handle_auto_tiling_click(app_state, app_config, &mouse_event, rows)
                    {
                        handled = true;
                    }

                    // Check if click is on button bar (only if no prompt)
                    if !handled
                        && app_state.active_prompt.is_none()
                        && mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
                    {
                        // Calculate where window buttons start (after auto-tiling button)
                        // Format: "[label ]" + 2 spaces
                        let window_buttons_start =
                            1 + 1 + app_state.auto_tiling_button.label.len() as u16 + 1 + 2;

                        handled = window_manager
                            .button_bar_click(
                                mouse_event.column,
                                bar_y,
                                mouse_event.row,
                                window_buttons_start,
                            )
                            .is_some();
                    }

                    // Handle right-click on button bar for taskbar context menu
                    if !handled && app_state.active_prompt.is_none() {
                        let window_buttons_start =
                            1 + 1 + app_state.auto_tiling_button.label.len() as u16 + 1 + 2;
                        if show_taskbar_menu(
                            app_state,
                            window_manager,
                            &mouse_event,
                            bar_y,
                            window_buttons_start,
                        ) {
                            handled = true;
                        }
                    }

                    // Handle right-click for context menu (inside windows)
                    if !handled
                        && app_state.active_prompt.is_none()
                        && show_context_menu(app_state, window_manager, &mouse_event)
                    {
                        handled = true;
                    }

                    // Handle context menu interactions
                    if !handled
                        && handle_context_menu_mouse(
                            app_state,
                            window_manager,
                            clipboard_manager,
                            &mouse_event,
                        )
                    {
                        handled = true;
                    }

                    // Handle taskbar menu interactions
                    if !handled
                        && handle_taskbar_menu_mouse(
                            app_state,
                            window_manager,
                            &mouse_event,
                            cols,
                            rows,
                            app_config.tiling_gaps,
                        )
                    {
                        handled = true;
                    }

                    // Handle system menu interactions
                    if !handled {
                        match handle_system_menu_mouse(
                            app_state,
                            window_manager,
                            clipboard_manager,
                            &mouse_event,
                        ) {
                            SystemMenuResult::Handled => handled = true,
                            SystemMenuResult::ShowSettings => {
                                // Open the config window (same as pressing 's' on desktop)
                                app_state.active_config_window =
                                    Some(ConfigWindow::new(cols, rows));
                                handled = true;
                            }
                            SystemMenuResult::ShowHelp => {
                                // Open the help window (same as pressing '?' on desktop)
                                crate::input::keyboard_handlers::show_help_window(
                                    app_state,
                                    backend.as_ref(),
                                    keybinding_profile,
                                );
                                handled = true;
                            }
                            SystemMenuResult::ShowAbout => {
                                // Open the about window (same as pressing 'l' on desktop)
                                crate::input::keyboard_handlers::show_about_window(
                                    app_state,
                                    backend.as_ref(),
                                );
                                handled = true;
                            }
                            SystemMenuResult::ShowExitPrompt => {
                                // Build exit confirmation message
                                let window_count = window_manager.window_count();
                                let message = if window_count > 0 {
                                    format!(
                                        "You have {} open terminal{}. Are you sure you want to exit?",
                                        window_count,
                                        if window_count == 1 { "" } else { "s" }
                                    )
                                } else {
                                    "Are you sure you want to exit?".to_string()
                                };

                                let mut buttons = vec![
                                    PromptButton::new(
                                        "Cancel".to_string(),
                                        PromptAction::Cancel,
                                        false,
                                    ),
                                    PromptButton::new(
                                        "Exit".to_string(),
                                        PromptAction::Confirm,
                                        true,
                                    ),
                                ];
                                // Add "Exit & Kill Daemon" option when persist mode is active and enabled
                                #[cfg(unix)]
                                if app_config.persist_enabled && window_manager.has_persist_client()
                                {
                                    buttons.push(PromptButton::new(
                                        "Exit & Kill Daemon".to_string(),
                                        PromptAction::Custom(1),
                                        true,
                                    ));
                                }

                                app_state.active_prompt = Some(
                                    Prompt::new(PromptType::Danger, message, buttons, cols, rows)
                                        .with_selection_indicators(true)
                                        .with_selected_button(0),
                                );
                                handled = true;
                            }
                            SystemMenuResult::NotHandled => {}
                        }
                    }

                    // Handle text selection (left-click, drag, mouse forwarding)
                    // Skip selection handling if clicking on the pivot (let window manager handle it)
                    let on_pivot = app_state.auto_tiling_enabled
                        && app_config.tiling_gaps
                        && window_manager.is_point_on_pivot(
                            mouse_event.column,
                            mouse_event.row,
                            cols,
                            rows,
                            app_config.tiling_gaps,
                        );
                    if !handled
                        && !on_pivot
                        && app_state.active_prompt.is_none()
                        && !app_state.context_menu.visible
                        && handle_selection_mouse(app_state, window_manager, &mouse_event)
                    {
                        handled = true;
                    }

                    // If not handled by buttons, let window manager handle it (only if no prompt)
                    if !handled
                        && app_state.active_prompt.is_none()
                        && !app_state.context_menu.visible
                    {
                        let window_closed = window_manager.handle_mouse_event(
                            video_buffer,
                            mouse_event,
                            charset,
                            app_config.tiling_gaps,
                            app_state.auto_tiling_enabled,
                        );
                        // Auto-reposition remaining windows if a window was closed
                        if window_closed && app_state.auto_tiling_enabled {
                            let (cols, rows) = backend.dimensions();
                            window_manager.auto_position_windows(
                                cols,
                                rows,
                                app_config.tiling_gaps,
                            );
                        }
                    }

                    // Check if exit was requested (from Exit button)
                    if app_state.should_exit {
                        should_break_main_loop = true;
                        break;
                    }
                }
                _ => {}
            }
        } // End of while events loop

        // Process auto-scroll during selection (frame-based timing)
        if app_state.selection_active {
            if let Some(direction) = app_state.auto_scroll_direction {
                let now = Instant::now();
                let should_scroll = match app_state.last_auto_scroll_time {
                    Some(last_time) => {
                        // Scroll every 50ms (~20 scrolls/sec at 3 lines = 60 lines/sec)
                        now.duration_since(last_time).as_millis() >= 50
                    }
                    None => true, // First scroll happens immediately
                };

                if should_scroll {
                    if let FocusState::Window(window_id) = window_manager.get_focus() {
                        window_manager.auto_scroll_with_selection(window_id, direction);
                        app_state.last_auto_scroll_time = Some(now);
                    }
                }
            }
        }

        // Poll persist daemon for PTY output and events (Unix persist mode)
        #[cfg(unix)]
        {
            let persist_events = window_manager.poll_persist_messages();
            for event in persist_events {
                match event {
                    crate::window::manager::PersistEvent::WindowClosed(window_id) => {
                        window_manager.close_window(window_id);
                        if app_state.auto_tiling_enabled {
                            let (cols, rows) = backend.dimensions();
                            window_manager.auto_position_windows(
                                cols,
                                rows,
                                app_config.tiling_gaps,
                            );
                        }
                    }
                    crate::window::manager::PersistEvent::DaemonDied => {
                        // Daemon died - show notification
                        app_state.active_toast =
                            Some(crate::ui::toast::Toast::new("Daemon connection lost"));
                    }
                    crate::window::manager::PersistEvent::Error(msg) => {
                        app_state.active_toast =
                            Some(crate::ui::toast::Toast::new(format!("Daemon: {msg}")));
                    }
                    _ => {}
                }
            }
        }

        // Flush all buffered terminal input once after processing the event batch
        // This avoids per-keystroke I/O overhead (especially important on Windows)
        window_manager.flush_all_terminal_input();

        // Check if we need to exit the main loop
        if should_break_main_loop {
            break;
        }
    }

    Ok(())
}