par-term 0.29.1

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! WindowEvent routing and dispatch for WindowState.
//!
//! Contains:
//! - `handle_window_event`: routes winit WindowEvents to terminal/renderer handlers,
//!   including close, resize, scale factor change, keyboard, mouse, focus, redraw, theme change.

use crate::app::window_state::WindowState;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;

impl WindowState {
    /// Handle window events for this window state
    pub(crate) fn handle_window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        event: WindowEvent,
    ) -> bool {
        use winit::keyboard::{Key, NamedKey};

        // Let egui handle the event (needed for proper rendering state)
        let (egui_consumed, egui_needs_repaint) =
            if let (Some(egui_state), Some(window)) = (&mut self.egui.state, &self.window) {
                let event_response = egui_state.on_window_event(window, &event);
                // Request redraw if egui needs it (e.g., text input in modals)
                if event_response.repaint {
                    window.request_redraw();
                }
                (event_response.consumed, event_response.repaint)
            } else {
                (false, false)
            };
        let _ = egui_needs_repaint; // Used above, silence unused warning

        // Debug: Log when egui consumes events but we ignore it
        let any_ui_visible = self.any_modal_ui_visible();
        if egui_consumed
            && !any_ui_visible
            && let WindowEvent::KeyboardInput {
                event: key_event, ..
            } = &event
            && let Key::Named(NamedKey::Space) = &key_event.logical_key
        {
            log::debug!("egui tried to consume Space (UI closed, ignoring)");
        }

        // When shader editor is visible, block keyboard events from terminal
        // even if egui didn't consume them (egui might not have focus)
        if any_ui_visible
            && let WindowEvent::KeyboardInput {
                event: key_event, ..
            } = &event
            // Always block keyboard input when UI is visible (except system keys)
            && !matches!(
                key_event.logical_key,
                Key::Named(NamedKey::F1)
                    | Key::Named(NamedKey::F2)
                    | Key::Named(NamedKey::F3)
                    | Key::Named(NamedKey::F11)
                    | Key::Named(NamedKey::Escape)
            )
        {
            return false;
        }

        if egui_consumed
            && any_ui_visible
            && !matches!(
                event,
                WindowEvent::CloseRequested | WindowEvent::RedrawRequested
            )
        {
            return false; // Event consumed by egui, don't close window
        }

        match event {
            WindowEvent::CloseRequested => {
                log::info!("Close requested for window");

                // Check if prompt_on_quit is enabled and there are active sessions
                let tab_count = self.tab_manager.visible_tab_count();
                if self.config.prompt_on_quit
                    && tab_count > 0
                    && !self.overlay_ui.quit_confirmation_ui.is_visible()
                {
                    log::info!(
                        "Showing quit confirmation dialog ({} active sessions)",
                        tab_count
                    );
                    self.overlay_ui
                        .quit_confirmation_ui
                        .show_confirmation(tab_count);
                    self.focus_state.needs_redraw = true;
                    self.request_redraw();
                    return false; // Don't close yet - wait for user confirmation
                }

                self.perform_shutdown();
                return true; // Signal to close this window
            }

            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                if let (Some(renderer), Some(window)) = (&mut self.renderer, &self.window) {
                    log::info!(
                        "Scale factor changed to {} (display change detected)",
                        scale_factor
                    );

                    let size = window.inner_size();
                    let (cols, rows) = renderer.handle_scale_factor_change(scale_factor, size);

                    // Reconfigure surface after scale factor change
                    // This is important when dragging between displays with different DPIs
                    renderer.reconfigure_surface();

                    // Calculate pixel dimensions
                    let cell_width = renderer.cell_width();
                    let cell_height = renderer.cell_height();
                    let width_px = (cols as f32 * cell_width) as usize;
                    let height_px = (rows as f32 * cell_height) as usize;

                    // Resize all tabs' terminals with pixel dimensions for TIOCGWINSZ support
                    for tab in self.tab_manager.tabs_mut() {
                        // try_lock: intentional — resize happens during ScaleFactorChanged
                        // which fires in the sync event loop. On miss: this tab's terminal
                        // keeps its old size until the next resize event. Low risk as scale
                        // factor changes are rare (drag between displays).
                        if let Ok(mut term) = tab.terminal.try_write() {
                            if let Err(e) = term.resize_with_pixels(cols, rows, width_px, height_px)
                            {
                                crate::debug_error!(
                                    "TERMINAL",
                                    "resize_with_pixels failed (scale_factor): {e}"
                                );
                            }
                        } else {
                            crate::debug::record_try_lock_failure("scale_factor_resize");
                        }
                    }

                    // Reconfigure macOS Metal layer after display change
                    #[cfg(target_os = "macos")]
                    {
                        if let Err(e) =
                            crate::macos_metal::configure_metal_layer_for_performance(window)
                        {
                            log::warn!(
                                "Failed to reconfigure Metal layer after display change: {}",
                                e
                            );
                        }
                    }

                    // Request redraw to apply changes
                    window.request_redraw();
                }
            }

            // Handle window moved - surface may become invalid when moving between monitors
            WindowEvent::Moved(_) => {
                if let (Some(renderer), Some(window)) = (&mut self.renderer, &self.window) {
                    log::debug!(
                        "Window moved - reconfiguring surface for potential display change"
                    );

                    // Reconfigure surface to handle potential display changes
                    // This catches cases where displays have same DPI but different surface properties
                    renderer.reconfigure_surface();

                    // On macOS, reconfigure the Metal layer for the potentially new display
                    #[cfg(target_os = "macos")]
                    {
                        if let Err(e) =
                            crate::macos_metal::configure_metal_layer_for_performance(window)
                        {
                            log::warn!(
                                "Failed to reconfigure Metal layer after window move: {}",
                                e
                            );
                        }
                    }

                    // Request redraw to ensure proper rendering on new display
                    window.request_redraw();
                }
            }

            WindowEvent::Resized(physical_size) => {
                if let Some(renderer) = &mut self.renderer {
                    let (cols, rows) = renderer.resize(physical_size);

                    // Calculate text area pixel dimensions
                    let cell_width = renderer.cell_width();
                    let cell_height = renderer.cell_height();
                    let width_px = (cols as f32 * cell_width) as usize;
                    let height_px = (rows as f32 * cell_height) as usize;

                    // Resize all tabs' terminals with pixel dimensions for TIOCGWINSZ support
                    // This allows applications like kitty icat to query pixel dimensions
                    // Note: The core library (v0.11.0+) implements scrollback reflow when
                    // width changes - wrapped lines are unwrapped/re-wrapped as needed.
                    for tab in self.tab_manager.tabs_mut() {
                        // try_lock: intentional — Resized fires in the sync event loop.
                        // On miss: this tab's terminal keeps its old dimensions; the cell
                        // cache is still invalidated below so rendering uses the correct
                        // grid size. The terminal size will be fixed on the next resize event.
                        let new_scrollback_len = if let Ok(mut term) = tab.terminal.try_write() {
                            if let Err(e) = term.resize_with_pixels(cols, rows, width_px, height_px)
                            {
                                crate::debug_error!(
                                    "TERMINAL",
                                    "resize_with_pixels failed (Resized): {e}"
                                );
                            }
                            Some(term.scrollback_len())
                        } else {
                            crate::debug::record_try_lock_failure("resize");
                            None
                        };
                        if let Some(sl) = new_scrollback_len {
                            tab.active_cache_mut().scrollback_len = sl;
                        }
                        // Invalidate cell cache to force regeneration
                        tab.active_cache_mut().cells = None;
                    }

                    // Update scrollbar for active tab
                    if let Some(tab) = self.tab_manager.active_tab() {
                        let total_lines = rows + tab.active_cache().scrollback_len;
                        // try_lock: intentional — scrollbar mark update during Resized event.
                        // On miss: scrollbar renders without marks this frame. Cosmetic only.
                        let marks = tab
                            .try_with_terminal(|term| term.scrollback_marks())
                            .unwrap_or_default();
                        renderer.update_scrollbar(
                            tab.active_scroll_state().offset,
                            rows,
                            total_lines,
                            &marks,
                        );
                    }

                    // Update resize overlay state
                    self.overlay_state.resize_dimensions =
                        Some((physical_size.width, physical_size.height, cols, rows));
                    self.overlay_state.resize_overlay_visible = true;
                    // Hide overlay 1 second after resize stops
                    self.overlay_state.resize_overlay_hide_time =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(1));

                    // Notify tmux of the new size if gateway mode is active
                    self.notify_tmux_of_resize();

                    // --- Snap window to grid cell boundaries ---
                    //
                    // Goal: eliminate the partial-cell gap between the terminal grid
                    // and the window edge that appears after a user drag.
                    //
                    // Anti-loop guard: if this Resized event IS the response to our
                    // own request_inner_size call, skip — we're already at the snapped size.
                    // We allow a ±1 px tolerance because the OS may round to even physical
                    // pixels (e.g. Retina 2× requires integer logical pixels).
                    if let Some(pending) = self.pending_snap_size.take() {
                        let dw = (pending.width as i32 - physical_size.width as i32).unsigned_abs();
                        let dh =
                            (pending.height as i32 - physical_size.height as i32).unsigned_abs();
                        if dw > 1 || dh > 1 {
                            // Not our snap response (concurrent user drag or OS constraint).
                            // Clear pending — the snap logic below will re-evaluate.
                            crate::debug_info!(
                                "RESIZE",
                                "snap guard: pending {}x{} != physical {}x{} (dw={} dh={}), clearing",
                                pending.width,
                                pending.height,
                                physical_size.width,
                                physical_size.height,
                                dw,
                                dh
                            );
                        }
                        // else: this resize was triggered by our own snap request — done.
                    }

                    if self.pending_snap_size.is_none() && self.config.snap_window_to_grid {
                        // Only snap in single-pane mode (split pane handled separately).
                        let is_split = self
                            .tab_manager
                            .active_tab()
                            .map(|t| t.pane_count() > 1)
                            .unwrap_or(false);

                        if !is_split && let Some(renderer) = &self.renderer {
                            let (chrome_x, chrome_y) = renderer.chrome_overhead();
                            let cell_w = renderer.cell_width();
                            let cell_h = renderer.cell_height();
                            let snapped_w = (chrome_x + cols as f32 * cell_w).round() as u32;
                            let snapped_h = (chrome_y + rows as f32 * cell_h).round() as u32;

                            crate::debug_info!(
                                "RESIZE",
                                "snap: physical={}x{} snapped={}x{} chrome=({:.1},{:.1}) cell=({:.1},{:.1}) grid={}x{}",
                                physical_size.width,
                                physical_size.height,
                                snapped_w,
                                snapped_h,
                                chrome_x,
                                chrome_y,
                                cell_w,
                                cell_h,
                                cols,
                                rows
                            );

                            if snapped_w != physical_size.width || snapped_h != physical_size.height
                            {
                                let snapped = winit::dpi::PhysicalSize::new(snapped_w, snapped_h);
                                self.pending_snap_size = Some(snapped);
                                self.with_window(|w| {
                                    let _ = w.request_inner_size(snapped);
                                });
                            }
                        }
                    }
                }
            }

            WindowEvent::KeyboardInput { event, .. } => {
                self.handle_key_event(event, event_loop);
            }

            WindowEvent::ModifiersChanged(modifiers) => {
                self.input_handler.update_modifiers(modifiers);
            }

            WindowEvent::MouseWheel { delta, .. } => {
                // Skip terminal handling if egui UI is visible or using the pointer
                // Note: any_ui_visible check is needed because is_egui_using_pointer()
                // returns false before egui is initialized (e.g., at startup when
                // shader_install_ui is shown before first render)
                if !any_ui_visible && !self.is_egui_using_pointer() {
                    self.handle_mouse_wheel(delta);
                }
            }

            WindowEvent::MouseInput { button, state, .. } => {
                use winit::event::ElementState;

                // Eat the first mouse press that brings the window into focus.
                // Without this, the click is forwarded to the PTY where mouse-aware
                // apps (tmux with `mouse on`) trigger a zero-char selection that
                // clears the system clipboard — destroying any clipboard image.
                //
                // Some platforms deliver `Focused(true)` before the mouse press, others
                // can deliver it after the press/release. Treat a press that arrives while
                // we're still unfocused as a focus-click too, then avoid double-arming the
                // later focus event path.
                let is_focus_click_press = state == ElementState::Pressed
                    && (self.focus_state.focus_click_pending || !self.focus_state.is_focused);
                if is_focus_click_press {
                    self.focus_state.focus_click_pending = false;
                    if !self.focus_state.is_focused {
                        self.focus_state.focus_click_suppressed_while_unfocused_at =
                            Some(std::time::Instant::now());
                    }
                    // If the focus click landed in the tab bar, let it through so the
                    // tab switch registers in egui. Only suppress clicks in the terminal
                    // area to prevent PTY mouse-tracking apps from seeing the focus click.
                    let mouse_position = self
                        .tab_manager
                        .active_tab()
                        .map(|t| t.active_mouse().position)
                        .unwrap_or((0.0, 0.0));
                    if self.is_mouse_in_tab_bar(mouse_position) {
                        // Don't suppress — egui needs both press and release to fire clicked_by()
                        self.focus_state.ui_consumed_mouse_press = false;
                        self.begin_clipboard_image_click_guard(button, state);
                        self.handle_mouse_button(button, state);
                        self.finish_clipboard_image_click_guard(button, state);
                    } else {
                        self.focus_state.ui_consumed_mouse_press = true; // Also suppress the release
                        self.request_redraw();
                    }
                } else {
                    // Track UI mouse consumption to prevent release events bleeding through
                    // when UI closes during a click (e.g., drawer toggle)
                    let ui_wants_pointer = any_ui_visible || self.is_egui_using_pointer();

                    if state == ElementState::Pressed {
                        if ui_wants_pointer {
                            self.focus_state.ui_consumed_mouse_press = true;
                            self.request_redraw();
                        } else {
                            self.focus_state.ui_consumed_mouse_press = false;
                            self.begin_clipboard_image_click_guard(button, state);
                            self.handle_mouse_button(button, state);
                            self.finish_clipboard_image_click_guard(button, state);
                        }
                    } else {
                        // Release: block if we consumed the press OR if UI wants pointer
                        if self.focus_state.ui_consumed_mouse_press || ui_wants_pointer {
                            self.focus_state.ui_consumed_mouse_press = false;
                            self.request_redraw();
                        } else {
                            self.begin_clipboard_image_click_guard(button, state);
                            self.handle_mouse_button(button, state);
                            self.finish_clipboard_image_click_guard(button, state);
                        }
                    }
                }
            }

            WindowEvent::CursorMoved { position, .. } => {
                // Skip terminal handling if egui UI is visible or using the pointer
                if any_ui_visible || self.is_egui_using_pointer() {
                    // Request redraw so egui can update hover states
                    self.request_redraw();
                } else {
                    self.handle_mouse_move((position.x, position.y));
                }
            }

            WindowEvent::Focused(focused) => {
                self.handle_focus_change(focused);
            }

            WindowEvent::RedrawRequested => {
                // Skip rendering if shutting down
                if self.is_shutting_down {
                    return false;
                }

                // Handle shell exit based on configured action (Keep / Close / Restart*).
                // Returns true if the window should close.
                if self.handle_shell_exit() {
                    return true;
                }

                self.render();
            }

            WindowEvent::DroppedFile(path) => {
                self.handle_dropped_file(path);
            }

            WindowEvent::CursorEntered { .. } => {
                // Focus follows mouse: auto-focus window when cursor enters
                if self.config.focus_follows_mouse
                    && let Some(window) = &self.window
                {
                    window.focus_window();
                }
            }

            WindowEvent::ThemeChanged(system_theme) => {
                let is_dark = system_theme == winit::window::Theme::Dark;
                let theme_changed = self.config.apply_system_theme(is_dark);
                let tab_style_changed = self.config.apply_system_tab_style(is_dark);

                if theme_changed {
                    log::info!(
                        "System theme changed to {}, switching to theme: {}",
                        if is_dark { "dark" } else { "light" },
                        self.config.theme
                    );
                    let theme = self.config.load_theme();
                    for tab in self.tab_manager.tabs_mut() {
                        // try_lock: intentional — ThemeChanged fires in the sync event loop.
                        // On miss: this tab keeps the old theme until the next theme event
                        // or config reload. Cell cache is still invalidated to prevent stale
                        // rendering with the old theme colors.
                        if let Ok(mut term) = tab.terminal.try_write() {
                            term.set_theme(theme.clone());
                        }
                        // Apply to split pane terminals (primary pane shares tab.terminal)
                        let tab_terminal = std::sync::Arc::clone(&tab.terminal);
                        if let Some(pm) = tab.pane_manager_mut() {
                            for pane in pm.all_panes() {
                                if !std::sync::Arc::ptr_eq(&pane.terminal, &tab_terminal)
                                    && let Ok(mut term) = pane.terminal.try_write()
                                {
                                    term.set_theme(theme.clone());
                                }
                            }
                        }
                        tab.active_cache_mut().cells = None;
                    }
                }

                if tab_style_changed {
                    log::info!(
                        "Auto tab style: switching to {} tab style",
                        if is_dark {
                            self.config.dark_tab_style.display_name()
                        } else {
                            self.config.light_tab_style.display_name()
                        }
                    );
                }

                if theme_changed || tab_style_changed {
                    if let Err(e) = self.save_config_debounced() {
                        log::error!("Failed to save config after theme change: {}", e);
                    }
                    self.focus_state.needs_redraw = true;
                    self.request_redraw();
                }
            }

            _ => {}
        }

        false // Don't close window
    }
}