Skip to main content

par_term_render/cell_renderer/
layout.rs

1use super::{BackgroundInstance, Cell, CellRenderer, RowCacheEntry, TextInstance, pipeline};
2
3/// Terminal grid dimensions, cell sizes, padding, and content offsets.
4pub(crate) struct GridLayout {
5    pub(crate) cols: usize,
6    pub(crate) rows: usize,
7    pub(crate) cell_width: f32,
8    pub(crate) cell_height: f32,
9    pub(crate) window_padding: f32,
10    /// Vertical offset for terminal content (e.g., tab bar at top).
11    /// Content is rendered starting at y = window_padding + content_offset_y.
12    pub(crate) content_offset_y: f32,
13    /// Horizontal offset for terminal content (e.g., tab bar on left).
14    /// Content is rendered starting at x = window_padding + content_offset_x.
15    pub(crate) content_offset_x: f32,
16    /// Bottom inset for terminal content (e.g., tab bar at bottom).
17    /// Reduces available height without shifting content vertically.
18    pub(crate) content_inset_bottom: f32,
19    /// Right inset for terminal content (e.g., AI Inspector panel).
20    /// Reduces available width without shifting content horizontally.
21    pub(crate) content_inset_right: f32,
22    /// Additional bottom inset from egui panels (status bar, tmux bar).
23    /// This is added to content_inset_bottom for scrollbar bounds only,
24    /// since egui panels already claim space before wgpu rendering.
25    pub(crate) egui_bottom_inset: f32,
26    /// Additional right inset from egui panels (AI Inspector).
27    /// This is added to content_inset_right for scrollbar bounds only,
28    /// since egui panels already claim space before wgpu rendering.
29    pub(crate) egui_right_inset: f32,
30}
31
32impl CellRenderer {
33    pub fn cell_width(&self) -> f32 {
34        self.grid.cell_width
35    }
36    pub fn cell_height(&self) -> f32 {
37        self.grid.cell_height
38    }
39    pub fn window_padding(&self) -> f32 {
40        self.grid.window_padding
41    }
42    pub fn content_offset_y(&self) -> f32 {
43        self.grid.content_offset_y
44    }
45    /// Set the vertical content offset (e.g., tab bar height at top).
46    /// Returns Some((cols, rows)) if grid size changed, None otherwise.
47    pub fn set_content_offset_y(&mut self, offset: f32) -> Option<(usize, usize)> {
48        if (self.grid.content_offset_y - offset).abs() > f32::EPSILON {
49            self.grid.content_offset_y = offset;
50            let size = (self.config.width, self.config.height);
51            return Some(self.resize(size.0, size.1));
52        }
53        None
54    }
55    pub fn content_offset_x(&self) -> f32 {
56        self.grid.content_offset_x
57    }
58    /// Set the horizontal content offset (e.g., tab bar on left).
59    /// Returns Some((cols, rows)) if grid size changed, None otherwise.
60    pub fn set_content_offset_x(&mut self, offset: f32) -> Option<(usize, usize)> {
61        if (self.grid.content_offset_x - offset).abs() > f32::EPSILON {
62            self.grid.content_offset_x = offset;
63            let size = (self.config.width, self.config.height);
64            return Some(self.resize(size.0, size.1));
65        }
66        None
67    }
68    pub fn content_inset_bottom(&self) -> f32 {
69        self.grid.content_inset_bottom
70    }
71    /// Set the bottom content inset (e.g., tab bar at bottom).
72    /// Returns Some((cols, rows)) if grid size changed, None otherwise.
73    pub fn set_content_inset_bottom(&mut self, inset: f32) -> Option<(usize, usize)> {
74        if (self.grid.content_inset_bottom - inset).abs() > f32::EPSILON {
75            self.grid.content_inset_bottom = inset;
76            let size = (self.config.width, self.config.height);
77            return Some(self.resize(size.0, size.1));
78        }
79        None
80    }
81    pub fn content_inset_right(&self) -> f32 {
82        self.grid.content_inset_right
83    }
84    /// Set the right content inset (e.g., AI Inspector panel).
85    /// Returns Some((cols, rows)) if grid size changed, None otherwise.
86    pub fn set_content_inset_right(&mut self, inset: f32) -> Option<(usize, usize)> {
87        if (self.grid.content_inset_right - inset).abs() > f32::EPSILON {
88            log::info!(
89                "[SCROLLBAR] set_content_inset_right: {:.1} -> {:.1} (physical px)",
90                self.grid.content_inset_right,
91                inset
92            );
93            self.grid.content_inset_right = inset;
94            let size = (self.config.width, self.config.height);
95            return Some(self.resize(size.0, size.1));
96        }
97        None
98    }
99    pub fn grid_size(&self) -> (usize, usize) {
100        (self.grid.cols, self.grid.rows)
101    }
102
103    pub fn resize(&mut self, width: u32, height: u32) -> (usize, usize) {
104        if width == 0 || height == 0 {
105            return (self.grid.cols, self.grid.rows);
106        }
107        let (width, height) = super::surface::clamp_surface_extent(
108            width,
109            height,
110            self.device.limits().max_texture_dimension_2d,
111        );
112        self.config.width = width;
113        self.config.height = height;
114        self.surface.configure(&self.device, &self.config);
115
116        // Match the pane render path formula (see `chrome_overhead` below),
117        // which is always active. Width: no scrollbar deduction here — the pane
118        // render path conditionally subtracts scrollbar_width via RendererSizing
119        // when the scrollbar is visible.
120        // Height: 1× padding (top margin is content_offset_y, not padding).
121        let available_width = (width as f32
122            - self.grid.window_padding * 2.0
123            - self.grid.content_offset_x
124            - self.grid.content_inset_right)
125            .max(0.0);
126        let available_height = (height as f32
127            - self.grid.window_padding
128            - self.grid.content_offset_y
129            - self.grid.content_inset_bottom
130            - self.grid.egui_bottom_inset)
131            .max(0.0);
132        let new_cols = (available_width / self.grid.cell_width).max(1.0) as usize;
133        let new_rows = (available_height / self.grid.cell_height).max(1.0) as usize;
134
135        if new_cols != self.grid.cols || new_rows != self.grid.rows {
136            self.grid.cols = new_cols;
137            self.grid.rows = new_rows;
138            self.cells = vec![Cell::default(); self.grid.cols * self.grid.rows];
139            self.dirty_rows = vec![true; self.grid.rows];
140            self.row_cache = vec![None::<RowCacheEntry>; self.grid.rows];
141            self.recreate_instance_buffers();
142        }
143
144        self.update_bg_image_uniforms(None);
145        (self.grid.cols, self.grid.rows)
146    }
147
148    /// Returns total non-terminal pixel overhead as (horizontal_px, vertical_px).
149    ///
150    /// Matches the pane render path formula, which is always active:
151    ///   Horizontal: window_padding*2 + content_offset_x + content_inset_right
152    ///   Vertical:   window_padding + content_offset_y + content_inset_bottom + egui_bottom_inset
153    ///
154    /// Note: scrollbar is NOT included — it is conditionally subtracted in the
155    /// pane render path (RendererSizing.scrollbar_width) only when visible.
156    /// Height uses 1× padding (bottom only; top margin is content_offset_y).
157    pub fn chrome_overhead(&self) -> (f32, f32) {
158        let chrome_x = self.grid.window_padding * 2.0
159            + self.grid.content_offset_x
160            + self.grid.content_inset_right;
161        let chrome_y = self.grid.window_padding
162            + self.grid.content_offset_y
163            + self.grid.content_inset_bottom
164            + self.grid.egui_bottom_inset;
165        (chrome_x, chrome_y)
166    }
167
168    /// Instance capacity the single-grid (offscreen) layout needs:
169    /// cells + cursor overlays + one separator per row + one gutter bar per row.
170    pub(crate) fn single_grid_instance_capacity(&self) -> (usize, usize) {
171        (
172            super::render::SingleGridLayout::new(self.grid.cols, self.grid.rows).bg_instances(),
173            self.grid.cols * self.grid.rows * super::TEXT_INSTANCES_PER_CELL,
174        )
175    }
176
177    pub(crate) fn recreate_instance_buffers(&mut self) {
178        let (bg, text) = self.single_grid_instance_capacity();
179        self.allocate_instance_buffers(bg, text);
180    }
181
182    /// Reallocate both instance buffers (GPU and CPU side) to the given capacities.
183    pub(crate) fn allocate_instance_buffers(&mut self, max_bg: usize, max_text: usize) {
184        self.buffers.max_bg_instances = max_bg;
185        self.buffers.max_text_instances = max_text;
186        let (bg_buf, text_buf) = pipeline::create_instance_buffers(
187            &self.device,
188            self.buffers.max_bg_instances,
189            self.buffers.max_text_instances,
190        );
191        self.buffers.bg_instance_buffer = bg_buf;
192        self.buffers.text_instance_buffer = text_buf;
193        // Reset actual counts - will be updated when instance buffers are built
194        self.buffers.actual_bg_instances = 0;
195        self.buffers.actual_text_instances = 0;
196        self.buffers.pane_bg_cursor = 0;
197        self.buffers.pane_text_cursor = 0;
198        // A new allocation may well be the fix for a previous over-run, so let it
199        // be reported again if it still does not fit.
200        self.buffers.overflow_reported = false;
201
202        self.bg_instances = vec![
203            BackgroundInstance {
204                position: [0.0, 0.0],
205                size: [0.0, 0.0],
206                color: [0.0, 0.0, 0.0, 0.0],
207            };
208            self.buffers.max_bg_instances
209        ];
210        self.text_instances = vec![
211            TextInstance {
212                position: [0.0, 0.0],
213                size: [0.0, 0.0],
214                tex_offset: [0.0, 0.0],
215                tex_size: [0.0, 0.0],
216                color: [0.0, 0.0, 0.0, 0.0],
217                is_colored: 0,
218            };
219            self.buffers.max_text_instances
220        ];
221
222        // Resize scratch buffers to match new grid; keep existing allocations if large enough
223        self.scratch_row_bg.reserve(
224            self.grid
225                .cols
226                .saturating_sub(self.scratch_row_bg.capacity()),
227        );
228        self.scratch_row_text
229            .reserve((self.grid.cols * 2).saturating_sub(self.scratch_row_text.capacity()));
230    }
231
232    /// Update scale factor and recalculate all font metrics and cell dimensions.
233    /// This is called when the window is dragged between displays with different DPIs.
234    pub fn update_scale_factor(&mut self, scale_factor: f64) {
235        let new_scale = scale_factor as f32;
236
237        // Skip if scale factor hasn't changed
238        if (self.scale_factor - new_scale).abs() < f32::EPSILON {
239            return;
240        }
241
242        log::info!(
243            "Recalculating font metrics for scale factor change: {} -> {}",
244            self.scale_factor,
245            new_scale
246        );
247
248        self.scale_factor = new_scale;
249
250        // Recalculate font_size_pixels based on new scale factor
251        let platform_dpi = if cfg!(target_os = "macos") {
252            crate::cell_renderer::MACOS_PLATFORM_DPI
253        } else {
254            crate::cell_renderer::DEFAULT_PLATFORM_DPI
255        };
256        let base_font_pixels =
257            self.font.base_font_size * platform_dpi / crate::cell_renderer::FONT_REFERENCE_DPI;
258        self.font.font_size_pixels = (base_font_pixels * new_scale).max(1.0);
259
260        // Re-extract font metrics at new scale
261        let (font_ascent, font_descent, font_leading, char_advance) = {
262            let primary_font = self.font_manager.get_font(0).expect(
263                "Primary font at index 0 must exist in FontManager when updating scale factor",
264            );
265            let metrics = primary_font.metrics(&[]);
266            let scale = self.font.font_size_pixels / metrics.units_per_em as f32;
267            let glyph_id = primary_font.charmap().map('m');
268            let advance = primary_font.glyph_metrics(&[]).advance_width(glyph_id) * scale;
269            (
270                metrics.ascent * scale,
271                metrics.descent * scale,
272                metrics.leading * scale,
273                advance,
274            )
275        };
276
277        self.font.font_ascent = font_ascent;
278        self.font.font_descent = font_descent;
279        self.font.font_leading = font_leading;
280        self.font.char_advance = char_advance;
281
282        // Recalculate cell dimensions (rounded to integer pixels for uniform glyph brightness)
283        let natural_line_height = font_ascent + font_descent + font_leading;
284        self.grid.cell_height = (natural_line_height * self.font.line_spacing)
285            .max(1.0)
286            .round();
287        self.grid.cell_width = (char_advance * self.font.char_spacing).max(1.0).round();
288
289        log::info!(
290            "New cell dimensions: {}x{} (font_size_pixels: {})",
291            self.grid.cell_width,
292            self.grid.cell_height,
293            self.font.font_size_pixels
294        );
295
296        // Clear glyph cache - glyphs need to be re-rasterized at new DPI
297        self.clear_glyph_cache();
298
299        // Mark all rows as dirty to force re-rendering
300        self.dirty_rows.fill(true);
301    }
302
303    pub fn update_window_padding(&mut self, padding: f32) -> Option<(usize, usize)> {
304        if (self.grid.window_padding - padding).abs() > f32::EPSILON {
305            self.grid.window_padding = padding;
306            let size = (self.config.width, self.config.height);
307            return Some(self.resize(size.0, size.1));
308        }
309        None
310    }
311}