par-term 0.48.0

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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! Split-pane rendering helpers.
//!
//! Contains:
//! - `PaneRenderData`: per-pane snapshot used during `submit_gpu_frame`
//! - `gather_pane_render_data`: collects per-pane cells/graphics/metadata from the pane manager
//! - `with_pane_capture_params`: scoped construction of the borrowed pane render infos
//! - `render_split_panes_with_data`: drives the GPU split-pane render pass
//! - `capture_frame_image`: the same gather, composited offscreen for screenshots (QA-011)

use super::types::RendererSizing;
use crate::config::{Config, PaneTitlePosition, ScrollbackMark, color_u8_to_f32};
use crate::selection::SelectionMode;
use anyhow::Result;
use par_term_render::cell_renderer::PaneViewport;
use par_term_render::renderer::{
    DividerRenderInfo, PaneDividerSettings, PaneRenderInfo, PaneTitleInfo, Renderer,
};
use std::sync::Arc;

/// Pane render data for split pane rendering
pub(super) struct PaneRenderData {
    /// Viewport bounds and state for this pane
    pub(super) viewport: PaneViewport,
    /// Cells to render (should match viewport grid size)
    pub(super) cells: Arc<Vec<crate::config::Cell>>,
    /// Grid dimensions (cols, rows)
    pub(super) grid_size: (usize, usize),
    /// Cursor position within this pane (col, row), or None if no cursor visible
    pub(super) cursor_pos: Option<(usize, usize)>,
    /// Cursor opacity (0.0 = hidden, 1.0 = fully visible)
    pub(super) cursor_opacity: f32,
    /// Scrollback marks for this pane
    pub(super) marks: Vec<ScrollbackMark>,
    /// Scrollback length for this pane (needed for separator mark mapping)
    pub(super) scrollback_len: usize,
    /// Current scroll offset for this pane (needed for separator mark mapping)
    pub(super) scroll_offset: usize,
    /// Per-pane background image override (None = use global background)
    pub(super) background: Option<crate::pane::PaneBackground>,
    /// Inline graphics (Sixel/iTerm2/Kitty) to render for this pane
    pub(super) graphics: Vec<par_term_emu_core_rust::graphics::TerminalGraphic>,
    /// Kitty virtual placements (U=1) used for Unicode placeholder rendering.
    pub(super) virtual_placements: Vec<par_term_emu_core_rust::graphics::TerminalGraphic>,
}

/// Width reservations for `gather_pane_render_data`.
#[derive(Clone, Copy)]
pub(super) struct PaneLayoutOptions {
    /// Physical pixels subtracted from each pane's content width for the
    /// scrollbar (applied to all panes so column counts stay stable across
    /// focus changes).
    pub(super) scrollbar_inset: f32,
    /// A par-mux transport is attached: daemon-driven tabs reserve the
    /// scrollbar strip at the window edge (see `mux_scrollbar_reserved_cols`).
    pub(super) mux_attached: bool,
}

/// Result of `gather_pane_render_data`.
pub(super) type PaneRenderDataResult = Option<(
    Vec<PaneRenderData>,
    Vec<crate::pane::DividerRect>,
    Vec<PaneTitleInfo>,
    Option<PaneViewport>,
    usize, // focused pane scrollback_len (for tab.cache update)
)>;

/// Physical pixels of a pane that hold no cells `(width, height)`: the
/// pane padding on both sides, the scrollbar inset, and the title bar —
/// the same subtractions [`gather_pane_render_data`] makes before sizing a
/// pane's grid, so `pane_min_size` is enforced in displayed cells.
pub(crate) fn pane_cell_overhead(
    config: &Config,
    effective_pane_padding: f32,
    scrollbar_inset: f32,
    scale_factor: f32,
) -> (f32, f32) {
    let padding = effective_pane_padding * scale_factor * 2.0;
    let title = if config.panes.show_pane_titles {
        config.panes.pane_title_height * scale_factor
    } else {
        0.0
    };
    (padding + scrollbar_inset, padding + title)
}

/// How an unfocused pane is dimmed (PN9): `(opacity, brightness)`
/// multipliers. `darken` scales colors and keeps text opaque; `fade`
/// lowers opacity, text included.
pub(crate) fn inactive_pane_dim(config: &Config) -> (f32, f32) {
    if !config.panes.dim_inactive_panes {
        return (1.0, 1.0);
    }
    let level = config.panes.inactive_pane_opacity;
    match config.panes.inactive_pane_dim_mode {
        par_term_config::InactivePaneDimMode::Darken => (1.0, level),
        par_term_config::InactivePaneDimMode::Fade => (level, 1.0),
    }
}

