1use anyhow::{Context, Result};
2use std::collections::HashMap;
3use std::sync::Arc;
4use winit::window::Window;
5
6use crate::scrollbar::Scrollbar;
7use par_term_config::SeparatorMark;
8use par_term_fonts::font_manager::FontManager;
9
10pub mod atlas;
11pub mod background;
12pub mod block_chars;
13pub mod pipeline;
14pub mod render;
15pub mod types;
16pub use types::{Cell, PaneViewport};
18pub(crate) use types::{BackgroundInstance, GlyphInfo, RowCacheEntry, TextInstance};
20
21pub struct CellRenderer {
22 pub(crate) device: Arc<wgpu::Device>,
23 pub(crate) queue: Arc<wgpu::Queue>,
24 pub(crate) surface: wgpu::Surface<'static>,
25 pub(crate) config: wgpu::SurfaceConfiguration,
26 pub(crate) supported_present_modes: Vec<wgpu::PresentMode>,
28
29 pub(crate) bg_pipeline: wgpu::RenderPipeline,
31 pub(crate) text_pipeline: wgpu::RenderPipeline,
32 pub(crate) bg_image_pipeline: wgpu::RenderPipeline,
33 #[allow(dead_code)]
34 pub(crate) visual_bell_pipeline: wgpu::RenderPipeline,
35
36 pub(crate) vertex_buffer: wgpu::Buffer,
38 pub(crate) bg_instance_buffer: wgpu::Buffer,
39 pub(crate) text_instance_buffer: wgpu::Buffer,
40 pub(crate) bg_image_uniform_buffer: wgpu::Buffer,
41 #[allow(dead_code)]
42 pub(crate) visual_bell_uniform_buffer: wgpu::Buffer,
43
44 pub(crate) text_bind_group: wgpu::BindGroup,
46 #[allow(dead_code)]
47 pub(crate) text_bind_group_layout: wgpu::BindGroupLayout,
48 pub(crate) bg_image_bind_group: Option<wgpu::BindGroup>,
49 pub(crate) bg_image_bind_group_layout: wgpu::BindGroupLayout,
50 #[allow(dead_code)]
51 pub(crate) visual_bell_bind_group: wgpu::BindGroup,
52
53 pub(crate) atlas_texture: wgpu::Texture,
55 #[allow(dead_code)]
56 pub(crate) atlas_view: wgpu::TextureView,
57 pub(crate) glyph_cache: HashMap<u64, GlyphInfo>,
58 pub(crate) lru_head: Option<u64>,
59 pub(crate) lru_tail: Option<u64>,
60 pub(crate) atlas_next_x: u32,
61 pub(crate) atlas_next_y: u32,
62 pub(crate) atlas_row_height: u32,
63
64 pub(crate) cols: usize,
66 pub(crate) rows: usize,
67 pub(crate) cell_width: f32,
68 pub(crate) cell_height: f32,
69 pub(crate) window_padding: f32,
70 pub(crate) content_offset_y: f32,
73 pub(crate) content_offset_x: f32,
76 pub(crate) content_inset_bottom: f32,
79 pub(crate) content_inset_right: f32,
82 pub(crate) egui_bottom_inset: f32,
86 pub(crate) egui_right_inset: f32,
90 #[allow(dead_code)]
91 pub(crate) scale_factor: f32,
92
93 pub(crate) font_manager: FontManager,
95 pub(crate) scrollbar: Scrollbar,
96
97 pub(crate) cells: Vec<Cell>,
99 pub(crate) dirty_rows: Vec<bool>,
100 pub(crate) row_cache: Vec<Option<RowCacheEntry>>,
101 pub(crate) cursor_pos: (usize, usize),
102 pub(crate) cursor_opacity: f32,
103 pub(crate) cursor_style: par_term_emu_core_rust::cursor::CursorStyle,
104 pub(crate) cursor_overlay: Option<BackgroundInstance>,
106 pub(crate) cursor_color: [f32; 3],
108 pub(crate) cursor_text_color: Option<[f32; 3]>,
110 pub(crate) cursor_hidden_for_shader: bool,
112 pub(crate) is_focused: bool,
114
115 pub(crate) cursor_guide_enabled: bool,
118 pub(crate) cursor_guide_color: [f32; 4],
120 pub(crate) cursor_shadow_enabled: bool,
122 pub(crate) cursor_shadow_color: [f32; 4],
124 pub(crate) cursor_shadow_offset: [f32; 2],
126 #[allow(dead_code)]
128 pub(crate) cursor_shadow_blur: f32,
129 pub(crate) cursor_boost: f32,
131 pub(crate) cursor_boost_color: [f32; 3],
133 pub(crate) unfocused_cursor_style: par_term_config::UnfocusedCursorStyle,
135 pub(crate) visual_bell_intensity: f32,
136 pub(crate) window_opacity: f32,
137 pub(crate) background_color: [f32; 4],
138
139 pub(crate) base_font_size: f32,
141 pub(crate) line_spacing: f32,
142 pub(crate) char_spacing: f32,
143
144 pub(crate) font_ascent: f32,
146 pub(crate) font_descent: f32,
147 pub(crate) font_leading: f32,
148 pub(crate) font_size_pixels: f32,
149 pub(crate) char_advance: f32,
150
151 pub(crate) bg_image_texture: Option<wgpu::Texture>,
153 pub(crate) bg_image_mode: par_term_config::BackgroundImageMode,
154 pub(crate) bg_image_opacity: f32,
155 pub(crate) bg_image_width: u32,
156 pub(crate) bg_image_height: u32,
157 pub(crate) bg_is_solid_color: bool,
161 pub(crate) solid_bg_color: [f32; 3],
164
165 pub(crate) pane_bg_cache: HashMap<String, background::PaneBackgroundEntry>,
167
168 pub(crate) max_bg_instances: usize,
170 pub(crate) max_text_instances: usize,
171
172 pub(crate) bg_instances: Vec<BackgroundInstance>,
174 pub(crate) text_instances: Vec<TextInstance>,
175
176 #[allow(dead_code)]
178 pub(crate) enable_text_shaping: bool,
179 pub(crate) enable_ligatures: bool,
180 pub(crate) enable_kerning: bool,
181
182 pub(crate) font_antialias: bool,
185 pub(crate) font_hinting: bool,
187 pub(crate) font_thin_strokes: par_term_config::ThinStrokesMode,
189 pub(crate) minimum_contrast: f32,
192
193 pub(crate) solid_pixel_offset: (u32, u32),
195
196 pub(crate) transparency_affects_only_default_background: bool,
200
201 pub(crate) keep_text_opaque: bool,
203
204 pub(crate) link_underline_style: par_term_config::LinkUnderlineStyle,
206
207 pub(crate) command_separator_enabled: bool,
210 pub(crate) command_separator_thickness: f32,
212 pub(crate) command_separator_opacity: f32,
214 pub(crate) command_separator_exit_color: bool,
216 pub(crate) command_separator_color: [f32; 3],
218 pub(crate) visible_separator_marks: Vec<SeparatorMark>,
220}
221
222impl CellRenderer {
223 #[allow(clippy::too_many_arguments)]
224 pub async fn new(
225 window: Arc<Window>,
226 font_family: Option<&str>,
227 font_family_bold: Option<&str>,
228 font_family_italic: Option<&str>,
229 font_family_bold_italic: Option<&str>,
230 font_ranges: &[par_term_config::FontRange],
231 font_size: f32,
232 cols: usize,
233 rows: usize,
234 window_padding: f32,
235 line_spacing: f32,
236 char_spacing: f32,
237 scrollbar_position: &str,
238 scrollbar_width: f32,
239 scrollbar_thumb_color: [f32; 4],
240 scrollbar_track_color: [f32; 4],
241 enable_text_shaping: bool,
242 enable_ligatures: bool,
243 enable_kerning: bool,
244 font_antialias: bool,
245 font_hinting: bool,
246 font_thin_strokes: par_term_config::ThinStrokesMode,
247 minimum_contrast: f32,
248 vsync_mode: par_term_config::VsyncMode,
249 power_preference: par_term_config::PowerPreference,
250 window_opacity: f32,
251 background_color: [u8; 3],
252 background_image_path: Option<&str>,
253 background_image_mode: par_term_config::BackgroundImageMode,
254 background_image_opacity: f32,
255 ) -> Result<Self> {
256 #[cfg(target_os = "windows")]
265 let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
266 backends: wgpu::Backends::DX12,
267 ..Default::default()
268 });
269 #[cfg(target_os = "macos")]
270 let instance = wgpu::Instance::default();
271 #[cfg(target_os = "linux")]
272 let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
273 backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
274 ..Default::default()
275 });
276 let surface = instance.create_surface(window.clone())?;
277 let adapter = instance
278 .request_adapter(&wgpu::RequestAdapterOptions {
279 power_preference: power_preference.to_wgpu(),
280 compatible_surface: Some(&surface),
281 force_fallback_adapter: false,
282 })
283 .await
284 .context("Failed to find wgpu adapter")?;
285
286 let (device, queue) = adapter
287 .request_device(&wgpu::DeviceDescriptor {
288 label: Some("device"),
289 required_features: wgpu::Features::empty(),
290 required_limits: wgpu::Limits::default(),
291 memory_hints: wgpu::MemoryHints::default(),
292 ..Default::default()
293 })
294 .await?;
295
296 let device = Arc::new(device);
297 let queue = Arc::new(queue);
298
299 let size = window.inner_size();
300 let surface_caps = surface.get_capabilities(&adapter);
301 let surface_format = surface_caps
302 .formats
303 .iter()
304 .copied()
305 .find(|f| !f.is_srgb())
306 .unwrap_or(surface_caps.formats[0]);
307
308 let supported_present_modes = surface_caps.present_modes.clone();
310
311 let requested_mode = vsync_mode.to_present_mode();
313 let present_mode = if supported_present_modes.contains(&requested_mode) {
314 requested_mode
315 } else {
316 log::warn!(
318 "Requested present mode {:?} not supported (available: {:?}), falling back",
319 requested_mode,
320 supported_present_modes
321 );
322 if supported_present_modes.contains(&wgpu::PresentMode::Fifo) {
323 wgpu::PresentMode::Fifo
324 } else {
325 supported_present_modes[0]
326 }
327 };
328
329 let alpha_mode = if surface_caps
332 .alpha_modes
333 .contains(&wgpu::CompositeAlphaMode::PreMultiplied)
334 {
335 wgpu::CompositeAlphaMode::PreMultiplied
336 } else if surface_caps
337 .alpha_modes
338 .contains(&wgpu::CompositeAlphaMode::PostMultiplied)
339 {
340 wgpu::CompositeAlphaMode::PostMultiplied
341 } else if surface_caps
342 .alpha_modes
343 .contains(&wgpu::CompositeAlphaMode::Auto)
344 {
345 wgpu::CompositeAlphaMode::Auto
346 } else {
347 surface_caps.alpha_modes[0]
348 };
349 log::info!(
350 "Selected alpha mode: {:?} (available: {:?})",
351 alpha_mode,
352 surface_caps.alpha_modes
353 );
354
355 let config = wgpu::SurfaceConfiguration {
356 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
357 format: surface_format,
358 width: size.width.max(1),
359 height: size.height.max(1),
360 present_mode,
361 alpha_mode,
362 view_formats: vec![],
363 desired_maximum_frame_latency: 2,
364 };
365 surface.configure(&device, &config);
366
367 let scale_factor = window.scale_factor() as f32;
368
369 let platform_dpi = if cfg!(target_os = "macos") {
370 72.0
371 } else {
372 96.0
373 };
374
375 let base_font_pixels = font_size * platform_dpi / 72.0;
376 let font_size_pixels = (base_font_pixels * scale_factor).max(1.0);
377
378 let font_manager = FontManager::new(
379 font_family,
380 font_family_bold,
381 font_family_italic,
382 font_family_bold_italic,
383 font_ranges,
384 )?;
385
386 let (font_ascent, font_descent, font_leading, char_advance) = {
388 let primary_font = font_manager.get_font(0).unwrap();
389 let metrics = primary_font.metrics(&[]);
390 let scale = font_size_pixels / metrics.units_per_em as f32;
391 let glyph_id = primary_font.charmap().map('m');
392 let advance = primary_font.glyph_metrics(&[]).advance_width(glyph_id) * scale;
393 (
394 metrics.ascent * scale,
395 metrics.descent * scale,
396 metrics.leading * scale,
397 advance,
398 )
399 };
400
401 let natural_line_height = font_ascent + font_descent + font_leading;
402 let cell_height = (natural_line_height * line_spacing).max(1.0);
403 let cell_width = (char_advance * char_spacing).max(1.0);
404
405 let scrollbar = Scrollbar::new(
406 Arc::clone(&device),
407 surface_format,
408 scrollbar_width,
409 scrollbar_position,
410 scrollbar_thumb_color,
411 scrollbar_track_color,
412 );
413
414 let bg_pipeline = pipeline::create_bg_pipeline(&device, surface_format);
416
417 let (atlas_texture, atlas_view, atlas_sampler) = pipeline::create_atlas(&device);
418 let text_bind_group_layout = pipeline::create_text_bind_group_layout(&device);
419 let text_bind_group = pipeline::create_text_bind_group(
420 &device,
421 &text_bind_group_layout,
422 &atlas_view,
423 &atlas_sampler,
424 );
425 let text_pipeline =
426 pipeline::create_text_pipeline(&device, surface_format, &text_bind_group_layout);
427
428 let bg_image_bind_group_layout = pipeline::create_bg_image_bind_group_layout(&device);
429 let bg_image_pipeline = pipeline::create_bg_image_pipeline(
430 &device,
431 surface_format,
432 &bg_image_bind_group_layout,
433 );
434 let bg_image_uniform_buffer = pipeline::create_bg_image_uniform_buffer(&device);
435
436 let (visual_bell_pipeline, visual_bell_bind_group, _, visual_bell_uniform_buffer) =
437 pipeline::create_visual_bell_pipeline(&device, surface_format);
438
439 let vertex_buffer = pipeline::create_vertex_buffer(&device);
440
441 let max_bg_instances = cols * rows + 10 + rows; let max_text_instances = cols * rows * 2;
444 let (bg_instance_buffer, text_instance_buffer) =
445 pipeline::create_instance_buffers(&device, max_bg_instances, max_text_instances);
446
447 let mut renderer = Self {
448 device,
449 queue,
450 surface,
451 config,
452 supported_present_modes,
453 bg_pipeline,
454 text_pipeline,
455 bg_image_pipeline,
456 visual_bell_pipeline,
457 vertex_buffer,
458 bg_instance_buffer,
459 text_instance_buffer,
460 bg_image_uniform_buffer,
461 visual_bell_uniform_buffer,
462 text_bind_group,
463 text_bind_group_layout,
464 bg_image_bind_group: None,
465 bg_image_bind_group_layout,
466 visual_bell_bind_group,
467 atlas_texture,
468 atlas_view,
469 glyph_cache: HashMap::new(),
470 lru_head: None,
471 lru_tail: None,
472 atlas_next_x: 0,
473 atlas_next_y: 0,
474 atlas_row_height: 0,
475 cols,
476 rows,
477 cell_width,
478 cell_height,
479 window_padding,
480 content_offset_y: 0.0,
481 content_offset_x: 0.0,
482 content_inset_bottom: 0.0,
483 content_inset_right: 0.0,
484 egui_bottom_inset: 0.0,
485 egui_right_inset: 0.0,
486 scale_factor,
487 font_manager,
488 scrollbar,
489 cells: vec![Cell::default(); cols * rows],
490 dirty_rows: vec![true; rows],
491 row_cache: (0..rows).map(|_| None).collect(),
492 cursor_pos: (0, 0),
493 cursor_opacity: 0.0,
494 cursor_style: par_term_emu_core_rust::cursor::CursorStyle::SteadyBlock,
495 cursor_overlay: None,
496 cursor_color: [1.0, 1.0, 1.0],
497 cursor_text_color: None,
498 cursor_hidden_for_shader: false,
499 is_focused: true,
500 cursor_guide_enabled: false,
501 cursor_guide_color: [1.0, 1.0, 1.0, 0.08],
502 cursor_shadow_enabled: false,
503 cursor_shadow_color: [0.0, 0.0, 0.0, 0.5],
504 cursor_shadow_offset: [2.0, 2.0],
505 cursor_shadow_blur: 3.0,
506 cursor_boost: 0.0,
507 cursor_boost_color: [1.0, 1.0, 1.0],
508 unfocused_cursor_style: par_term_config::UnfocusedCursorStyle::default(),
509 visual_bell_intensity: 0.0,
510 window_opacity,
511 background_color: [
512 background_color[0] as f32 / 255.0,
513 background_color[1] as f32 / 255.0,
514 background_color[2] as f32 / 255.0,
515 1.0,
516 ],
517 base_font_size: font_size,
518 line_spacing,
519 char_spacing,
520 font_ascent,
521 font_descent,
522 font_leading,
523 font_size_pixels,
524 char_advance,
525 bg_image_texture: None,
526 bg_image_mode: background_image_mode,
527 bg_image_opacity: background_image_opacity,
528 bg_image_width: 0,
529 bg_image_height: 0,
530 bg_is_solid_color: false,
531 solid_bg_color: [0.0, 0.0, 0.0],
532 pane_bg_cache: HashMap::new(),
533 max_bg_instances,
534 max_text_instances,
535 bg_instances: vec![
536 BackgroundInstance {
537 position: [0.0, 0.0],
538 size: [0.0, 0.0],
539 color: [0.0, 0.0, 0.0, 0.0],
540 };
541 max_bg_instances
542 ],
543 text_instances: vec![
544 TextInstance {
545 position: [0.0, 0.0],
546 size: [0.0, 0.0],
547 tex_offset: [0.0, 0.0],
548 tex_size: [0.0, 0.0],
549 color: [0.0, 0.0, 0.0, 0.0],
550 is_colored: 0,
551 };
552 max_text_instances
553 ],
554 enable_text_shaping,
555 enable_ligatures,
556 enable_kerning,
557 font_antialias,
558 font_hinting,
559 font_thin_strokes,
560 minimum_contrast: minimum_contrast.clamp(1.0, 21.0),
561 solid_pixel_offset: (0, 0),
562 transparency_affects_only_default_background: false,
563 keep_text_opaque: true,
564 link_underline_style: par_term_config::LinkUnderlineStyle::default(),
565 command_separator_enabled: false,
566 command_separator_thickness: 1.0,
567 command_separator_opacity: 0.4,
568 command_separator_exit_color: true,
569 command_separator_color: [0.5, 0.5, 0.5],
570 visible_separator_marks: Vec::new(),
571 };
572
573 renderer.upload_solid_pixel();
575
576 log::info!(
577 "CellRenderer::new: background_image_path={:?}",
578 background_image_path
579 );
580 if let Some(path) = background_image_path {
581 if let Err(e) = renderer.load_background_image(path) {
583 log::warn!(
584 "Could not load background image '{}': {} - continuing without background image",
585 path,
586 e
587 );
588 }
589 }
590
591 Ok(renderer)
592 }
593
594 pub(crate) fn upload_solid_pixel(&mut self) {
596 let size = 2u32; let white_pixels: Vec<u8> = vec![255; (size * size * 4) as usize];
598
599 self.queue.write_texture(
600 wgpu::TexelCopyTextureInfo {
601 texture: &self.atlas_texture,
602 mip_level: 0,
603 origin: wgpu::Origin3d {
604 x: self.atlas_next_x,
605 y: self.atlas_next_y,
606 z: 0,
607 },
608 aspect: wgpu::TextureAspect::All,
609 },
610 &white_pixels,
611 wgpu::TexelCopyBufferLayout {
612 offset: 0,
613 bytes_per_row: Some(4 * size),
614 rows_per_image: Some(size),
615 },
616 wgpu::Extent3d {
617 width: size,
618 height: size,
619 depth_or_array_layers: 1,
620 },
621 );
622
623 self.solid_pixel_offset = (self.atlas_next_x, self.atlas_next_y);
624 self.atlas_next_x += size + 2; self.atlas_row_height = self.atlas_row_height.max(size);
626 }
627
628 pub fn device(&self) -> &wgpu::Device {
629 &self.device
630 }
631 pub fn queue(&self) -> &wgpu::Queue {
632 &self.queue
633 }
634 pub fn surface_format(&self) -> wgpu::TextureFormat {
635 self.config.format
636 }
637 pub fn cell_width(&self) -> f32 {
638 self.cell_width
639 }
640 pub fn cell_height(&self) -> f32 {
641 self.cell_height
642 }
643 pub fn window_padding(&self) -> f32 {
644 self.window_padding
645 }
646 pub fn content_offset_y(&self) -> f32 {
647 self.content_offset_y
648 }
649 pub fn set_content_offset_y(&mut self, offset: f32) -> Option<(usize, usize)> {
652 if (self.content_offset_y - offset).abs() > f32::EPSILON {
653 self.content_offset_y = offset;
654 let size = (self.config.width, self.config.height);
655 return Some(self.resize(size.0, size.1));
656 }
657 None
658 }
659 pub fn content_offset_x(&self) -> f32 {
660 self.content_offset_x
661 }
662 pub fn set_content_offset_x(&mut self, offset: f32) -> Option<(usize, usize)> {
665 if (self.content_offset_x - offset).abs() > f32::EPSILON {
666 self.content_offset_x = offset;
667 let size = (self.config.width, self.config.height);
668 return Some(self.resize(size.0, size.1));
669 }
670 None
671 }
672 pub fn content_inset_bottom(&self) -> f32 {
673 self.content_inset_bottom
674 }
675 pub fn set_content_inset_bottom(&mut self, inset: f32) -> Option<(usize, usize)> {
678 if (self.content_inset_bottom - inset).abs() > f32::EPSILON {
679 self.content_inset_bottom = inset;
680 let size = (self.config.width, self.config.height);
681 return Some(self.resize(size.0, size.1));
682 }
683 None
684 }
685 pub fn content_inset_right(&self) -> f32 {
686 self.content_inset_right
687 }
688 pub fn set_content_inset_right(&mut self, inset: f32) -> Option<(usize, usize)> {
691 if (self.content_inset_right - inset).abs() > f32::EPSILON {
692 log::info!(
693 "[SCROLLBAR] set_content_inset_right: {:.1} -> {:.1} (physical px)",
694 self.content_inset_right,
695 inset
696 );
697 self.content_inset_right = inset;
698 let size = (self.config.width, self.config.height);
699 return Some(self.resize(size.0, size.1));
700 }
701 None
702 }
703 pub fn grid_size(&self) -> (usize, usize) {
704 (self.cols, self.rows)
705 }
706 pub fn keep_text_opaque(&self) -> bool {
707 self.keep_text_opaque
708 }
709
710 pub fn resize(&mut self, width: u32, height: u32) -> (usize, usize) {
711 if width == 0 || height == 0 {
712 return (self.cols, self.rows);
713 }
714 self.config.width = width;
715 self.config.height = height;
716 self.surface.configure(&self.device, &self.config);
717
718 let available_width = (width as f32
719 - self.window_padding * 2.0
720 - self.content_offset_x
721 - self.content_inset_right)
722 .max(0.0);
723 let available_height = (height as f32
724 - self.window_padding * 2.0
725 - self.content_offset_y
726 - self.content_inset_bottom
727 - self.egui_bottom_inset)
728 .max(0.0);
729 let new_cols = (available_width / self.cell_width).max(1.0) as usize;
730 let new_rows = (available_height / self.cell_height).max(1.0) as usize;
731
732 if new_cols != self.cols || new_rows != self.rows {
733 self.cols = new_cols;
734 self.rows = new_rows;
735 self.cells = vec![Cell::default(); self.cols * self.rows];
736 self.dirty_rows = vec![true; self.rows];
737 self.row_cache = (0..self.rows).map(|_| None).collect();
738 self.recreate_instance_buffers();
739 }
740
741 self.update_bg_image_uniforms();
742 (self.cols, self.rows)
743 }
744
745 fn recreate_instance_buffers(&mut self) {
746 self.max_bg_instances = self.cols * self.rows + 10 + self.rows; self.max_text_instances = self.cols * self.rows * 2;
748 let (bg_buf, text_buf) = pipeline::create_instance_buffers(
749 &self.device,
750 self.max_bg_instances,
751 self.max_text_instances,
752 );
753 self.bg_instance_buffer = bg_buf;
754 self.text_instance_buffer = text_buf;
755
756 self.bg_instances = vec![
757 BackgroundInstance {
758 position: [0.0, 0.0],
759 size: [0.0, 0.0],
760 color: [0.0, 0.0, 0.0, 0.0],
761 };
762 self.max_bg_instances
763 ];
764 self.text_instances = vec![
765 TextInstance {
766 position: [0.0, 0.0],
767 size: [0.0, 0.0],
768 tex_offset: [0.0, 0.0],
769 tex_size: [0.0, 0.0],
770 color: [0.0, 0.0, 0.0, 0.0],
771 is_colored: 0,
772 };
773 self.max_text_instances
774 ];
775 }
776
777 pub fn update_cells(&mut self, new_cells: &[Cell]) {
778 for row in 0..self.rows {
779 let start = row * self.cols;
780 let end = (row + 1) * self.cols;
781 if start < new_cells.len() && end <= new_cells.len() {
782 let row_slice = &new_cells[start..end];
783 if row_slice != &self.cells[start..end] {
784 self.cells[start..end].clone_from_slice(row_slice);
785 self.dirty_rows[row] = true;
786 }
787 }
788 }
789 }
790
791 pub fn clear_all_cells(&mut self) {
793 for cell in &mut self.cells {
794 *cell = Cell::default();
795 }
796 for dirty in &mut self.dirty_rows {
797 *dirty = true;
798 }
799 }
800
801 pub fn update_cursor(
802 &mut self,
803 pos: (usize, usize),
804 opacity: f32,
805 style: par_term_emu_core_rust::cursor::CursorStyle,
806 ) {
807 if self.cursor_pos != pos || self.cursor_opacity != opacity || self.cursor_style != style {
808 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
809 self.cursor_pos = pos;
810 self.cursor_opacity = opacity;
811 self.cursor_style = style;
812 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
813
814 use par_term_emu_core_rust::cursor::CursorStyle;
816 self.cursor_overlay = if opacity > 0.0 {
817 let col = pos.0;
818 let row = pos.1;
819 let x0 =
820 (self.window_padding + self.content_offset_x + col as f32 * self.cell_width)
821 .round();
822 let x1 = (self.window_padding
823 + self.content_offset_x
824 + (col + 1) as f32 * self.cell_width)
825 .round();
826 let y0 =
827 (self.window_padding + self.content_offset_y + row as f32 * self.cell_height)
828 .round();
829 let y1 = (self.window_padding
830 + self.content_offset_y
831 + (row + 1) as f32 * self.cell_height)
832 .round();
833
834 match style {
835 CursorStyle::SteadyBlock | CursorStyle::BlinkingBlock => None,
836 CursorStyle::SteadyBar | CursorStyle::BlinkingBar => Some(BackgroundInstance {
837 position: [
838 x0 / self.config.width as f32 * 2.0 - 1.0,
839 1.0 - (y0 / self.config.height as f32 * 2.0),
840 ],
841 size: [
842 2.0 / self.config.width as f32 * 2.0,
843 (y1 - y0) / self.config.height as f32 * 2.0,
844 ],
845 color: [
846 self.cursor_color[0],
847 self.cursor_color[1],
848 self.cursor_color[2],
849 opacity,
850 ],
851 }),
852 CursorStyle::SteadyUnderline | CursorStyle::BlinkingUnderline => {
853 Some(BackgroundInstance {
854 position: [
855 x0 / self.config.width as f32 * 2.0 - 1.0,
856 1.0 - ((y1 - 2.0) / self.config.height as f32 * 2.0),
857 ],
858 size: [
859 (x1 - x0) / self.config.width as f32 * 2.0,
860 2.0 / self.config.height as f32 * 2.0,
861 ],
862 color: [
863 self.cursor_color[0],
864 self.cursor_color[1],
865 self.cursor_color[2],
866 opacity,
867 ],
868 })
869 }
870 }
871 } else {
872 None
873 };
874 }
875 }
876
877 pub fn clear_cursor(&mut self) {
878 self.update_cursor(self.cursor_pos, 0.0, self.cursor_style);
879 }
880
881 pub fn update_cursor_color(&mut self, color: [u8; 3]) {
883 self.cursor_color = [
884 color[0] as f32 / 255.0,
885 color[1] as f32 / 255.0,
886 color[2] as f32 / 255.0,
887 ];
888 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
889 }
890
891 pub fn update_cursor_text_color(&mut self, color: Option<[u8; 3]>) {
893 self.cursor_text_color = color.map(|c| {
894 [
895 c[0] as f32 / 255.0,
896 c[1] as f32 / 255.0,
897 c[2] as f32 / 255.0,
898 ]
899 });
900 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
901 }
902
903 pub fn set_cursor_hidden_for_shader(&mut self, hidden: bool) {
905 if self.cursor_hidden_for_shader != hidden {
906 self.cursor_hidden_for_shader = hidden;
907 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
908 }
909 }
910
911 pub fn set_focused(&mut self, focused: bool) {
913 if self.is_focused != focused {
914 self.is_focused = focused;
915 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
916 }
917 }
918
919 pub fn update_cursor_guide(&mut self, enabled: bool, color: [u8; 4]) {
921 self.cursor_guide_enabled = enabled;
922 self.cursor_guide_color = [
923 color[0] as f32 / 255.0,
924 color[1] as f32 / 255.0,
925 color[2] as f32 / 255.0,
926 color[3] as f32 / 255.0,
927 ];
928 if enabled {
929 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
930 }
931 }
932
933 pub fn update_cursor_shadow(
935 &mut self,
936 enabled: bool,
937 color: [u8; 4],
938 offset: [f32; 2],
939 blur: f32,
940 ) {
941 self.cursor_shadow_enabled = enabled;
942 self.cursor_shadow_color = [
943 color[0] as f32 / 255.0,
944 color[1] as f32 / 255.0,
945 color[2] as f32 / 255.0,
946 color[3] as f32 / 255.0,
947 ];
948 self.cursor_shadow_offset = offset;
949 self.cursor_shadow_blur = blur;
950 if enabled {
951 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
952 }
953 }
954
955 pub fn update_cursor_boost(&mut self, intensity: f32, color: [u8; 3]) {
957 self.cursor_boost = intensity.clamp(0.0, 1.0);
958 self.cursor_boost_color = [
959 color[0] as f32 / 255.0,
960 color[1] as f32 / 255.0,
961 color[2] as f32 / 255.0,
962 ];
963 if intensity > 0.0 {
964 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
965 }
966 }
967
968 pub fn update_unfocused_cursor_style(&mut self, style: par_term_config::UnfocusedCursorStyle) {
970 self.unfocused_cursor_style = style;
971 if !self.is_focused {
972 self.dirty_rows[self.cursor_pos.1.min(self.rows - 1)] = true;
973 }
974 }
975
976 pub fn update_scrollbar(
977 &mut self,
978 scroll_offset: usize,
979 visible_lines: usize,
980 total_lines: usize,
981 marks: &[par_term_config::ScrollbackMark],
982 ) {
983 let right_inset = self.content_inset_right + self.egui_right_inset;
984 self.scrollbar.update(
985 &self.queue,
986 scroll_offset,
987 visible_lines,
988 total_lines,
989 self.config.width,
990 self.config.height,
991 self.content_offset_y,
992 self.content_inset_bottom + self.egui_bottom_inset,
993 right_inset,
994 marks,
995 );
996 }
997
998 pub fn set_visual_bell_intensity(&mut self, intensity: f32) {
999 self.visual_bell_intensity = intensity;
1000 }
1001
1002 pub fn update_opacity(&mut self, opacity: f32) {
1003 self.window_opacity = opacity;
1004 self.update_bg_image_uniforms();
1007 }
1008
1009 pub fn set_transparency_affects_only_default_background(&mut self, value: bool) {
1012 if self.transparency_affects_only_default_background != value {
1013 log::info!(
1014 "transparency_affects_only_default_background: {} -> {} (window_opacity={})",
1015 self.transparency_affects_only_default_background,
1016 value,
1017 self.window_opacity
1018 );
1019 self.transparency_affects_only_default_background = value;
1020 self.dirty_rows.fill(true);
1022 }
1023 }
1024
1025 pub fn set_keep_text_opaque(&mut self, value: bool) {
1028 if self.keep_text_opaque != value {
1029 log::info!(
1030 "keep_text_opaque: {} -> {} (window_opacity={}, transparency_affects_only_default_bg={})",
1031 self.keep_text_opaque,
1032 value,
1033 self.window_opacity,
1034 self.transparency_affects_only_default_background
1035 );
1036 self.keep_text_opaque = value;
1037 self.dirty_rows.fill(true);
1039 }
1040 }
1041
1042 pub fn set_link_underline_style(&mut self, style: par_term_config::LinkUnderlineStyle) {
1043 if self.link_underline_style != style {
1044 self.link_underline_style = style;
1045 self.dirty_rows.fill(true);
1046 }
1047 }
1048
1049 pub fn update_command_separator(
1051 &mut self,
1052 enabled: bool,
1053 thickness: f32,
1054 opacity: f32,
1055 exit_color: bool,
1056 color: [u8; 3],
1057 ) {
1058 self.command_separator_enabled = enabled;
1059 self.command_separator_thickness = thickness;
1060 self.command_separator_opacity = opacity;
1061 self.command_separator_exit_color = exit_color;
1062 self.command_separator_color = [
1063 color[0] as f32 / 255.0,
1064 color[1] as f32 / 255.0,
1065 color[2] as f32 / 255.0,
1066 ];
1067 }
1068
1069 pub fn set_separator_marks(&mut self, marks: Vec<SeparatorMark>) {
1071 self.visible_separator_marks = marks;
1072 }
1073
1074 fn separator_color(
1076 &self,
1077 exit_code: Option<i32>,
1078 custom_color: Option<(u8, u8, u8)>,
1079 opacity_mult: f32,
1080 ) -> [f32; 4] {
1081 let alpha = self.command_separator_opacity * opacity_mult;
1082 if let Some((r, g, b)) = custom_color {
1084 return [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, alpha];
1085 }
1086 if self.command_separator_exit_color {
1087 match exit_code {
1088 Some(0) => [0.3, 0.75, 0.3, alpha], Some(_) => [0.85, 0.25, 0.25, alpha], None => [0.5, 0.5, 0.5, alpha], }
1092 } else {
1093 [
1094 self.command_separator_color[0],
1095 self.command_separator_color[1],
1096 self.command_separator_color[2],
1097 alpha,
1098 ]
1099 }
1100 }
1101
1102 pub fn update_scale_factor(&mut self, scale_factor: f64) {
1105 let new_scale = scale_factor as f32;
1106
1107 if (self.scale_factor - new_scale).abs() < f32::EPSILON {
1109 return;
1110 }
1111
1112 log::info!(
1113 "Recalculating font metrics for scale factor change: {} -> {}",
1114 self.scale_factor,
1115 new_scale
1116 );
1117
1118 self.scale_factor = new_scale;
1119
1120 let platform_dpi = if cfg!(target_os = "macos") {
1122 72.0
1123 } else {
1124 96.0
1125 };
1126 let base_font_pixels = self.base_font_size * platform_dpi / 72.0;
1127 self.font_size_pixels = (base_font_pixels * new_scale).max(1.0);
1128
1129 let (font_ascent, font_descent, font_leading, char_advance) = {
1131 let primary_font = self.font_manager.get_font(0).unwrap();
1132 let metrics = primary_font.metrics(&[]);
1133 let scale = self.font_size_pixels / metrics.units_per_em as f32;
1134 let glyph_id = primary_font.charmap().map('m');
1135 let advance = primary_font.glyph_metrics(&[]).advance_width(glyph_id) * scale;
1136 (
1137 metrics.ascent * scale,
1138 metrics.descent * scale,
1139 metrics.leading * scale,
1140 advance,
1141 )
1142 };
1143
1144 self.font_ascent = font_ascent;
1145 self.font_descent = font_descent;
1146 self.font_leading = font_leading;
1147 self.char_advance = char_advance;
1148
1149 let natural_line_height = font_ascent + font_descent + font_leading;
1151 self.cell_height = (natural_line_height * self.line_spacing).max(1.0);
1152 self.cell_width = (char_advance * self.char_spacing).max(1.0);
1153
1154 log::info!(
1155 "New cell dimensions: {}x{} (font_size_pixels: {})",
1156 self.cell_width,
1157 self.cell_height,
1158 self.font_size_pixels
1159 );
1160
1161 self.clear_glyph_cache();
1163
1164 self.dirty_rows.fill(true);
1166 }
1167
1168 #[allow(dead_code)]
1169 pub fn update_window_padding(&mut self, padding: f32) -> Option<(usize, usize)> {
1170 if (self.window_padding - padding).abs() > f32::EPSILON {
1171 self.window_padding = padding;
1172 let size = (self.config.width, self.config.height);
1173 return Some(self.resize(size.0, size.1));
1174 }
1175 None
1176 }
1177
1178 pub fn update_scrollbar_appearance(
1179 &mut self,
1180 width: f32,
1181 thumb_color: [f32; 4],
1182 track_color: [f32; 4],
1183 ) {
1184 self.scrollbar
1185 .update_appearance(width, thumb_color, track_color);
1186 }
1187
1188 pub fn update_scrollbar_position(&mut self, position: &str) {
1189 self.scrollbar.update_position(position);
1190 }
1191
1192 pub fn scrollbar_contains_point(&self, x: f32, y: f32) -> bool {
1193 self.scrollbar.contains_point(x, y)
1194 }
1195
1196 pub fn scrollbar_thumb_bounds(&self) -> Option<(f32, f32)> {
1197 self.scrollbar.thumb_bounds()
1198 }
1199
1200 pub fn scrollbar_track_contains_x(&self, x: f32) -> bool {
1201 self.scrollbar.track_contains_x(x)
1202 }
1203
1204 pub fn scrollbar_mouse_y_to_scroll_offset(&self, mouse_y: f32) -> Option<usize> {
1205 self.scrollbar.mouse_y_to_scroll_offset(mouse_y)
1206 }
1207
1208 pub fn scrollbar_mark_at_position(
1211 &self,
1212 mouse_x: f32,
1213 mouse_y: f32,
1214 tolerance: f32,
1215 ) -> Option<&par_term_config::ScrollbackMark> {
1216 self.scrollbar.mark_at_position(mouse_x, mouse_y, tolerance)
1217 }
1218
1219 pub fn reconfigure_surface(&mut self) {
1220 self.surface.configure(&self.device, &self.config);
1221 }
1222
1223 pub fn update_font_antialias(&mut self, enabled: bool) -> bool {
1226 if self.font_antialias != enabled {
1227 self.font_antialias = enabled;
1228 self.clear_glyph_cache();
1229 self.dirty_rows.fill(true);
1230 true
1231 } else {
1232 false
1233 }
1234 }
1235
1236 pub fn update_font_hinting(&mut self, enabled: bool) -> bool {
1239 if self.font_hinting != enabled {
1240 self.font_hinting = enabled;
1241 self.clear_glyph_cache();
1242 self.dirty_rows.fill(true);
1243 true
1244 } else {
1245 false
1246 }
1247 }
1248
1249 pub fn update_font_thin_strokes(&mut self, mode: par_term_config::ThinStrokesMode) -> bool {
1252 if self.font_thin_strokes != mode {
1253 self.font_thin_strokes = mode;
1254 self.clear_glyph_cache();
1255 self.dirty_rows.fill(true);
1256 true
1257 } else {
1258 false
1259 }
1260 }
1261
1262 pub fn update_minimum_contrast(&mut self, ratio: f32) -> bool {
1265 let ratio = ratio.clamp(1.0, 21.0);
1267 if (self.minimum_contrast - ratio).abs() > 0.001 {
1268 self.minimum_contrast = ratio;
1269 self.dirty_rows.fill(true);
1270 true
1271 } else {
1272 false
1273 }
1274 }
1275
1276 pub(crate) fn ensure_minimum_contrast(&self, fg: [f32; 4], bg: [f32; 4]) -> [f32; 4] {
1280 if self.minimum_contrast <= 1.0 {
1282 return fg;
1283 }
1284
1285 fn luminance(color: [f32; 4]) -> f32 {
1287 let r = color[0].powf(2.2);
1288 let g = color[1].powf(2.2);
1289 let b = color[2].powf(2.2);
1290 0.2126 * r + 0.7152 * g + 0.0722 * b
1291 }
1292
1293 fn contrast_ratio(l1: f32, l2: f32) -> f32 {
1294 let (lighter, darker) = if l1 > l2 { (l1, l2) } else { (l2, l1) };
1295 (lighter + 0.05) / (darker + 0.05)
1296 }
1297
1298 let fg_lum = luminance(fg);
1299 let bg_lum = luminance(bg);
1300 let current_ratio = contrast_ratio(fg_lum, bg_lum);
1301
1302 if current_ratio >= self.minimum_contrast {
1304 return fg;
1305 }
1306
1307 let bg_is_dark = bg_lum < 0.5;
1310
1311 let mut low = 0.0f32;
1313 let mut high = 1.0f32;
1314
1315 for _ in 0..20 {
1316 let mid = (low + high) / 2.0;
1318
1319 let adjusted = if bg_is_dark {
1320 [
1322 fg[0] + (1.0 - fg[0]) * mid,
1323 fg[1] + (1.0 - fg[1]) * mid,
1324 fg[2] + (1.0 - fg[2]) * mid,
1325 fg[3],
1326 ]
1327 } else {
1328 [
1330 fg[0] * (1.0 - mid),
1331 fg[1] * (1.0 - mid),
1332 fg[2] * (1.0 - mid),
1333 fg[3],
1334 ]
1335 };
1336
1337 let adjusted_lum = luminance(adjusted);
1338 let new_ratio = contrast_ratio(adjusted_lum, bg_lum);
1339
1340 if new_ratio >= self.minimum_contrast {
1341 high = mid;
1342 } else {
1343 low = mid;
1344 }
1345 }
1346
1347 if bg_is_dark {
1349 [
1350 fg[0] + (1.0 - fg[0]) * high,
1351 fg[1] + (1.0 - fg[1]) * high,
1352 fg[2] + (1.0 - fg[2]) * high,
1353 fg[3],
1354 ]
1355 } else {
1356 [
1357 fg[0] * (1.0 - high),
1358 fg[1] * (1.0 - high),
1359 fg[2] * (1.0 - high),
1360 fg[3],
1361 ]
1362 }
1363 }
1364
1365 pub(crate) fn should_use_thin_strokes(&self) -> bool {
1367 use par_term_config::ThinStrokesMode;
1368
1369 let is_retina = self.scale_factor > 1.5;
1371
1372 let bg_brightness =
1374 (self.background_color[0] + self.background_color[1] + self.background_color[2]) / 3.0;
1375 let is_dark_background = bg_brightness < 0.5;
1376
1377 match self.font_thin_strokes {
1378 ThinStrokesMode::Never => false,
1379 ThinStrokesMode::Always => true,
1380 ThinStrokesMode::RetinaOnly => is_retina,
1381 ThinStrokesMode::DarkBackgroundsOnly => is_dark_background,
1382 ThinStrokesMode::RetinaDarkBackgroundsOnly => is_retina && is_dark_background,
1383 }
1384 }
1385
1386 #[allow(dead_code)]
1388 pub fn supported_present_modes(&self) -> &[wgpu::PresentMode] {
1389 &self.supported_present_modes
1390 }
1391
1392 pub fn is_vsync_mode_supported(&self, mode: par_term_config::VsyncMode) -> bool {
1394 self.supported_present_modes
1395 .contains(&mode.to_present_mode())
1396 }
1397
1398 pub fn update_vsync_mode(
1401 &mut self,
1402 mode: par_term_config::VsyncMode,
1403 ) -> (par_term_config::VsyncMode, bool) {
1404 let requested = mode.to_present_mode();
1405 let current = self.config.present_mode;
1406
1407 let actual = if self.supported_present_modes.contains(&requested) {
1409 requested
1410 } else {
1411 log::warn!(
1412 "Requested present mode {:?} not supported, falling back to Fifo",
1413 requested
1414 );
1415 wgpu::PresentMode::Fifo
1416 };
1417
1418 if actual != current {
1420 self.config.present_mode = actual;
1421 self.surface.configure(&self.device, &self.config);
1422 log::info!("VSync mode changed to {:?}", actual);
1423 }
1424
1425 let actual_vsync = match actual {
1427 wgpu::PresentMode::Immediate => par_term_config::VsyncMode::Immediate,
1428 wgpu::PresentMode::Mailbox => par_term_config::VsyncMode::Mailbox,
1429 wgpu::PresentMode::Fifo | wgpu::PresentMode::FifoRelaxed => {
1430 par_term_config::VsyncMode::Fifo
1431 }
1432 _ => par_term_config::VsyncMode::Fifo,
1433 };
1434
1435 (actual_vsync, actual != current)
1436 }
1437
1438 #[allow(dead_code)]
1440 pub fn current_vsync_mode(&self) -> par_term_config::VsyncMode {
1441 match self.config.present_mode {
1442 wgpu::PresentMode::Immediate => par_term_config::VsyncMode::Immediate,
1443 wgpu::PresentMode::Mailbox => par_term_config::VsyncMode::Mailbox,
1444 wgpu::PresentMode::Fifo | wgpu::PresentMode::FifoRelaxed => {
1445 par_term_config::VsyncMode::Fifo
1446 }
1447 _ => par_term_config::VsyncMode::Fifo,
1448 }
1449 }
1450
1451 #[allow(dead_code)]
1452 pub fn update_graphics(
1453 &mut self,
1454 _graphics: &[par_term_emu_core_rust::graphics::TerminalGraphic],
1455 _scroll_offset: usize,
1456 _scrollback_len: usize,
1457 _visible_lines: usize,
1458 ) -> Result<()> {
1459 Ok(())
1460 }
1461}