/// Gather per-pane render data from the active tab's pane manager.
///
/// This is a free function (not a `&mut self` method) so it can be called while
/// `self.renderer` is mutably borrowed.  The caller must already hold `&mut Tab`
/// from `tab_manager.active_tab_mut()`.
///
/// Returns `None` when no pane manager is present or the tab is absent.
/// # Arguments
/// * `scrollbar_inset` - Physical pixels to subtract from each pane's content width
///   for the scrollbar.  In split-pane mode this is applied to ALL panes so the
///   column count never changes on focus switch (preventing layout reflow).
///   The scrollbar is shown per-pane based on each pane's scrollback state.
#[allow(clippy::too_many_arguments)] // Render-pass inputs the caller already holds; a params struct would just restate them
pub(super) fn gather_pane_render_data(
    tab: &mut crate::tab::Tab,
    config: &Config,
    sizing: &RendererSizing,
    effective_pane_padding: f32,
    cursor_opacity: f32,
    pane_count: usize,
    layout: PaneLayoutOptions,
    copy_mode: &crate::copy_mode::CopyModeState,
) -> PaneRenderDataResult {
    let PaneLayoutOptions {
        scrollbar_inset,
        mux_attached,
    } = layout;
    let effective_padding = if pane_count > 1 && config.window.hide_window_padding_on_split {
        0.0
    } else {
        sizing.padding
    };

    let content_width = sizing.size.width as f32
        - effective_padding * 2.0
        - sizing.content_offset_x
        - sizing.content_inset_right;
    let content_height = sizing.size.height as f32
        - sizing.content_offset_y
        - sizing.content_inset_bottom
        - effective_padding
        - sizing.status_bar_height;

    let tab_scroll_offset = tab.active_scroll_state().offset;
    // A tmux/par-mux display tab (tmux_pane_id set by the layout
    // consumers): its panes' sizes belong to the daemon layout.
    let tab_is_daemon_driven = tab.tmux.tmux_pane_id.is_some();
    // Agent badges on pane titles (UX.md V3); cloned so the pane manager
    // can be borrowed mutably below.
    let tab_mux_view = tab.mux_view.clone();

    let pm = tab.pane_manager.as_mut()?;

    // A par-mux tab's layout was sized to the grid minus the scrollbar strip
    // (mux_client_grid); lay the panes out over that same reduced width so
    // native positions match the daemon's cells and the strip at the right
    // edge stays free for the scrollbar. The tmux gateway pushes the full
    // width, so its tabs keep the full content area.
    let mux_tab = mux_attached && tab_is_daemon_driven;
    let layout_width = if mux_tab {
        let reserved = crate::app::tmux_handler::mux_scrollbar_reserved_cols(
            scrollbar_inset,
            sizing.cell_width,
        );
        let full_cols = (content_width / sizing.cell_width).floor() as usize;
        (full_cols.saturating_sub(reserved).max(1) as f32 * sizing.cell_width).min(content_width)
    } else {
        content_width
    };

    // Update pane bounds
    let bounds = crate::pane::PaneBounds::new(
        effective_padding + sizing.content_offset_x,
        sizing.content_offset_y,
        layout_width,
        content_height,
    );
    pm.set_min_pane_size(
        config.panes.pane_min_size,
        (sizing.cell_width, sizing.cell_height),
        pane_cell_overhead(
            config,
            effective_pane_padding,
            scrollbar_inset,
            sizing.scale_factor,
        ),
    );
    pm.set_bounds(bounds);
    // The pane(s) whose right edge is right-most border the reserved strip.
    let layout_right_edge = pm
        .visible_panes()
        .iter()
        .map(|p| p.bounds.x + p.bounds.width)
        .fold(bounds.x, f32::max);
    let content_right_edge = bounds.x + content_width;

    // Terminal resize is done per-pane in the loop below so each pane
    // subtracts `scrollbar_inset` from its column calculation.
    // This avoids two competing resize calls that would cause SIGWINCH storms.
    // Note: title_height_offset is not needed here because `viewport_height`
    // (computed per-pane below) already subtracts the title bar height.

    let focused_pane_id = pm.focused_pane_id();
    // A zoomed pane is drawn alone (A1); the hidden panes keep running.
    let all_pane_ids: Vec<_> = pm.visible_panes().iter().map(|p| p.id).collect();
    let tab_pane_count = pm.pane_count();
    let zoomed_pane = pm.zoomed_pane_id();
    // V7: tree-order numbers over every pane, so a zoomed pane keeps the
    // number it has unzoomed (the identify overlay uses the same order).
    let pane_numbers: Vec<_> = if config.panes.show_pane_numbers && tab_pane_count > 1 {
        pm.all_panes().iter().map(|p| p.id).collect()
    } else {
        Vec::new()
    };
    let dividers = pm.get_dividers();

    let pane_bg_opacity = config.panes.pane_background_opacity;
    let (inactive_opacity, inactive_brightness) = inactive_pane_dim(config);

    // Title settings (all in physical pixels)
    let show_titles = config.panes.show_pane_titles;
    let title_height = config.panes.pane_title_height * sizing.scale_factor;
    let title_position = config.panes.pane_title_position;
    let title_text_color = color_u8_to_f32(config.panes.pane_title_color);
    let title_bg_color = color_u8_to_f32(config.panes.pane_title_bg_color);
    let need_marks = config.scrollbar.scrollbar_command_marks
        || config.command_separator.command_separator_enabled;

    let mut pane_data: Vec<PaneRenderData> = Vec::new();
    let mut pane_titles: Vec<PaneTitleInfo> = Vec::new();
    let mut focused_pane_scrollback_len: usize = 0;
    let mut focused_viewport: Option<PaneViewport> = None;

    for pane_id in &all_pane_ids {
        let Some(pane) = pm.get_pane_mut(*pane_id) else {
            continue;
        };
        let is_focused = Some(*pane_id) == focused_pane_id;
        let bounds = pane.bounds;

        // Viewport y and height accounting for title bar position
        let (viewport_y, viewport_height) = if show_titles {
            match title_position {
                PaneTitlePosition::Top => (
                    bounds.y + title_height,
                    (bounds.height - title_height).max(0.0),
                ),
                PaneTitlePosition::Bottom => (bounds.y, (bounds.height - title_height).max(0.0)),
            }
        } else {
            (bounds.y, bounds.height)
        };

        let physical_pane_padding = effective_pane_padding * sizing.scale_factor;

        // Compute grid size and resize the PTY BEFORE gathering cells so that
        // get_cells_with_scrollback returns cells at the correct dimensions.
        // All panes subtract the scrollbar inset so column counts remain stable
        // across focus changes (preventing layout reflow on pane click).
        let sb_inset = scrollbar_inset;
        let content_w =
            (bounds.width - physical_pane_padding * 2.0 - sb_inset).max(sizing.cell_width);
        let content_h = (viewport_height - physical_pane_padding * 2.0).max(sizing.cell_height);
        let mut cols = ((content_w / sizing.cell_width).floor() as usize).max(1);
        let mut rows = ((content_h / sizing.cell_height).floor() as usize).max(1);
        // A daemon-driven pane keeps the size its layout gave it (see the
        // skipped resize below), so the grid it is drawn with is that size.
        if tab_is_daemon_driven && let Ok(term) = pane.terminal.try_read() {
            (cols, rows) = term.dimensions();
        }

        // Center the cell grid within the content area by distributing
        // remainder pixels evenly on both sides (like Alacritty/Kitty).
        // Floor to integer pixels so all cell boundaries land on exact pixel
        // positions — sub-pixel centering offsets cause hairline gaps between
        // adjacent differently-colored cells due to GPU FP rasterization.
        let actual_content_w = cols as f32 * sizing.cell_width;
        let actual_content_h = rows as f32 * sizing.cell_height;
        let mut center_offset_x = ((content_w - actual_content_w) / 2.0).floor();
        let mut center_offset_y = ((content_h - actual_content_h) / 2.0).floor();
        // A daemon-driven grid is sized by its layout, not this content
        // area, and can be wider than it: a negative centering offset then
        // shifts column 0 out of the pane (the left column went missing).
        // Anchor it at the pane's top-left instead.
        let mut viewport_padding = physical_pane_padding;
        if tab_is_daemon_driven {
            center_offset_x = center_offset_x.max(0.0);
            center_offset_y = center_offset_y.max(0.0);
            if actual_content_w > content_w {
                viewport_padding = 0.0;
            }
        }

        // Panes in a tmux/par-mux display tab are sized by the daemon's
        // layout (the layout consumers resize them from their bounds). This
        // per-frame resize subtracts the divider padding and scrollbar
        // inset, which is right for a local PTY but for a daemon-backed
        // pane only shrinks the local emulator: the daemon PTY stays at the
        // layout width, htop draws for that width, and the non-reflowing
        // alt screen then drops its right-most columns (every meter lost
        // its closing bracket) — and each layout change and this resize
        // fought, flipping 104<->107 (measured). Content may draw a few
        // pixels under the divider padding or scrollbar; that is the cost.
        if !tab_is_daemon_driven {
            pane.resize_terminal_with_cell_dims(
                cols,
                rows,
                sizing.cell_width as u32,
                sizing.cell_height as u32,
            );
        }

        // The scrollbar is drawn at the viewport's right edge. The
        // right-most pane of a par-mux tab extends its viewport over the
        // strip reserved for it (layout_width < content_width), so the
        // scrollbar lands in the strip instead of over the pane's own last
        // columns. The grid itself still starts at bounds.x with its layout
        // width, so no cell moves.
        let viewport_width = if mux_tab
            && (bounds.x + bounds.width) >= layout_right_edge - sizing.cell_width / 2.0
        {
            (content_right_edge - bounds.x).max(bounds.width)
        } else {
            bounds.width
        };
        let mut viewport = PaneViewport::with_padding(
            bounds.x,
            viewport_y,
            viewport_width,
            viewport_height,
            is_focused,
            if is_focused {
                pane_bg_opacity
            } else {
                pane_bg_opacity * inactive_opacity
            },
            viewport_padding,
        );
        if !is_focused {
            viewport.brightness = inactive_brightness;
        }
        viewport.content_offset_x = center_offset_x;
        viewport.content_offset_y = center_offset_y;

        if is_focused {
            focused_viewport = Some(viewport);
        }

        // Build pane title info
        if show_titles {
            let title_y = match title_position {
                PaneTitlePosition::Top => bounds.y,
                PaneTitlePosition::Bottom => bounds.y + bounds.height - title_height,
            };
            pane_titles.push(PaneTitleInfo {
                x: bounds.x,
                y: title_y,
                width: bounds.width,
                height: title_height,
                title: crate::tab::pane_badges::decorate_pane_title_with_agent(
                    pane.get_title(),
                    zoomed_pane == Some(*pane_id),
                    pane_numbers
                        .iter()
                        .position(|id| id == pane_id)
                        .map(|i| i + 1),
                    tab_mux_view.pane_agent(*pane_id),
                ),
                focused: is_focused,
                text_color: title_text_color,
                bg_color: title_bg_color,
            });
        }

        // Gather cells — fall back to cached cells on lock contention to prevent
        // empty-frame flashes (animated shaders trigger 60fps redraws, so lock
        // contention with the PTY reader is common during heavy output).
        //
        // For the focused pane, gather_render_data already called
        // get_cells_with_scrollback() in extract_tab_cells and stored the result
        // in pane.cache.pane_cells with the current generation.  Reuse those cells
        // to avoid a second blocking terminal.lock() call, which is the primary
        // cause of FPS drops when the PTY reader is busy (e.g. tmux with many panes).
        //
        // Unfocused panes MUST NOT use this fast path: nothing refreshes their
        // cache between frames, so cache_dims_match would return true forever
        // with stale content.  They always go through try_read() which compares
        // the terminal's current generation against the cached generation — this
        // is the cross-frame cache: it still takes a cheap `try_read()` on the
        // pane's TerminalManager every frame, but skips the expensive
        // `try_get_cells_with_scrollback()` call (which takes the CORE terminal's
        // write lock, contended by the PTY reader thread) whenever the generation,
        // scroll offset, selection, and grid dims are unchanged since the cache
        // was last populated.
        let grid_size = (cols, rows);
        let expected_cell_count = cols * rows;
        let scroll_offset = if is_focused { tab_scroll_offset } else { 0 };
        // Selection is baked directly into cell colors (see `is_cell_selected` in
        // rendering.rs), so it MUST be part of the cache key — a selection change
        // does not bump `update_generation()`.
        let current_selection = pane.mouse.selection;
        let cache_dims_match = is_focused
            && pane.cache.pane_cells_generation > 0
            && pane.cache.pane_cells_scroll_offset == scroll_offset
            && pane.cache.pane_cells_selection == current_selection
            && pane.cache.pane_cells_grid_dims == grid_size
            && pane
                .cache
                .pane_cells
                .as_ref()
                .is_some_and(|c| c.len() == expected_cell_count);
        let cells = if cache_dims_match {
            Arc::clone(
                pane.cache
                    .pane_cells
                    .as_ref()
                    .expect("pane_cells must exist when pane cache dimensions match"),
            )
        } else if let Ok(term) = pane.terminal.try_read() {
            let current_gen = term.update_generation();
            let selection =
                current_selection.map(|sel| sel.viewport_adjusted(scroll_offset).normalized());
            let rectangular = current_selection
                .map(|sel| sel.mode == SelectionMode::Rectangular)
                .unwrap_or(false);
            // Use try_get_cells_with_scrollback to avoid blocking on the internal
            // terminal mutex when the PTY reader is processing output.  Falls through
            // to the pane_cells cache on contention.
            if current_gen == pane.cache.pane_cells_generation
                && pane.cache.pane_cells_scroll_offset == scroll_offset
                && pane.cache.pane_cells_selection == current_selection
                && pane.cache.pane_cells_grid_dims == grid_size
                && let Some(ref cached) = pane.cache.pane_cells
                && cached.len() == expected_cell_count
            {
                Arc::clone(cached)
            } else if let Some(fresh) =
                term.try_get_cells_with_scrollback(scroll_offset, selection, rectangular)
            {
                let fresh = Arc::new(fresh);
                pane.cache.pane_cells = Some(Arc::clone(&fresh));
                pane.cache.pane_cells_generation = current_gen;
                pane.cache.pane_cells_scroll_offset = scroll_offset;
                pane.cache.pane_cells_selection = current_selection;
                pane.cache.pane_cells_grid_dims = grid_size;
                fresh
            } else if pane.cache.pane_cells_grid_dims == grid_size
                && let Some(ref cached) = pane.cache.pane_cells
            {
                Arc::clone(cached)
            } else {
                Arc::new(Vec::new())
            }
        } else if pane.cache.pane_cells_grid_dims == grid_size
            && let Some(ref cached) = pane.cache.pane_cells
        {
            // try_lock miss — use last successfully gathered cells to avoid
            // rendering an empty pane for this frame.
            Arc::clone(cached)
        } else {
            Arc::new(Vec::new())
        };

        // Gather marks and scrollback length — use cached scrollback_len on lock miss
        let (marks, pane_scrollback_len) = if need_marks {
            if let Ok(mut term) = pane.terminal.try_write() {
                let sb_len = term.scrollback_len();
                term.update_scrollback_metadata(sb_len, 0);
                pane.cache.pane_scrollback_len = sb_len;
                (term.scrollback_marks(), sb_len)
            } else {
                (Vec::new(), pane.cache.pane_scrollback_len)
            }
        } else {
            // Still need scrollback_len for graphics position math
            let sb_len = if let Ok(term) = pane.terminal.try_read() {
                pane.cache.pane_scrollback_len = term.scrollback_len();
                pane.cache.pane_scrollback_len
            } else {
                pane.cache.pane_scrollback_len
            };
            (Vec::new(), sb_len)
        };
        let pane_scroll_offset = if is_focused { tab_scroll_offset } else { 0 };

        // Cache focused pane scrollback_len for scroll operations
        if is_focused && pane_scrollback_len > 0 {
            focused_pane_scrollback_len = pane_scrollback_len;
        }

        // Per-pane backgrounds only apply when multiple panes exist
        let pane_background = if tab_pane_count > 1 && pane.background().has_image() {
            Some(pane.background().clone())
        } else {
            None
        };

        // Cursor position — only show when viewport is not scrolled away from the live screen.
        // When scroll_offset > 0 the cursor is off-screen (in scrollback), so hide it.
        // Copy mode is the exception: the focused pane draws the copy-mode
        // cursor (valid in scrollback too), mirroring extract_tab_cells.
        let cursor_pos = if is_focused && copy_mode.active {
            copy_mode.screen_cursor_pos(scroll_offset)
        } else if scroll_offset == 0 {
            if let Ok(term) = pane.terminal.try_read() {
                if term.is_cursor_visible() {
                    Some(term.cursor_position())
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

        // Collect Kitty virtual placements (U=1) — these are stored separately
        // from active graphics and get rendered wherever the cell grid contains
        // the corresponding placeholder character runs.
        let pane_virtual_placements = if let Ok(term) = pane.terminal.try_read() {
            term.get_virtual_placements()
        } else {
            Vec::new()
        };

        // Collect inline graphics (Sixel/iTerm2/Kitty)
        let pane_graphics = if let Ok(term) = pane.terminal.try_read() {
            // Remove graphics whose rows have been overwritten by cell writes
            // (e.g. tmux control-mode redraw doesn't send ED 2).
            term.invalidate_overwritten_graphics();

            let mut g = term.get_graphics_with_animations();
            let sb = term.get_scrollback_graphics();
            crate::debug_log!(
                "GRAPHICS",
                "pane {:?}: active_graphics={}, scrollback_graphics={}, scrollback_len={}, scroll_offset={}, visible_rows={}, viewport=({},{},{}x{})",
                pane_id,
                g.len(),
                sb.len(),
                pane_scrollback_len,
                pane_scroll_offset,
                rows,
                viewport.x,
                viewport.y,
                viewport.width,
                viewport.height
            );
            for (i, gfx) in g.iter().chain(sb.iter()).enumerate() {
                crate::debug_log!(
                    "GRAPHICS",
                    "  graphic[{}]: id={}, pos=({},{}), scroll_offset_rows={}, scrollback_row={:?}, size={}x{}",
                    i,
                    gfx.id,
                    gfx.position.0,
                    gfx.position.1,
                    gfx.scroll_offset_rows,
                    gfx.scrollback_row,
                    gfx.width,
                    gfx.height
                );
            }
            g.extend(sb);
            g
        } else {
            crate::debug_log!(
                "GRAPHICS",
                "pane {:?}: try_lock() failed, no graphics",
                pane_id
            );
            Vec::new()
        };

        pane_data.push(PaneRenderData {
            viewport,
            cells,
            grid_size: (cols, rows),
            cursor_pos,
            cursor_opacity: if is_focused { cursor_opacity } else { 0.0 },
            marks,
            scrollback_len: pane_scrollback_len,
            scroll_offset: pane_scroll_offset,
            background: pane_background,
            graphics: pane_graphics,
            virtual_placements: pane_virtual_placements,
        });
    }

    Some((
        pane_data,
        dividers,
        pane_titles,
        focused_viewport,
        focused_pane_scrollback_len,
    ))
}

/// Parameters for [`WindowState::render_split_panes_with_data`].
pub(super) struct SplitPaneRenderParams<'a> {
    pub pane_data: Vec<PaneRenderData>,
    pub dividers: Vec<crate::pane::DividerRect>,
    pub pane_titles: Vec<PaneTitleInfo>,
    pub focused_viewport: Option<PaneViewport>,
    pub config: &'a Config,
    pub egui_data: Option<(egui::FullOutput, &'a egui::Context)>,
    pub hovered_divider_index: Option<usize>,
    pub show_scrollbar: bool,
}

/// Gathered pane state, before it is turned into the borrowed render infos.
///
/// This is [`SplitPaneRenderParams`] minus `egui_data`, which is the part an
/// offscreen capture can also supply.
pub(super) struct PaneCaptureInput<'a> {
    pub pane_data: Vec<PaneRenderData>,
    pub dividers: Vec<crate::pane::DividerRect>,
    pub pane_titles: Vec<PaneTitleInfo>,
    pub focused_viewport: Option<PaneViewport>,
    pub config: &'a Config,
    pub hovered_divider_index: Option<usize>,
    pub show_scrollbar: bool,
}

/// Build the borrowed [`par_term_render::renderer::PaneCaptureParams`] and hand it to `f`.
///
/// A scoped callback rather than a returned value because the pane infos borrow
/// the owned cell `Arc`s, the divider infos and the divider settings, all of
/// which have to outlive the render call and none of which can escape this
/// frame. Both the live path and the QA-011 screenshot path go through here, so
/// a capture cannot drift out of step with what is drawn on screen.
pub(super) fn with_pane_capture_params<R>(
    renderer: &mut Renderer,
    input: PaneCaptureInput<'_>,
    f: impl FnOnce(&mut Renderer, par_term_render::renderer::PaneCaptureParams<'_>) -> R,
) -> R {
    let PaneCaptureInput {
        pane_data,
        dividers,
        pane_titles,
        focused_viewport,
        config,
        hovered_divider_index,
        show_scrollbar,
    } = input;
    // Two-phase construction: separate owned cell data from pane metadata
    // so PaneRenderInfo can borrow cell slices safely.  This replaces the
    // previous unsafe Box::into_raw / Box::from_raw pattern that leaked
    // memory if render_split_panes panicked.
    //
    // Phase 1: Extract cells into a Vec that outlives the render infos.
    // The remaining pane fields are collected into partial render infos.
    let mut owned_cells: Vec<Arc<Vec<crate::config::Cell>>> = Vec::with_capacity(pane_data.len());
    let mut partial_infos: Vec<PaneRenderInfo> = Vec::with_capacity(pane_data.len());

    for pane in pane_data {
        let focused = pane.viewport.focused;
        owned_cells.push(pane.cells);
        partial_infos.push(PaneRenderInfo {
            viewport: pane.viewport,
            // Placeholder — will be patched in Phase 2 once owned_cells
            // is finished growing and its elements have stable addresses.
            cells: &[],
            grid_size: pane.grid_size,
            cursor_pos: pane.cursor_pos,
            cursor_opacity: pane.cursor_opacity,
            // Focused pane: respect autohide via show_scrollbar flag.
            // Unfocused panes: always show scrollbar when they have scrollback
            // content, so the scrollbar doesn't disappear on focus loss.
            show_scrollbar: if focused {
                show_scrollbar && pane.scrollback_len > 0
            } else {
                pane.scrollback_len > 0
            },
            marks: pane.marks,
            scrollback_len: pane.scrollback_len,
            scroll_offset: pane.scroll_offset,
            background: pane.background,
            graphics: pane.graphics,
            virtual_placements: pane.virtual_placements,
        });
    }

    // Phase 2: Patch cell references now that owned_cells won't reallocate.
    // owned_cells lives until scope exit (even on panic), so the borrows
    // are valid for the lifetime of partial_infos.
    for (info, cells) in partial_infos.iter_mut().zip(owned_cells.iter()) {
        info.cells = cells.as_slice();
    }
    let pane_render_infos = partial_infos;

    // Build divider render info
    let divider_render_infos: Vec<DividerRenderInfo> = dividers
        .iter()
        .enumerate()
        .map(|(i, d)| DividerRenderInfo::from_rect(d, hovered_divider_index == Some(i)))
        .collect();

    // Build divider settings from config
    let divider_settings = PaneDividerSettings {
        divider_color: color_u8_to_f32(config.panes.pane_divider_color),
        hover_color: color_u8_to_f32(config.panes.pane_divider_hover_color),
        show_focus_indicator: config.panes.pane_focus_indicator,
        focus_color: color_u8_to_f32(config.panes.pane_focus_color),
        focus_width: config.panes.pane_focus_width * renderer.scale_factor(),
        divider_style: config.panes.pane_divider_style,
    };

    renderer.update_shader_focused_pane(focused_viewport.as_ref());

    // owned_cells is dropped automatically at scope exit, even on panic.
    f(
        renderer,
        par_term_render::renderer::PaneCaptureParams {
            panes: &pane_render_infos,
            dividers: &divider_render_infos,
            pane_titles: &pane_titles,
            focused_viewport: focused_viewport.as_ref(),
            divider_settings: &divider_settings,
        },
    )
}

impl crate::app::window_state::WindowState {
    /// Render split panes when the active tab has multiple panes
    pub(super) fn render_split_panes_with_data(
        renderer: &mut Renderer,
        p: SplitPaneRenderParams<'_>,
    ) -> Result<bool> {
        let SplitPaneRenderParams {
            pane_data,
            dividers,
            pane_titles,
            focused_viewport,
            config,
            egui_data,
            hovered_divider_index,
            show_scrollbar,
        } = p;
        with_pane_capture_params(
            renderer,
            PaneCaptureInput {
                pane_data,
                dividers,
                pane_titles,
                focused_viewport,
                config,
                hovered_divider_index,
                show_scrollbar,
            },
            move |renderer, cap| {
                renderer.render_split_panes(par_term_render::renderer::SplitPanesRenderParams {
                    panes: cap.panes,
                    dividers: cap.dividers,
                    pane_titles: cap.pane_titles,
                    focused_viewport: cap.focused_viewport,
                    divider_settings: cap.divider_settings,
                    egui_data,
                    force_egui_opaque: false,
                })
            },
        )
    }
}

#[cfg(test)]
mod copy_mode_cursor_tests {
    use super::{PaneLayoutOptions, gather_pane_render_data};
    use crate::config::Config;
    use crate::copy_mode::CopyModeState;
    use par_term_terminal::TerminalManager;
    use std::sync::Arc;
    use tokio::sync::RwLock;
    use winit::dpi::PhysicalSize;

    /// A tab whose focused pane runs a deterministic headless terminal (no
    /// PTY), so cursor position and scrollback length are exact.
    ///
    /// The tab itself is real (`Tab::new` spawns the shell on the tab-level
    /// terminal), but the pane's terminal is swapped for one fed 30 numbered
    /// lines — the gather path only ever reads `pane.terminal`.
    fn tab_with_fed_pane() -> (crate::tab::Tab, usize) {
        let runtime = Arc::new(
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("build test runtime"),
        );
        let config = Config::default();
        let mut tab =
            crate::tab::Tab::new(1, 1, &config, runtime, None, Some((80, 24))).expect("tab");

        let term = TerminalManager::new_with_scrollback(80, 24, 200).expect("terminal");
        for i in 0..30 {
            term.process_data(format!("line {i:02}\r\n").as_bytes());
        }
        let sb_len = term.scrollback_len();

        let pm = tab.pane_manager.as_mut().expect("pane manager");
        let pane_id = pm.focused_pane_id().expect("focused pane");
        let pane = pm.get_pane_mut(pane_id).expect("pane");
        pane.terminal = Arc::new(RwLock::new(term));
        (tab, sb_len)
    }

    fn sizing_80x24() -> super::RendererSizing {
        super::RendererSizing {
            size: PhysicalSize::new(640, 384),
            content_offset_y: 0.0,
            content_offset_x: 0.0,
            content_inset_bottom: 0.0,
            content_inset_right: 0.0,
            cell_width: 8.0,
            cell_height: 16.0,
            padding: 0.0,
            status_bar_height: 0.0,
            scale_factor: 1.0,
            scrollbar_width: 0.0,
        }
    }

    fn gather_cursor(
        tab: &mut crate::tab::Tab,
        copy_mode: &CopyModeState,
    ) -> Option<(usize, usize)> {
        let (pane_data, ..) = gather_pane_render_data(
            tab,
            &Config::default(),
            &sizing_80x24(),
            0.0,
            1.0,
            1,
            PaneLayoutOptions {
                scrollbar_inset: 0.0,
                mux_attached: false,
            },
            copy_mode,
        )
        .expect("pane data");
        pane_data[0].cursor_pos
    }

    /// With copy mode active on the focused pane, the gathered cursor is the
    /// copy-mode cursor, not the terminal cursor the shell left behind.
    #[test]
    fn focused_pane_cursor_follows_copy_mode_on_the_live_view() {
        let (mut tab, sb_len) = tab_with_fed_pane();

        let mut copy_mode = CopyModeState::new();
        copy_mode.enter(4, 5, 80, 24, sb_len);
        copy_mode.move_up();
        copy_mode.move_up();

        let expected = (4, 3);
        assert_ne!(
            tab.pane_manager
                .as_ref()
                .and_then(|pm| pm.focused_pane_id())
                .and_then(|id| pm_get_pane(&tab, id))
                .and_then(|p| p.terminal.try_read().ok())
                .map(|t| t.cursor_position()),
            Some(expected),
            "precondition: the terminal cursor must differ from the copy-mode cursor"
        );
        assert_eq!(copy_mode.screen_cursor_pos(0), Some(expected));
        assert_eq!(gather_cursor(&mut tab, &copy_mode), Some(expected));
    }

    /// A copy-mode cursor moved into scrollback stays visible at
    /// scroll_offset > 0 and tracks further motion (the terminal cursor is
    /// hidden there, so the old code returned None).
    #[test]
    fn focused_pane_copy_mode_cursor_stays_visible_in_scrollback() {
        let (mut tab, sb_len) = tab_with_fed_pane();
        tab.active_scroll_state_mut().offset = 3;

        let mut copy_mode = CopyModeState::new();
        copy_mode.enter(4, 5, 80, 24, sb_len);
        copy_mode.cursor_absolute_line = sb_len.saturating_sub(3);

        // viewport_top = sb_len - 3 → the cursor sits at screen row 0.
        assert_eq!(copy_mode.screen_cursor_pos(3), Some((4, 0)));
        assert_eq!(gather_cursor(&mut tab, &copy_mode), Some((4, 0)));

        // Motion tracks: one line down moves the drawn cursor one row.
        copy_mode.cursor_absolute_line = sb_len.saturating_sub(2);
        assert_eq!(gather_cursor(&mut tab, &copy_mode), Some((4, 1)));
    }

    fn pm_get_pane(tab: &crate::tab::Tab, id: crate::pane::PaneId) -> Option<&crate::pane::Pane> {
        tab.pane_manager.as_ref()?.get_pane(id)
    }

    /// PN9: with `dim_inactive_panes` on, `darken` (the default) gives the
    /// unfocused pane full opacity and reduced brightness; `fade` gives it
    /// reduced opacity (the old behavior) and full brightness. The focused
    /// pane is never dimmed.
    #[test]
    fn inactive_panes_darken_by_default_and_fade_on_request() {
        use crate::pane::{Pane, PaneNode, SplitDirection};
        use par_term_config::InactivePaneDimMode;

        let (mut tab, _) = tab_with_fed_pane();
        let stub = |id| {
            Pane::new_wrapping_terminal(
                id,
                Arc::new(RwLock::new(
                    TerminalManager::new_with_scrollback(40, 24, 0).expect("terminal"),
                )),
                None,
                Arc::new(std::sync::atomic::AtomicBool::new(false)),
            )
        };
        let pm = tab.pane_manager.as_mut().expect("pm");
        pm.set_root(PaneNode::split(
            SplitDirection::Vertical,
            0.5,
            PaneNode::leaf(stub(1)),
            PaneNode::leaf(stub(2)),
        ));
        pm.focus_pane(1);

        let mut viewports = |config: &Config| -> Vec<(bool, f32, f32)> {
            let (pane_data, ..) = gather_pane_render_data(
                &mut tab,
                config,
                &sizing_80x24(),
                0.0,
                1.0,
                2,
                PaneLayoutOptions {
                    scrollbar_inset: 0.0,
                    mux_attached: false,
                },
                &CopyModeState::new(),
            )
            .expect("pane data");
            pane_data
                .iter()
                .map(|p| {
                    (
                        p.viewport.focused,
                        p.viewport.opacity,
                        p.viewport.brightness,
                    )
                })
                .collect()
        };

        let mut config = Config::default();
        config.panes.dim_inactive_panes = true;
        config.panes.inactive_pane_opacity = 0.6;
        assert_eq!(
            config.panes.inactive_pane_dim_mode,
            InactivePaneDimMode::Darken
        );
        assert_eq!(
            viewports(&config),
            vec![(true, 1.0, 1.0), (false, 1.0, 0.6)],
            "darken keeps opacity and lowers brightness"
        );

        config.panes.inactive_pane_dim_mode = InactivePaneDimMode::Fade;
        assert_eq!(
            viewports(&config),
            vec![(true, 1.0, 1.0), (false, 0.6, 1.0)],
            "fade lowers opacity, as before PN9"
        );

        config.panes.dim_inactive_panes = false;
        assert_eq!(
            viewports(&config),
            vec![(true, 1.0, 1.0), (false, 1.0, 1.0)]
        );
    }
}