Skip to main content

code_atlas/
render.rs

1use std::{
2    fmt, fs,
3    path::Path,
4    str::FromStr,
5    time::{Instant, SystemTime, UNIX_EPOCH},
6};
7
8use anyhow::{Context, Result, bail, ensure};
9use fontdue::{Font, FontSettings};
10use serde::{Deserialize, Serialize};
11use tiny_skia::{
12    BlendMode, Color, FillRule, LineCap, LineJoin, Paint, Path as SkiaPath, PathBuilder, Pixmap,
13    PixmapPaint, Stroke, Transform,
14};
15
16use crate::{
17    layout::{LayoutOptions, call_control_points, call_curve, sample_rect},
18    model::{Atlas, NodeKind, Point, Rect},
19};
20
21pub(crate) const DENSITY_KNEE_MULTIPLIER: usize = 4;
22pub(crate) const DENSE_EXPOSURE_EXPONENT: f64 = 1.05;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum RenderBackend {
26    Software,
27    Wgpu,
28}
29
30impl FromStr for RenderBackend {
31    type Err = anyhow::Error;
32
33    fn from_str(value: &str) -> Result<Self> {
34        match value {
35            "software" | "cpu" => Ok(Self::Software),
36            "wgpu" | "gpu" => Ok(Self::Wgpu),
37            _ => bail!("unknown render backend {value:?}; expected software or wgpu"),
38        }
39    }
40}
41
42impl fmt::Display for RenderBackend {
43    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44        formatter.write_str(match self {
45            Self::Software => "software",
46            Self::Wgpu => "wgpu",
47        })
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Theme {
53    Architect,
54    Night,
55    Ink,
56    SolarizedDark,
57    SolarizedLight,
58}
59
60impl FromStr for Theme {
61    type Err = anyhow::Error;
62
63    fn from_str(value: &str) -> Result<Self> {
64        match value {
65            "architect" | "architect-pencil" | "pencil" => Ok(Self::Architect),
66            "night" | "night-transit" => Ok(Self::Night),
67            "ink" | "ink-transit" => Ok(Self::Ink),
68            "solarized-dark" => Ok(Self::SolarizedDark),
69            "solarized-light" => Ok(Self::SolarizedLight),
70            _ => bail!(
71                "unknown theme {value:?}; expected architect, night, ink, solarized-dark, or solarized-light"
72            ),
73        }
74    }
75}
76
77impl fmt::Display for Theme {
78    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79        formatter.write_str(match self {
80            Self::Architect => "architect",
81            Self::Night => "night",
82            Self::Ink => "ink",
83            Self::SolarizedDark => "solarized-dark",
84            Self::SolarizedLight => "solarized-light",
85        })
86    }
87}
88
89#[derive(Debug, Clone)]
90pub struct RenderOptions {
91    pub backend: RenderBackend,
92    pub theme: Theme,
93    /// Optional HTTP(S) template used by interactive HTML endpoint links.
94    /// It must contain `{revision}`, `{path}`, and `{line}` placeholders.
95    pub source_url_template: Option<String>,
96    pub call_opacity: u8,
97    pub call_width: f32,
98    pub boundary_width: f32,
99    /// Reduce per-call pigment on very large graphs while preserving every
100    /// independently composited stroke and its cumulative darkening.
101    pub density_aware_exposure: bool,
102    pub density_reference_calls: usize,
103    /// Physical resolution used to convert raster pixels to PDF points.
104    pub pdf_dpi: f64,
105    /// Optional independent resolution for the raster call layer embedded in
106    /// PDF output. The page geometry continues to use `pdf_dpi`.
107    pub pdf_call_dpi: Option<f64>,
108    /// Maximum core width and height of one PDF call-layer tile in pixels.
109    pub pdf_call_tile_size: u32,
110    /// Retain and reuse checksummed PDF call-layer tiles beside the output.
111    pub pdf_resume: bool,
112    /// Discard an existing PDF tile cache before starting a resumable render.
113    pub pdf_restart: bool,
114    /// Internal deterministic interruption hook used by resume tests.
115    pub pdf_stop_after_tiles: Option<usize>,
116    /// Maximum concurrent PDF tile compression jobs. Zero selects a bounded
117    /// hardware-aware default.
118    pub pdf_compression_workers: usize,
119}
120
121impl Default for RenderOptions {
122    fn default() -> Self {
123        Self {
124            backend: RenderBackend::Software,
125            theme: Theme::Architect,
126            source_url_template: None,
127            call_opacity: 34,
128            call_width: 1.10,
129            boundary_width: 0.62,
130            density_aware_exposure: true,
131            density_reference_calls: 2_500,
132            pdf_dpi: 144.0,
133            pdf_call_dpi: None,
134            pdf_call_tile_size: 2_048,
135            pdf_resume: false,
136            pdf_restart: false,
137            pdf_stop_after_tiles: None,
138            pdf_compression_workers: 0,
139        }
140    }
141}
142
143#[derive(Debug, Clone, Default, Serialize, Deserialize)]
144pub struct PdfTileTimingStats {
145    pub planning_ms: u64,
146    pub scene_prepare_ms: u64,
147    pub spline_evaluation_gpu_ms: Option<f64>,
148    pub rasterization_gpu_ms: Option<f64>,
149    pub render_and_readback_ms: u64,
150    pub rgba_split_ms: u64,
151    pub compression_ms: u64,
152    pub cache_write_ms: u64,
153    pub pdf_assembly_ms: u64,
154    /// Wall time of the overlapped render/split/compress/write pipeline.
155    pub tile_pipeline_wall_ms: u64,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct PdfTileCacheStats {
160    pub enabled: bool,
161    pub cache_key: String,
162    pub manifest_path: String,
163    pub tiles_rendered: usize,
164    pub tiles_reused: usize,
165    pub compression_workers: usize,
166    pub max_in_flight_tiles: usize,
167    pub compression_codec: String,
168    pub compression_level: i32,
169    pub timings: PdfTileTimingStats,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct RenderStats {
174    pub backend: String,
175    pub gpu_adapter: Option<String>,
176    pub width: u32,
177    pub height: u32,
178    pub call_layer_width: u32,
179    pub call_layer_height: u32,
180    pub call_layer_dpi: Option<f64>,
181    pub call_layer_tiles: usize,
182    pub call_layer_tile_size: Option<u32>,
183    pub call_layer_overlap: Option<u32>,
184    pub files_drawn: usize,
185    pub file_labels_drawn: usize,
186    pub directory_labels_drawn: usize,
187    pub calls_drawn: usize,
188    pub directory_boundaries_drawn: usize,
189    pub output_bytes: u64,
190    pub effective_call_opacity: u8,
191    pub call_compositing: String,
192    pub direction_source_color: String,
193    pub direction_target_color: String,
194    pub render_ms: u64,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub pdf_tile_cache: Option<PdfTileCacheStats>,
197}
198
199pub fn render_png(
200    atlas: &Atlas,
201    output: &Path,
202    layout_options: &LayoutOptions,
203    render_options: &RenderOptions,
204) -> Result<RenderStats> {
205    match render_options.backend {
206        RenderBackend::Software => {
207            render_software_png(atlas, output, layout_options, render_options)
208        }
209        RenderBackend::Wgpu => {
210            match crate::render_wgpu::render_wgpu_png(atlas, output, layout_options, render_options)
211            {
212                Ok(stats) => Ok(stats),
213                Err(error) if gpu_is_unavailable(&error) => {
214                    eprintln!(
215                        "wgpu is unavailable ({error:#}); falling back to the software call renderer"
216                    );
217                    let mut stats =
218                        render_software_png(atlas, output, layout_options, render_options)?;
219                    stats.backend = "software (wgpu unavailable)".to_owned();
220                    Ok(stats)
221                }
222                Err(error) => Err(error),
223            }
224        }
225    }
226}
227
228pub fn render_output(
229    atlas: &Atlas,
230    output: &Path,
231    layout_options: &LayoutOptions,
232    render_options: &RenderOptions,
233) -> Result<RenderStats> {
234    match output
235        .extension()
236        .and_then(|extension| extension.to_str())
237        .unwrap_or_default()
238        .to_ascii_lowercase()
239        .as_str()
240    {
241        "png" => render_png(atlas, output, layout_options, render_options),
242        "svg" | "pdf" => {
243            crate::export::render_vector_artifact(atlas, output, layout_options, render_options)
244        }
245        "html" | "htm" => {
246            crate::html::render_interactive_html(atlas, output, layout_options, render_options)
247        }
248        extension => {
249            bail!("unsupported output extension {extension:?}; expected .png, .svg, .pdf, or .html")
250        }
251    }
252}
253
254pub(crate) fn render_call_layer_png(
255    atlas: &Atlas,
256    output: &Path,
257    layout_options: &LayoutOptions,
258    render_options: &RenderOptions,
259) -> Result<RenderStats> {
260    match render_options.backend {
261        RenderBackend::Software => {
262            render_software_call_layer_png(atlas, output, layout_options, render_options)
263        }
264        RenderBackend::Wgpu => match crate::render_wgpu::render_wgpu_call_layer_png(
265            atlas,
266            output,
267            layout_options,
268            render_options,
269        ) {
270            Ok(stats) => Ok(stats),
271            Err(error) if gpu_is_unavailable(&error) => {
272                eprintln!(
273                    "wgpu is unavailable ({error:#}); falling back to the software call renderer"
274                );
275                let mut stats =
276                    render_software_call_layer_png(atlas, output, layout_options, render_options)?;
277                stats.backend = "software (wgpu unavailable)".to_owned();
278                Ok(stats)
279            }
280            Err(error) => Err(error),
281        },
282    }
283}
284
285pub(crate) fn gpu_is_unavailable(error: &anyhow::Error) -> bool {
286    let message = format!("{error:#}");
287    message.contains("no compatible GPU adapter")
288        || message.contains("No suitable graphics adapter")
289        || message.contains("does not support blendable RGBA16Float")
290        || message.contains("does not support 4x multisampled RGBA16Float")
291        || message.contains("exceeds the adapter's")
292        || message.contains("GPU spline scene exceeds")
293}
294
295pub(crate) fn render_software_png(
296    atlas: &Atlas,
297    output: &Path,
298    layout_options: &LayoutOptions,
299    render_options: &RenderOptions,
300) -> Result<RenderStats> {
301    render_software_png_inner(atlas, output, layout_options, render_options, true, true)
302}
303
304pub(crate) fn render_software_base_png(
305    atlas: &Atlas,
306    output: &Path,
307    layout_options: &LayoutOptions,
308    render_options: &RenderOptions,
309) -> Result<RenderStats> {
310    render_software_png_inner(atlas, output, layout_options, render_options, false, false)
311}
312
313pub(crate) fn render_software_call_layer_png(
314    atlas: &Atlas,
315    output: &Path,
316    layout_options: &LayoutOptions,
317    render_options: &RenderOptions,
318) -> Result<RenderStats> {
319    let started = Instant::now();
320    let palette = Palette::for_theme(render_options.theme);
321    let opacity = effective_call_opacity(atlas.calls.len(), render_options);
322    let call_indices: Vec<_> = (0..atlas.calls.len()).collect();
323    let (pixmap, calls_drawn) = render_software_call_tile(
324        atlas,
325        layout_options,
326        render_options,
327        &call_indices,
328        CallTileViewport {
329            x: 0,
330            y: 0,
331            width: layout_options.width,
332            height: layout_options.height,
333        },
334    )?;
335    if let Some(parent) = output.parent() {
336        fs::create_dir_all(parent)
337            .with_context(|| format!("cannot create output directory {}", parent.display()))?;
338    }
339    pixmap
340        .save_png(output)
341        .with_context(|| format!("cannot save {}", output.display()))?;
342    Ok(RenderStats {
343        backend: RenderBackend::Software.to_string(),
344        gpu_adapter: None,
345        width: layout_options.width,
346        height: layout_options.height,
347        call_layer_width: layout_options.width,
348        call_layer_height: layout_options.height,
349        call_layer_dpi: None,
350        call_layer_tiles: 1,
351        call_layer_tile_size: None,
352        call_layer_overlap: None,
353        files_drawn: atlas.files().count(),
354        file_labels_drawn: 0,
355        directory_labels_drawn: 0,
356        calls_drawn,
357        directory_boundaries_drawn: atlas
358            .nodes
359            .iter()
360            .filter(|node| node.kind == NodeKind::Directory && node.id != 0)
361            .count(),
362        output_bytes: fs::metadata(output)?.len(),
363        effective_call_opacity: opacity,
364        call_compositing: optical_density_description(),
365        direction_source_color: palette.direction_source.hex(),
366        direction_target_color: palette.direction_target.hex(),
367        render_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
368        pdf_tile_cache: None,
369    })
370}
371
372/// Render one transparent, integer-aligned viewport of the global call layer.
373/// Geometry remains in full-frame coordinates until the final translation, so
374/// independently rendered overlapping tiles are pixel-equivalent at seams.
375#[derive(Debug, Clone, Copy)]
376pub(crate) struct CallTileViewport {
377    pub x: u32,
378    pub y: u32,
379    pub width: u32,
380    pub height: u32,
381}
382
383#[derive(Debug)]
384pub(crate) struct CallTile {
385    pub core_x: u32,
386    pub core_y: u32,
387    pub core_width: u32,
388    pub core_height: u32,
389    pub render_x: u32,
390    pub render_y: u32,
391    pub render_width: u32,
392    pub render_height: u32,
393    pub call_indices: Vec<usize>,
394}
395
396pub(crate) fn plan_call_tiles(
397    atlas: &Atlas,
398    layout: &LayoutOptions,
399    render: &RenderOptions,
400) -> Result<(Vec<CallTile>, usize, u32)> {
401    ensure!(
402        (64..=8_192).contains(&render.pdf_call_tile_size),
403        "--pdf-call-tile-size must be between 64 and 8192 pixels"
404    );
405    let tile_size = render.pdf_call_tile_size;
406    let overlap = call_tile_overlap(layout, render);
407    let columns = layout.width.div_ceil(tile_size);
408    let rows = layout.height.div_ceil(tile_size);
409    let mut tiles = Vec::with_capacity((columns as usize).saturating_mul(rows as usize));
410    for row in 0..rows {
411        for column in 0..columns {
412            let core_x = column * tile_size;
413            let core_y = row * tile_size;
414            let core_width = tile_size.min(layout.width - core_x);
415            let core_height = tile_size.min(layout.height - core_y);
416            let render_x = core_x.saturating_sub(overlap);
417            let render_y = core_y.saturating_sub(overlap);
418            let render_x1 = (core_x + core_width)
419                .saturating_add(overlap)
420                .min(layout.width);
421            let render_y1 = (core_y + core_height)
422                .saturating_add(overlap)
423                .min(layout.height);
424            tiles.push(CallTile {
425                core_x,
426                core_y,
427                core_width,
428                core_height,
429                render_x,
430                render_y,
431                render_width: render_x1 - render_x,
432                render_height: render_y1 - render_y,
433                call_indices: Vec::new(),
434            });
435        }
436    }
437
438    let drawing_scale = (layout.width.min(layout.height) as f64 / 1080.0).max(0.5);
439    let stroke_margin = (f64::from(render.call_width) * drawing_scale * 1.28 * 0.5 + 2.0).ceil();
440    let mut calls_drawn = 0;
441    for (call_index, call) in atlas.calls.iter().enumerate() {
442        let mut points = call_control_points(atlas, call);
443        if points.len() < 2 {
444            continue;
445        }
446        let first = points[0];
447        let last = *points.last().expect("target control point");
448        let denominator = points.len().saturating_sub(1).max(1) as f64;
449        let bundle_strength = layout.bundle_strength.clamp(0.0, 1.0);
450        for (index, point) in points.iter_mut().enumerate() {
451            let amount = index as f64 / denominator;
452            let direct_x = first.x + (last.x - first.x) * amount;
453            let direct_y = first.y + (last.y - first.y) * amount;
454            point.x = direct_x + (point.x - direct_x) * bundle_strength;
455            point.y = direct_y + (point.y - direct_y) * bundle_strength;
456        }
457        calls_drawn += 1;
458        let Some((x0, y0, x1, y1)) =
459            curve_bounds(&points, stroke_margin, layout.width, layout.height)
460        else {
461            continue;
462        };
463        let first_column = x0 / tile_size;
464        let last_column = x1.saturating_sub(1) / tile_size;
465        let first_row = y0 / tile_size;
466        let last_row = y1.saturating_sub(1) / tile_size;
467        for row in first_row..=last_row {
468            for column in first_column..=last_column {
469                let index = (row * columns + column) as usize;
470                tiles[index].call_indices.push(call_index);
471            }
472        }
473    }
474    tiles.retain(|tile| !tile.call_indices.is_empty());
475    Ok((tiles, calls_drawn, overlap))
476}
477
478fn curve_bounds(
479    points: &[Point],
480    margin: f64,
481    width: u32,
482    height: u32,
483) -> Option<(u32, u32, u32, u32)> {
484    let min_x = points
485        .iter()
486        .map(|point| point.x)
487        .fold(f64::INFINITY, f64::min)
488        - margin;
489    let min_y = points
490        .iter()
491        .map(|point| point.y)
492        .fold(f64::INFINITY, f64::min)
493        - margin;
494    let max_x = points
495        .iter()
496        .map(|point| point.x)
497        .fold(f64::NEG_INFINITY, f64::max)
498        + margin;
499    let max_y = points
500        .iter()
501        .map(|point| point.y)
502        .fold(f64::NEG_INFINITY, f64::max)
503        + margin;
504    if max_x <= 0.0 || max_y <= 0.0 || min_x >= f64::from(width) || min_y >= f64::from(height) {
505        return None;
506    }
507    let x0 = min_x.floor().clamp(0.0, f64::from(width)) as u32;
508    let y0 = min_y.floor().clamp(0.0, f64::from(height)) as u32;
509    let x1 = max_x.ceil().clamp(0.0, f64::from(width)) as u32;
510    let y1 = max_y.ceil().clamp(0.0, f64::from(height)) as u32;
511    (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
512}
513
514pub(crate) fn call_tile_overlap(layout: &LayoutOptions, render: &RenderOptions) -> u32 {
515    let drawing_scale = (layout.width.min(layout.height) as f64 / 1080.0).max(0.5);
516    (f64::from(render.call_width) * drawing_scale * 1.28 * 0.5 + 0.34 + 2.0)
517        .ceil()
518        .max(4.0) as u32
519}
520
521pub(crate) fn render_software_call_tile(
522    atlas: &Atlas,
523    layout_options: &LayoutOptions,
524    render_options: &RenderOptions,
525    call_indices: &[usize],
526    viewport: CallTileViewport,
527) -> Result<(Pixmap, usize)> {
528    let palette = Palette::for_theme(render_options.theme);
529    let drawing_scale = (layout_options.width.min(layout_options.height) as f32 / 1080.0).max(0.5);
530    let opacity = effective_call_opacity(atlas.calls.len(), render_options);
531    let mut density = OpticalDensityLayer::new(viewport.width, viewport.height)?;
532    let mut ordered_indices = call_indices.to_vec();
533    ordered_indices.sort_unstable_by_key(|index| {
534        atlas
535            .calls
536            .get(*index)
537            .map(|call| call.id)
538            .unwrap_or(u64::MAX)
539    });
540    let mut calls_drawn = 0;
541    for index in ordered_indices {
542        let Some(call) = atlas.calls.get(index) else {
543            continue;
544        };
545        let mut points = call_curve(atlas, call, layout_options);
546        if points.len() < 2 {
547            continue;
548        }
549        for point in &mut points {
550            point.x -= f64::from(viewport.x);
551            point.y -= f64::from(viewport.y);
552        }
553        density.deposit_pencil_call(
554            &points,
555            palette.direction_source,
556            palette.direction_target,
557            opacity,
558            render_options.call_width * drawing_scale,
559            call.id ^ 0xca11_517e,
560        );
561        calls_drawn += 1;
562    }
563    Ok((density.resolve()?, calls_drawn))
564}
565
566#[derive(Clone, Copy, Default)]
567struct OpticalDensityPixel {
568    red: f32,
569    green: f32,
570    blue: f32,
571    density: f32,
572}
573
574struct OpticalDensityLayer {
575    width: u32,
576    height: u32,
577    pixels: Vec<OpticalDensityPixel>,
578    coverage: Vec<f32>,
579    path_position: Vec<f32>,
580    dirty: Vec<u32>,
581}
582
583impl OpticalDensityLayer {
584    fn new(width: u32, height: u32) -> Result<Self> {
585        let pixel_count = (width as usize)
586            .checked_mul(height as usize)
587            .context("optical-density call tile dimensions overflow")?;
588        Ok(Self {
589            width,
590            height,
591            pixels: vec![OpticalDensityPixel::default(); pixel_count],
592            coverage: vec![0.0; pixel_count],
593            path_position: vec![0.0; pixel_count],
594            dirty: Vec::new(),
595        })
596    }
597
598    fn deposit_pencil_call(
599        &mut self,
600        points: &[Point],
601        source: Rgba,
602        target: Rgba,
603        opacity: u8,
604        width: f32,
605        seed: u64,
606    ) {
607        if opacity == 0 || points.len() < 2 {
608            return;
609        }
610        let source = linear_rgb(source);
611        let target = linear_rgb(target);
612        for (pass, (alpha_scale, width_scale, amplitude)) in
613            [(0.62, 0.82, 0.14), (0.38, 1.28, 0.34)]
614                .into_iter()
615                .enumerate()
616        {
617            let jittered = jitter_points(points, seed ^ pass as u64, amplitude);
618            let alpha = (opacity as f32 * alpha_scale).round().max(1.0) / 255.0;
619            let unit_density = -(1.0 - alpha.min(0.999_999)).ln();
620            self.rasterize_path(&jittered, width * width_scale);
621            self.commit_path(unit_density, source, target);
622        }
623    }
624
625    fn rasterize_path(&mut self, points: &[Point], width: f32) {
626        let denominator = points.len().saturating_sub(1).max(1) as f64;
627        for (segment, pair) in points.windows(2).enumerate() {
628            let start = pair[0];
629            let end = pair[1];
630            let dx = end.x - start.x;
631            let dy = end.y - start.y;
632            let length_squared = dx * dx + dy * dy;
633            if length_squared <= f64::EPSILON {
634                continue;
635            }
636            let radius = f64::from(width.max(0.05)) * 0.5;
637            let x0 = (start.x.min(end.x) - radius - 0.5)
638                .floor()
639                .clamp(0.0, f64::from(self.width)) as u32;
640            let y0 = (start.y.min(end.y) - radius - 0.5)
641                .floor()
642                .clamp(0.0, f64::from(self.height)) as u32;
643            let x1 = (start.x.max(end.x) + radius + 0.5)
644                .ceil()
645                .clamp(0.0, f64::from(self.width)) as u32;
646            let y1 = (start.y.max(end.y) + radius + 0.5)
647                .ceil()
648                .clamp(0.0, f64::from(self.height)) as u32;
649            for y in y0..y1 {
650                for x in x0..x1 {
651                    let px = f64::from(x) + 0.5;
652                    let py = f64::from(y) + 0.5;
653                    let along = (((px - start.x) * dx + (py - start.y) * dy) / length_squared)
654                        .clamp(0.0, 1.0);
655                    let closest_x = start.x + dx * along;
656                    let closest_y = start.y + dy * along;
657                    let distance = (px - closest_x).hypot(py - closest_y);
658                    let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0) as f32;
659                    if coverage == 0.0 {
660                        continue;
661                    }
662                    let index = y as usize * self.width as usize + x as usize;
663                    if coverage > self.coverage[index] {
664                        if self.coverage[index] == 0.0 {
665                            self.dirty.push(index as u32);
666                        }
667                        self.coverage[index] = coverage;
668                        self.path_position[index] = ((segment as f64 + along) / denominator) as f32;
669                    }
670                }
671            }
672        }
673    }
674
675    fn commit_path(&mut self, unit_density: f32, source: [f32; 3], target: [f32; 3]) {
676        for index in self.dirty.drain(..) {
677            let index = index as usize;
678            let weight = self.coverage[index] * unit_density;
679            let t = self.path_position[index].clamp(0.0, 1.0);
680            let color = [
681                source[0] + (target[0] - source[0]) * t,
682                source[1] + (target[1] - source[1]) * t,
683                source[2] + (target[2] - source[2]) * t,
684            ];
685            let pixel = &mut self.pixels[index];
686            pixel.red += color[0] * weight;
687            pixel.green += color[1] * weight;
688            pixel.blue += color[2] * weight;
689            pixel.density += weight;
690            self.coverage[index] = 0.0;
691            self.path_position[index] = 0.0;
692        }
693    }
694
695    fn resolve(self) -> Result<Pixmap> {
696        let mut pixmap = Pixmap::new(self.width, self.height)
697            .context("optical-density call tile dimensions are too large")?;
698        for (output, density) in pixmap.data_mut().chunks_exact_mut(4).zip(self.pixels) {
699            if density.density <= f32::EPSILON {
700                continue;
701            }
702            let alpha = 1.0 - (-density.density).exp();
703            let inverse_density = density.density.recip();
704            let color = [
705                linear_to_srgb((density.red * inverse_density).clamp(0.0, 1.0)),
706                linear_to_srgb((density.green * inverse_density).clamp(0.0, 1.0)),
707                linear_to_srgb((density.blue * inverse_density).clamp(0.0, 1.0)),
708            ];
709            let alpha_byte = (alpha * 255.0).round().clamp(0.0, 255.0) as u8;
710            output[3] = alpha_byte;
711            for (channel, value) in output[..3].iter_mut().zip(color) {
712                *channel = (value * alpha * 255.0)
713                    .round()
714                    .clamp(0.0, f32::from(alpha_byte)) as u8;
715            }
716        }
717        Ok(pixmap)
718    }
719}
720
721fn linear_rgb(color: Rgba) -> [f32; 3] {
722    [
723        srgb_to_linear(color.r),
724        srgb_to_linear(color.g),
725        srgb_to_linear(color.b),
726    ]
727}
728
729fn linear_to_srgb(value: f32) -> f32 {
730    if value <= 0.003_130_8 {
731        value * 12.92
732    } else {
733        1.055 * value.powf(1.0 / 2.4) - 0.055
734    }
735}
736
737pub(crate) fn optical_density_description() -> String {
738    "order-independent optical density with exponential transmittance".to_owned()
739}
740
741fn render_software_png_inner(
742    atlas: &Atlas,
743    output: &Path,
744    layout_options: &LayoutOptions,
745    render_options: &RenderOptions,
746    draw_calls: bool,
747    draw_label_layer: bool,
748) -> Result<RenderStats> {
749    let render_started = Instant::now();
750    let palette = Palette::for_theme(render_options.theme);
751    let architectural = matches!(render_options.theme, Theme::Architect | Theme::Night);
752    let drawing_scale = (layout_options.width.min(layout_options.height) as f32 / 1080.0).max(0.5);
753    let mut pixmap = Pixmap::new(layout_options.width, layout_options.height)
754        .context("output dimensions are too large for the software renderer")?;
755    pixmap.fill(palette.background.color());
756    if architectural {
757        draw_paper_texture(
758            &mut pixmap,
759            layout_options.texture_seed,
760            palette.paper_fiber,
761        )?;
762    }
763
764    let root_points = sample_rect(atlas.nodes[0].rect, 3);
765    let root_path = polygon_path(&root_points)?;
766    fill_path(&mut pixmap, &root_path, palette.land, BlendMode::SourceOver);
767
768    let mut files_drawn = 0;
769    for node in atlas
770        .nodes
771        .iter()
772        .filter(|node| node.kind == NodeKind::File)
773    {
774        let perimeter_samples = if architectural {
775            if node.rect.width().min(node.rect.height()) > 30.0 {
776                8
777            } else {
778                3
779            }
780        } else {
781            2
782        };
783        let points = sample_rect(node.rect, perimeter_samples);
784        let path = polygon_path(&points)?;
785        fill_path(
786            &mut pixmap,
787            &path,
788            palette.file_color(&node.language),
789            BlendMode::SourceOver,
790        );
791        if architectural {
792            pencil_outline(
793                &mut pixmap,
794                &points,
795                palette.file_border,
796                PencilStroke {
797                    width: render_options.boundary_width * 0.62 * drawing_scale,
798                    seed: node.id as u64 ^ layout_options.texture_seed,
799                    blend_mode: boundary_blend_mode(render_options.theme),
800                },
801                0.24 * drawing_scale as f64,
802                2,
803            )?;
804        }
805        files_drawn += 1;
806    }
807
808    let mut directory_boundaries_drawn = 0;
809    let mut directories: Vec<_> = atlas
810        .nodes
811        .iter()
812        .filter(|node| node.kind == NodeKind::Directory && node.id != 0)
813        .collect();
814    directories.sort_by_key(|node| node.depth);
815    for directory in directories {
816        let samples = if architectural { 10 } else { 4 };
817        let points = sample_rect(directory.rect, samples);
818        let path = polygon_path(&points)?;
819        let width =
820            render_options.boundary_width * drawing_scale * (1.0 + 0.35 / directory.depth as f32);
821        if architectural {
822            pencil_outline(
823                &mut pixmap,
824                &points,
825                palette.directory_border,
826                PencilStroke {
827                    width,
828                    seed: directory.id as u64 ^ 0xd1ec_7000,
829                    blend_mode: boundary_blend_mode(render_options.theme),
830                },
831                0.34 * drawing_scale as f64,
832                3,
833            )?;
834        } else {
835            stroke_path(
836                &mut pixmap,
837                &path,
838                palette.directory_border,
839                width,
840                BlendMode::SourceOver,
841            );
842        }
843        directory_boundaries_drawn += 1;
844    }
845
846    if architectural {
847        pencil_outline(
848            &mut pixmap,
849            &root_points,
850            palette.outer_border,
851            PencilStroke {
852                width: render_options.boundary_width * 1.8 * drawing_scale,
853                seed: layout_options.texture_seed ^ 0xc0a5_7000,
854                blend_mode: boundary_blend_mode(render_options.theme),
855            },
856            0.28 * drawing_scale as f64,
857            3,
858        )?;
859    } else {
860        stroke_path(
861            &mut pixmap,
862            &root_path,
863            palette.outer_border,
864            render_options.boundary_width * 2.2 * drawing_scale,
865            BlendMode::SourceOver,
866        );
867    }
868    let effective_call_opacity = effective_call_opacity(atlas.calls.len(), render_options);
869    let calls_drawn = if draw_calls {
870        // Calls deposit into one floating-point optical-density field. The
871        // field resolves exactly once, making shared-route exposure independent
872        // of call order and identical for every theme.
873        let call_indices: Vec<_> = (0..atlas.calls.len()).collect();
874        let (call_layer, calls_drawn) = render_software_call_tile(
875            atlas,
876            layout_options,
877            render_options,
878            &call_indices,
879            CallTileViewport {
880                x: 0,
881                y: 0,
882                width: layout_options.width,
883                height: layout_options.height,
884            },
885        )?;
886        pixmap.draw_pixmap(
887            0,
888            0,
889            call_layer.as_ref(),
890            &PixmapPaint::default(),
891            Transform::identity(),
892            None,
893        );
894        calls_drawn
895    } else {
896        0
897    };
898
899    // Typography is deliberately composited last. Dense call traffic may run
900    // through a parcel, but it must never erase the map's hierarchy or file
901    // names.
902    let label_stats = if draw_label_layer {
903        draw_labels(&mut pixmap, atlas, layout_options, palette)?
904    } else {
905        LabelStats::default()
906    };
907
908    if let Some(parent) = output.parent() {
909        fs::create_dir_all(parent)
910            .with_context(|| format!("cannot create output directory {}", parent.display()))?;
911    }
912    pixmap
913        .save_png(output)
914        .with_context(|| format!("cannot save {}", output.display()))?;
915    let output_bytes = fs::metadata(output)?.len();
916
917    Ok(RenderStats {
918        backend: RenderBackend::Software.to_string(),
919        gpu_adapter: None,
920        width: layout_options.width,
921        height: layout_options.height,
922        call_layer_width: layout_options.width,
923        call_layer_height: layout_options.height,
924        call_layer_dpi: None,
925        call_layer_tiles: 1,
926        call_layer_tile_size: None,
927        call_layer_overlap: None,
928        files_drawn,
929        file_labels_drawn: label_stats.files,
930        directory_labels_drawn: label_stats.directories,
931        calls_drawn,
932        directory_boundaries_drawn,
933        output_bytes,
934        effective_call_opacity,
935        call_compositing: optical_density_description(),
936        direction_source_color: palette.direction_source.hex(),
937        direction_target_color: palette.direction_target.hex(),
938        render_ms: render_started
939            .elapsed()
940            .as_millis()
941            .min(u128::from(u64::MAX)) as u64,
942        pdf_tile_cache: None,
943    })
944}
945
946fn srgb_to_linear(value: u8) -> f32 {
947    let value = value as f32 / 255.0;
948    if value <= 0.04045 {
949        value / 12.92
950    } else {
951        ((value + 0.055) / 1.055).powf(2.4)
952    }
953}
954
955pub fn effective_call_opacity(call_count: usize, options: &RenderOptions) -> u8 {
956    let reference_calls = options.density_reference_calls.max(1);
957    let full_strength_until = reference_calls.saturating_mul(DENSITY_KNEE_MULTIPLIER);
958    if !options.density_aware_exposure
959        || call_count <= full_strength_until
960        || options.call_opacity == 0
961    {
962        return options.call_opacity;
963    }
964    // Keep ordinary maps at full strength. Past the density knee, fall off
965    // steeply enough that very large maps still reveal their dominant bundles.
966    let scale = (full_strength_until as f64 / call_count as f64).powf(DENSE_EXPOSURE_EXPONENT);
967    (f64::from(options.call_opacity) * scale)
968        .round()
969        .clamp(1.0, f64::from(options.call_opacity)) as u8
970}
971
972fn draw_paper_texture(pixmap: &mut Pixmap, seed: u64, color: Rgba) -> Result<()> {
973    let width = pixmap.width() as f64;
974    let height = pixmap.height() as f64;
975    let drawing_scale = (width.min(height) / 1080.0).max(0.5) as f32;
976    let fibers = ((width * height / 2600.0) as usize).clamp(280, 1400);
977    let mut state = seed ^ 0x5eed_f1be_7000;
978    for index in 0..fibers {
979        state = splitmix64(state ^ index as u64);
980        let x = unit_f64(state) * width;
981        state = splitmix64(state);
982        let y = unit_f64(state) * height;
983        state = splitmix64(state);
984        let length = 8.0 + unit_f64(state) * width * 0.075;
985        state = splitmix64(state);
986        let rise = (unit_f64(state) - 0.5) * 1.8;
987        let path = open_path(&[
988            Point { x, y },
989            Point {
990                x: (x + length).min(width),
991                y: (y + rise).clamp(0.0, height),
992            },
993        ])?;
994        stroke_path(
995            pixmap,
996            &path,
997            color,
998            0.24 * drawing_scale,
999            BlendMode::Multiply,
1000        );
1001    }
1002    Ok(())
1003}
1004
1005#[derive(Clone, Copy)]
1006struct PencilStroke {
1007    width: f32,
1008    seed: u64,
1009    blend_mode: BlendMode,
1010}
1011
1012fn pencil_outline(
1013    pixmap: &mut Pixmap,
1014    points: &[Point],
1015    color: Rgba,
1016    stroke: PencilStroke,
1017    amplitude: f64,
1018    passes: usize,
1019) -> Result<()> {
1020    let passes = passes.max(1);
1021    for pass in 0..passes {
1022        let jittered = jitter_points(
1023            points,
1024            stroke.seed ^ pass as u64,
1025            amplitude * (pass + 1) as f64,
1026        );
1027        let path = polygon_path(&jittered)?;
1028        let mut pass_color = color;
1029        pass_color.a = ((color.a as usize / passes).max(1) as u8).saturating_add(5);
1030        stroke_path(
1031            pixmap,
1032            &path,
1033            pass_color,
1034            stroke.width * (0.78 + pass as f32 * 0.13),
1035            stroke.blend_mode,
1036        );
1037    }
1038    Ok(())
1039}
1040
1041fn boundary_blend_mode(theme: Theme) -> BlendMode {
1042    if theme == Theme::Night {
1043        BlendMode::Plus
1044    } else {
1045        BlendMode::Multiply
1046    }
1047}
1048
1049pub(crate) fn jitter_points(points: &[Point], seed: u64, amplitude: f64) -> Vec<Point> {
1050    let mut state = seed;
1051    points
1052        .iter()
1053        .map(|point| {
1054            state = splitmix64(state);
1055            let dx = (unit_f64(state) - 0.5) * 2.0 * amplitude;
1056            state = splitmix64(state);
1057            let dy = (unit_f64(state) - 0.5) * 2.0 * amplitude;
1058            Point {
1059                x: point.x + dx,
1060                y: point.y + dy,
1061            }
1062        })
1063        .collect()
1064}
1065
1066#[derive(Debug, Default, Clone, Copy)]
1067pub(crate) struct LabelStats {
1068    pub files: usize,
1069    pub directories: usize,
1070}
1071
1072#[derive(Debug, Clone)]
1073pub(crate) struct LabelCommand {
1074    pub text: String,
1075    pub size: f32,
1076    pub color: Rgba,
1077    pub placement: LabelPlacement,
1078}
1079
1080#[derive(Debug, Clone, Copy)]
1081pub(crate) enum LabelPlacement {
1082    Horizontal { x: f32, baseline: f32 },
1083    Vertical { x: f32, y: f32 },
1084    Signature { x: f32, baseline: f32 },
1085}
1086
1087pub(crate) fn draw_labels(
1088    pixmap: &mut Pixmap,
1089    atlas: &Atlas,
1090    options: &LayoutOptions,
1091    palette: Palette,
1092) -> Result<LabelStats> {
1093    let Some(font) = load_label_font() else {
1094        return Ok(LabelStats::default());
1095    };
1096    let (commands, stats) = build_label_commands(&font, atlas, options, palette);
1097    for command in commands {
1098        match command.placement {
1099            LabelPlacement::Horizontal { x, baseline } => draw_text(
1100                pixmap,
1101                &font,
1102                &command.text,
1103                x,
1104                baseline,
1105                command.size,
1106                command.color,
1107            ),
1108            LabelPlacement::Vertical { x, y } => draw_text_rotated_clockwise(
1109                pixmap,
1110                &font,
1111                &command.text,
1112                x,
1113                y,
1114                command.size,
1115                command.color,
1116            ),
1117            LabelPlacement::Signature { x, baseline } => {
1118                draw_hollow_heart(
1119                    pixmap,
1120                    x,
1121                    baseline - command.size * 0.88,
1122                    command.size * 0.92,
1123                    command.color,
1124                );
1125                draw_text(
1126                    pixmap,
1127                    &font,
1128                    &command.text,
1129                    x + command.size * 1.18,
1130                    baseline,
1131                    command.size,
1132                    command.color,
1133                );
1134            }
1135        }
1136    }
1137    Ok(stats)
1138}
1139
1140pub(crate) fn collect_label_commands(
1141    atlas: &Atlas,
1142    options: &LayoutOptions,
1143    palette: Palette,
1144) -> (Vec<LabelCommand>, LabelStats) {
1145    let Some(font) = load_label_font() else {
1146        return (Vec::new(), LabelStats::default());
1147    };
1148    build_label_commands(&font, atlas, options, palette)
1149}
1150
1151fn build_label_commands(
1152    font: &Font,
1153    atlas: &Atlas,
1154    options: &LayoutOptions,
1155    palette: Palette,
1156) -> (Vec<LabelCommand>, LabelStats) {
1157    let scale = (options.width.min(options.height) as f32 / 1080.0).max(0.55);
1158    let root = &atlas.nodes[0];
1159    let title_size = 17.0 * scale;
1160    let title = root.name.to_uppercase();
1161    let title_baseline = (root.rect.y0 as f32 - 13.0 * scale).max(title_size + 2.0);
1162    let mut commands = vec![LabelCommand {
1163        text: title,
1164        size: title_size,
1165        color: palette.label,
1166        placement: LabelPlacement::Horizontal {
1167            x: root.rect.x0 as f32,
1168            baseline: title_baseline,
1169        },
1170    }];
1171
1172    let meta = format!(
1173        "{} FILES / {} CALLS",
1174        atlas.files().count(),
1175        atlas.calls.len()
1176    );
1177    let meta_size = 9.5 * scale;
1178    let meta_width = measure_text(font, &meta, meta_size);
1179    commands.push(LabelCommand {
1180        text: meta,
1181        size: meta_size,
1182        color: palette.label,
1183        placement: LabelPlacement::Horizontal {
1184            x: (root.rect.x1 as f32 - meta_width).max(root.rect.x0 as f32),
1185            baseline: title_baseline,
1186        },
1187    });
1188
1189    let footer_size = 8.5 * scale;
1190    let footer_baseline =
1191        (root.rect.y1 as f32 + 17.0 * scale).min(options.height as f32 - 5.0 * scale);
1192    let mut footer_color = palette.label;
1193    footer_color.a = footer_color.a.saturating_mul(3) / 4;
1194    let revision: String = atlas.revision.chars().take(12).collect();
1195    let provenance = format!(
1196        "GIT {} / {}",
1197        revision.to_uppercase(),
1198        current_utc_timestamp()
1199    );
1200    commands.push(LabelCommand {
1201        text: provenance,
1202        size: footer_size,
1203        color: footer_color,
1204        placement: LabelPlacement::Horizontal {
1205            x: root.rect.x0 as f32,
1206            baseline: footer_baseline,
1207        },
1208    });
1209
1210    let signature = "tessi";
1211    let signature_width = footer_size * 1.18 + measure_text(font, signature, footer_size);
1212    commands.push(LabelCommand {
1213        text: signature.to_owned(),
1214        size: footer_size,
1215        color: footer_color,
1216        placement: LabelPlacement::Signature {
1217            x: (root.rect.x1 as f32 - signature_width).max(root.rect.x0 as f32),
1218            baseline: footer_baseline,
1219        },
1220    });
1221
1222    let mut occupied = Vec::new();
1223    let mut stats = LabelStats::default();
1224    let mut directories: Vec<_> = atlas
1225        .nodes
1226        .iter()
1227        .filter(|node| {
1228            node.kind == NodeKind::Directory
1229                && node.id != 0
1230                && node.depth <= 2
1231                && node.rect.width() > 64.0 * scale as f64
1232                && node.rect.height() > 25.0 * scale as f64
1233        })
1234        .collect();
1235    directories.sort_by_key(|node| node.depth);
1236
1237    for node in directories {
1238        let size = if node.depth == 1 { 11.0 } else { 8.5 } * scale;
1239        let max_width = (node.rect.width() as f32 - 10.0 * scale).max(1.0);
1240        let text = node.name.to_uppercase();
1241        let fitted = fit_font_size(font, &text, size, max_width, 6.0 * scale);
1242        let x = node.rect.x0 as f32 + 5.0 * scale;
1243        let preferred_baseline = node.rect.y0 as f32 + fitted + 5.0 * scale;
1244        let Some((baseline, bounds)) = place_label(
1245            node.rect,
1246            x,
1247            preferred_baseline,
1248            fitted,
1249            measure_text(font, &text, fitted),
1250            2.5 * scale,
1251            &occupied,
1252        ) else {
1253            continue;
1254        };
1255        commands.push(LabelCommand {
1256            text,
1257            size: fitted,
1258            color: palette.label,
1259            placement: LabelPlacement::Horizontal { x, baseline },
1260        });
1261        occupied.push(bounds);
1262        stats.directories += 1;
1263    }
1264
1265    // File parcels never overlap each other, so labels only need to avoid the
1266    // already-placed hierarchy labels. Fit full names whenever possible, then
1267    // shrink and finally abbreviate at a legible micro-label size. This keeps
1268    // small parcels identifiable when a high-resolution poster is zoomed.
1269    for node in atlas
1270        .nodes
1271        .iter()
1272        .filter(|node| node.kind == NodeKind::File)
1273    {
1274        let Some(label) = fit_file_label(font, &node.name, node.rect, scale, &occupied) else {
1275            continue;
1276        };
1277        let mut color = palette.label;
1278        color.a = color.a.saturating_mul(3) / 4;
1279        commands.push(LabelCommand {
1280            text: label.text,
1281            size: label.size,
1282            color,
1283            placement: label.placement,
1284        });
1285        stats.files += 1;
1286    }
1287    (commands, stats)
1288}
1289
1290#[derive(Debug, Clone)]
1291struct FittedFileLabel {
1292    text: String,
1293    size: f32,
1294    placement: LabelPlacement,
1295}
1296
1297fn fit_file_label(
1298    font: &Font,
1299    text: &str,
1300    container: Rect,
1301    scale: f32,
1302    occupied: &[LabelBounds],
1303) -> Option<FittedFileLabel> {
1304    let padding = (1.8 * scale)
1305        .min(container.width() as f32 * 0.16)
1306        .min(container.height() as f32 * 0.16)
1307        .max(0.6);
1308    let fitted = if container.height() > container.width() * 1.8 {
1309        fit_vertical_file_label(font, text, container, scale, padding, occupied)
1310            .or_else(|| fit_horizontal_file_label(font, text, container, scale, padding, occupied))
1311    } else {
1312        fit_horizontal_file_label(font, text, container, scale, padding, occupied)
1313            .or_else(|| fit_vertical_file_label(font, text, container, scale, padding, occupied))
1314    };
1315    fitted.or_else(|| fit_compact_file_marker(font, text, container, scale, occupied))
1316}
1317
1318fn fit_compact_file_marker(
1319    font: &Font,
1320    text: &str,
1321    container: Rect,
1322    scale: f32,
1323    occupied: &[LabelBounds],
1324) -> Option<FittedFileLabel> {
1325    let marker = text.chars().next()?.to_string();
1326    let size = 1.5 * scale;
1327    let width = measure_text(font, &marker, size);
1328    let padding = 0.3_f32.min(container.width() as f32 * 0.08);
1329    let x_positions = [
1330        container.x0 as f32 + padding,
1331        (container.x0 + container.x1) as f32 / 2.0 - width / 2.0,
1332    ];
1333    let baselines = [
1334        container.y1 as f32 - padding - size * 0.22,
1335        container.y0 as f32 + padding + size,
1336        (container.y0 + container.y1) as f32 / 2.0 + size * 0.39,
1337    ];
1338    for x in x_positions {
1339        for baseline in baselines {
1340            let bounds = label_bounds(x, baseline, width, size);
1341            if label_fits(container, bounds)
1342                && !occupied.iter().any(|other| bounds.overlaps(*other, 0.0))
1343            {
1344                return Some(FittedFileLabel {
1345                    text: marker,
1346                    size,
1347                    placement: LabelPlacement::Horizontal { x, baseline },
1348                });
1349            }
1350        }
1351    }
1352    None
1353}
1354
1355fn fit_horizontal_file_label(
1356    font: &Font,
1357    text: &str,
1358    container: Rect,
1359    scale: f32,
1360    padding: f32,
1361    occupied: &[LabelBounds],
1362) -> Option<FittedFileLabel> {
1363    let available_width = container.width() as f32 - 2.0 * padding;
1364    let available_height = container.height() as f32 - 2.0 * padding;
1365    let preferred = (7.5 * scale).min(available_height / 1.22);
1366    let minimum = 1.5 * scale;
1367    if available_width <= 0.0 || preferred < minimum {
1368        return None;
1369    }
1370
1371    let preferred_width = measure_text(font, text, preferred).max(1.0);
1372    let required_size = preferred * available_width / preferred_width;
1373    let size = required_size.clamp(minimum, preferred);
1374    let fitted_text = truncate_text_to_width(font, text, size, available_width)?;
1375    let width = measure_text(font, &fitted_text, size);
1376    let x = container.x0 as f32 + padding;
1377    let bottom = container.y1 as f32 - padding - size * 0.22;
1378    let top = container.y0 as f32 + padding + size;
1379    let middle = (container.y0 + container.y1) as f32 / 2.0 + size * 0.39;
1380
1381    for baseline in [bottom, top, middle] {
1382        let bounds = label_bounds(x, baseline, width, size);
1383        if label_fits(container, bounds)
1384            && !occupied
1385                .iter()
1386                .any(|other| bounds.overlaps(*other, 0.7 * scale))
1387        {
1388            return Some(FittedFileLabel {
1389                text: fitted_text,
1390                size,
1391                placement: LabelPlacement::Horizontal { x, baseline },
1392            });
1393        }
1394    }
1395    None
1396}
1397
1398fn fit_vertical_file_label(
1399    font: &Font,
1400    text: &str,
1401    container: Rect,
1402    scale: f32,
1403    padding: f32,
1404    occupied: &[LabelBounds],
1405) -> Option<FittedFileLabel> {
1406    let available_cross = container.width() as f32 - 2.0 * padding;
1407    let available_length = container.height() as f32 - 2.0 * padding;
1408    let preferred = (7.5 * scale).min(available_cross / 1.22);
1409    let minimum = 1.5 * scale;
1410    if available_length <= 0.0 || preferred < minimum {
1411        return None;
1412    }
1413
1414    let preferred_width = measure_text(font, text, preferred).max(1.0);
1415    let required_size = preferred * available_length / preferred_width;
1416    let size = required_size.clamp(minimum, preferred);
1417    let fitted_text = truncate_text_to_width(font, text, size, available_length)?;
1418    let text_length = measure_text(font, &fitted_text, size);
1419    let label_width = size * 1.22;
1420    let left = container.x0 as f32 + padding;
1421    let right = container.x1 as f32 - padding - label_width;
1422    let center_x = (container.x0 + container.x1) as f32 / 2.0 - label_width / 2.0;
1423    let top = container.y0 as f32 + padding;
1424    let bottom = container.y1 as f32 - padding - text_length;
1425    let center_y = (container.y0 + container.y1) as f32 / 2.0 - text_length / 2.0;
1426
1427    for (x, y) in [
1428        (left, bottom),
1429        (right, bottom),
1430        (left, top),
1431        (right, top),
1432        (center_x, center_y),
1433    ] {
1434        let bounds = LabelBounds {
1435            x0: x,
1436            y0: y,
1437            x1: x + label_width,
1438            y1: y + text_length,
1439        };
1440        if label_fits(container, bounds)
1441            && !occupied
1442                .iter()
1443                .any(|other| bounds.overlaps(*other, 0.7 * scale))
1444        {
1445            return Some(FittedFileLabel {
1446                text: fitted_text,
1447                size,
1448                placement: LabelPlacement::Vertical { x, y },
1449            });
1450        }
1451    }
1452    None
1453}
1454
1455fn truncate_text_to_width(font: &Font, text: &str, size: f32, max_width: f32) -> Option<String> {
1456    if measure_text(font, text, size) <= max_width {
1457        return Some(text.to_owned());
1458    }
1459    let ellipsis = "...";
1460    let ellipsis_width = measure_text(font, ellipsis, size);
1461    let mut output = String::new();
1462    for character in text.chars() {
1463        let candidate_width = measure_text(font, &output, size)
1464            + font.metrics(character, size).advance_width
1465            + ellipsis_width;
1466        if candidate_width > max_width {
1467            break;
1468        }
1469        output.push(character);
1470    }
1471    if output.is_empty() {
1472        return None;
1473    }
1474    output.push_str(ellipsis);
1475    Some(output)
1476}
1477
1478#[derive(Debug, Clone, Copy, PartialEq)]
1479struct LabelBounds {
1480    x0: f32,
1481    y0: f32,
1482    x1: f32,
1483    y1: f32,
1484}
1485
1486impl LabelBounds {
1487    fn overlaps(self, other: Self, gap: f32) -> bool {
1488        self.x0 < other.x1 + gap
1489            && self.x1 > other.x0 - gap
1490            && self.y0 < other.y1 + gap
1491            && self.y1 > other.y0 - gap
1492    }
1493}
1494
1495fn label_bounds(x: f32, baseline: f32, width: f32, size: f32) -> LabelBounds {
1496    LabelBounds {
1497        x0: x,
1498        y0: baseline - size,
1499        x1: x + width,
1500        y1: baseline + size * 0.22,
1501    }
1502}
1503
1504fn label_fits(container: Rect, bounds: LabelBounds) -> bool {
1505    bounds.x0 >= container.x0 as f32
1506        && bounds.y0 >= container.y0 as f32
1507        && bounds.x1 <= container.x1 as f32
1508        && bounds.y1 <= container.y1 as f32
1509}
1510
1511fn place_label(
1512    container: Rect,
1513    x: f32,
1514    preferred_baseline: f32,
1515    size: f32,
1516    width: f32,
1517    gap: f32,
1518    occupied: &[LabelBounds],
1519) -> Option<(f32, LabelBounds)> {
1520    let mut baseline = preferred_baseline;
1521    for _ in 0..=occupied.len() {
1522        let bounds = label_bounds(x, baseline, width, size);
1523        if !label_fits(container, bounds) {
1524            return None;
1525        }
1526        let colliding_bottom = occupied
1527            .iter()
1528            .filter(|other| bounds.overlaps(**other, gap))
1529            .map(|other| other.y1)
1530            .reduce(f32::max);
1531        let Some(bottom) = colliding_bottom else {
1532            return Some((baseline, bounds));
1533        };
1534        baseline = bottom + gap + size;
1535    }
1536    None
1537}
1538
1539fn load_label_font() -> Option<Font> {
1540    const FONT_PATHS: &[&str] = &[
1541        "/System/Library/Fonts/SFNSMono.ttf",
1542        "/System/Library/Fonts/Supplemental/Courier New.ttf",
1543        "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
1544        "/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
1545    ];
1546    FONT_PATHS.iter().find_map(|path| {
1547        let bytes = fs::read(path).ok()?;
1548        Font::from_bytes(bytes, FontSettings::default()).ok()
1549    })
1550}
1551
1552fn fit_font_size(font: &Font, text: &str, preferred: f32, max_width: f32, minimum: f32) -> f32 {
1553    let width = measure_text(font, text, preferred).max(1.0);
1554    (preferred * (max_width / width).min(1.0)).max(minimum.min(preferred))
1555}
1556
1557fn measure_text(font: &Font, text: &str, size: f32) -> f32 {
1558    text.chars()
1559        .map(|character| font.metrics(character, size).advance_width)
1560        .sum()
1561}
1562
1563fn draw_text(
1564    pixmap: &mut Pixmap,
1565    font: &Font,
1566    text: &str,
1567    x: f32,
1568    baseline: f32,
1569    size: f32,
1570    color: Rgba,
1571) {
1572    let width = pixmap.width() as i32;
1573    let height = pixmap.height() as i32;
1574    let mut pen_x = x;
1575    let data = pixmap.data_mut();
1576    for character in text.chars() {
1577        let (metrics, bitmap) = font.rasterize(character, size);
1578        let glyph_x = pen_x.round() as i32 + metrics.xmin;
1579        let glyph_y = baseline.round() as i32 - metrics.height as i32 - metrics.ymin;
1580        for row in 0..metrics.height {
1581            for column in 0..metrics.width {
1582                let destination_x = glyph_x + column as i32;
1583                let destination_y = glyph_y + row as i32;
1584                if destination_x < 0
1585                    || destination_y < 0
1586                    || destination_x >= width
1587                    || destination_y >= height
1588                {
1589                    continue;
1590                }
1591                let coverage = bitmap[row * metrics.width + column] as f32 / 255.0;
1592                let alpha = coverage * (color.a as f32 / 255.0);
1593                if alpha <= 0.0 {
1594                    continue;
1595                }
1596                let offset = ((destination_y * width + destination_x) * 4) as usize;
1597                for (channel, source) in [color.r, color.g, color.b].into_iter().enumerate() {
1598                    let destination = data[offset + channel] as f32;
1599                    data[offset + channel] =
1600                        (source as f32 * alpha + destination * (1.0 - alpha)).round() as u8;
1601                }
1602            }
1603        }
1604        pen_x += metrics.advance_width;
1605    }
1606}
1607
1608fn draw_text_rotated_clockwise(
1609    pixmap: &mut Pixmap,
1610    font: &Font,
1611    text: &str,
1612    x: f32,
1613    y: f32,
1614    size: f32,
1615    color: Rgba,
1616) {
1617    let canvas_width = pixmap.width() as i32;
1618    let canvas_height = pixmap.height() as i32;
1619    let normal_height = (size * 1.22).ceil().max(1.0) as i32;
1620    let origin_x = x.round() as i32;
1621    let origin_y = y.round() as i32;
1622    let mut pen_x = 0.0_f32;
1623    let data = pixmap.data_mut();
1624
1625    for character in text.chars() {
1626        let (metrics, bitmap) = font.rasterize(character, size);
1627        let glyph_x = pen_x.round() as i32 + metrics.xmin;
1628        let glyph_y = size.round() as i32 - metrics.height as i32 - metrics.ymin;
1629        for row in 0..metrics.height {
1630            for column in 0..metrics.width {
1631                let normal_x = glyph_x + column as i32;
1632                let normal_y = glyph_y + row as i32;
1633                if normal_y < 0 || normal_y >= normal_height {
1634                    continue;
1635                }
1636                let destination_x = origin_x + normal_height - 1 - normal_y;
1637                let destination_y = origin_y + normal_x;
1638                if destination_x < 0
1639                    || destination_y < 0
1640                    || destination_x >= canvas_width
1641                    || destination_y >= canvas_height
1642                {
1643                    continue;
1644                }
1645                let coverage = bitmap[row * metrics.width + column] as f32 / 255.0;
1646                let alpha = coverage * (color.a as f32 / 255.0);
1647                if alpha <= 0.0 {
1648                    continue;
1649                }
1650                let offset = ((destination_y * canvas_width + destination_x) * 4) as usize;
1651                for (channel, source) in [color.r, color.g, color.b].into_iter().enumerate() {
1652                    let destination = data[offset + channel] as f32;
1653                    data[offset + channel] =
1654                        (source as f32 * alpha + destination * (1.0 - alpha)).round() as u8;
1655                }
1656            }
1657        }
1658        pen_x += metrics.advance_width;
1659    }
1660}
1661
1662fn draw_hollow_heart(pixmap: &mut Pixmap, x: f32, y: f32, size: f32, color: Rgba) {
1663    let mut builder = PathBuilder::new();
1664    builder.move_to(x + size * 0.5, y + size * 0.92);
1665    builder.cubic_to(
1666        x + size * 0.08,
1667        y + size * 0.64,
1668        x,
1669        y + size * 0.34,
1670        x + size * 0.21,
1671        y + size * 0.19,
1672    );
1673    builder.cubic_to(
1674        x + size * 0.36,
1675        y + size * 0.08,
1676        x + size * 0.5,
1677        y + size * 0.19,
1678        x + size * 0.5,
1679        y + size * 0.32,
1680    );
1681    builder.cubic_to(
1682        x + size * 0.5,
1683        y + size * 0.19,
1684        x + size * 0.64,
1685        y + size * 0.08,
1686        x + size * 0.79,
1687        y + size * 0.19,
1688    );
1689    builder.cubic_to(
1690        x + size,
1691        y + size * 0.34,
1692        x + size * 0.92,
1693        y + size * 0.64,
1694        x + size * 0.5,
1695        y + size * 0.92,
1696    );
1697    if let Some(path) = builder.finish() {
1698        stroke_path(
1699            pixmap,
1700            &path,
1701            color,
1702            (size * 0.075).max(0.55),
1703            BlendMode::SourceOver,
1704        );
1705    }
1706}
1707
1708fn current_utc_timestamp() -> String {
1709    let seconds = SystemTime::now()
1710        .duration_since(UNIX_EPOCH)
1711        .unwrap_or_default()
1712        .as_secs()
1713        .min(i64::MAX as u64) as i64;
1714    format_utc_timestamp(seconds)
1715}
1716
1717fn format_utc_timestamp(seconds: i64) -> String {
1718    let days = seconds.div_euclid(86_400);
1719    let seconds_of_day = seconds.rem_euclid(86_400);
1720    let hour = seconds_of_day / 3_600;
1721    let minute = seconds_of_day % 3_600 / 60;
1722    let second = seconds_of_day % 60;
1723
1724    // Convert days since the Unix epoch to a proleptic Gregorian date.
1725    let shifted = days + 719_468;
1726    let era = if shifted >= 0 {
1727        shifted
1728    } else {
1729        shifted - 146_096
1730    } / 146_097;
1731    let day_of_era = shifted - era * 146_097;
1732    let year_of_era =
1733        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1734    let mut year = year_of_era + era * 400;
1735    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1736    let month_prime = (5 * day_of_year + 2) / 153;
1737    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
1738    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
1739    year += i64::from(month <= 2);
1740
1741    format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02} UTC")
1742}
1743
1744fn splitmix64(mut value: u64) -> u64 {
1745    value = value.wrapping_add(0x9e3779b97f4a7c15);
1746    value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
1747    value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
1748    value ^ (value >> 31)
1749}
1750
1751fn unit_f64(value: u64) -> f64 {
1752    value as f64 / u64::MAX as f64
1753}
1754
1755fn polygon_path(points: &[Point]) -> Result<SkiaPath> {
1756    let mut builder = PathBuilder::new();
1757    let Some(first) = points.first() else {
1758        bail!("cannot create an empty polygon");
1759    };
1760    builder.move_to(first.x as f32, first.y as f32);
1761    for point in &points[1..] {
1762        builder.line_to(point.x as f32, point.y as f32);
1763    }
1764    builder.close();
1765    builder.finish().context("invalid polygon geometry")
1766}
1767
1768fn open_path(points: &[Point]) -> Result<SkiaPath> {
1769    let mut builder = PathBuilder::new();
1770    let Some(first) = points.first() else {
1771        bail!("cannot create an empty path");
1772    };
1773    builder.move_to(first.x as f32, first.y as f32);
1774    for point in &points[1..] {
1775        builder.line_to(point.x as f32, point.y as f32);
1776    }
1777    builder.finish().context("invalid path geometry")
1778}
1779
1780fn fill_path(pixmap: &mut Pixmap, path: &SkiaPath, color: Rgba, blend_mode: BlendMode) {
1781    let mut paint = Paint {
1782        anti_alias: true,
1783        blend_mode,
1784        ..Paint::default()
1785    };
1786    paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1787    pixmap.fill_path(path, &paint, FillRule::Winding, Transform::identity(), None);
1788}
1789
1790fn stroke_path(
1791    pixmap: &mut Pixmap,
1792    path: &SkiaPath,
1793    color: Rgba,
1794    width: f32,
1795    blend_mode: BlendMode,
1796) {
1797    let mut paint = Paint {
1798        anti_alias: true,
1799        blend_mode,
1800        ..Paint::default()
1801    };
1802    paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1803    let stroke = Stroke {
1804        width,
1805        line_cap: LineCap::Round,
1806        line_join: LineJoin::Round,
1807        ..Stroke::default()
1808    };
1809    pixmap.stroke_path(path, &paint, &stroke, Transform::identity(), None);
1810}
1811
1812#[derive(Debug, Clone, Copy)]
1813pub(crate) struct Rgba {
1814    pub r: u8,
1815    pub g: u8,
1816    pub b: u8,
1817    pub a: u8,
1818}
1819
1820impl Rgba {
1821    pub(crate) const fn rgb(r: u8, g: u8, b: u8) -> Self {
1822        Self { r, g, b, a: 255 }
1823    }
1824
1825    pub(crate) const fn with_alpha(r: u8, g: u8, b: u8, a: u8) -> Self {
1826        Self { r, g, b, a }
1827    }
1828
1829    fn color(self) -> Color {
1830        Color::from_rgba8(self.r, self.g, self.b, self.a)
1831    }
1832
1833    pub(crate) fn hex(self) -> String {
1834        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
1835    }
1836}
1837
1838#[derive(Debug, Clone, Copy)]
1839pub(crate) struct Palette {
1840    pub background: Rgba,
1841    pub land: Rgba,
1842    pub paper_fiber: Rgba,
1843    pub outer_border: Rgba,
1844    pub directory_border: Rgba,
1845    pub file_border: Rgba,
1846    pub label: Rgba,
1847    pub direction_source: Rgba,
1848    pub direction_target: Rgba,
1849    pub elixir: Rgba,
1850    pub rust: Rgba,
1851    pub tests: Rgba,
1852    pub docs: Rgba,
1853    pub config: Rgba,
1854    pub other: Rgba,
1855}
1856
1857impl Palette {
1858    pub(crate) fn for_theme(theme: Theme) -> Self {
1859        match theme {
1860            Theme::Architect => Self {
1861                background: Rgba::rgb(241, 238, 229),
1862                land: Rgba::rgb(246, 243, 235),
1863                paper_fiber: Rgba::with_alpha(83, 77, 65, 8),
1864                outer_border: Rgba::with_alpha(48, 48, 45, 150),
1865                directory_border: Rgba::with_alpha(54, 55, 53, 105),
1866                file_border: Rgba::with_alpha(68, 68, 64, 48),
1867                label: Rgba::with_alpha(48, 48, 45, 150),
1868                direction_source: Rgba::rgb(172, 52, 68),
1869                direction_target: Rgba::rgb(34, 92, 150),
1870                elixir: Rgba::rgb(234, 231, 237),
1871                rust: Rgba::rgb(238, 231, 222),
1872                tests: Rgba::rgb(230, 235, 230),
1873                docs: Rgba::rgb(238, 236, 229),
1874                config: Rgba::rgb(234, 233, 228),
1875                other: Rgba::rgb(241, 238, 231),
1876            },
1877            Theme::Night => Self {
1878                background: Rgba::rgb(6, 10, 17),
1879                land: Rgba::rgb(13, 20, 30),
1880                paper_fiber: Rgba::with_alpha(155, 175, 202, 6),
1881                outer_border: Rgba::with_alpha(160, 180, 205, 155),
1882                directory_border: Rgba::with_alpha(130, 150, 175, 70),
1883                file_border: Rgba::with_alpha(118, 140, 163, 32),
1884                label: Rgba::with_alpha(205, 218, 235, 215),
1885                direction_source: Rgba::rgb(255, 70, 142),
1886                direction_target: Rgba::rgb(55, 210, 255),
1887                elixir: Rgba::rgb(22, 30, 42),
1888                rust: Rgba::rgb(24, 32, 43),
1889                tests: Rgba::rgb(21, 31, 41),
1890                docs: Rgba::rgb(20, 28, 39),
1891                config: Rgba::rgb(25, 32, 42),
1892                other: Rgba::rgb(18, 26, 37),
1893            },
1894            Theme::Ink => Self {
1895                background: Rgba::rgb(245, 242, 232),
1896                land: Rgba::rgb(235, 231, 218),
1897                paper_fiber: Rgba::with_alpha(70, 62, 49, 0),
1898                outer_border: Rgba::with_alpha(29, 43, 67, 170),
1899                directory_border: Rgba::with_alpha(40, 52, 73, 70),
1900                file_border: Rgba::with_alpha(40, 52, 73, 30),
1901                label: Rgba::with_alpha(29, 43, 67, 150),
1902                direction_source: Rgba::rgb(190, 35, 70),
1903                direction_target: Rgba::rgb(30, 70, 175),
1904                elixir: Rgba::rgb(225, 218, 235),
1905                rust: Rgba::rgb(235, 219, 211),
1906                tests: Rgba::rgb(214, 231, 227),
1907                docs: Rgba::rgb(226, 226, 218),
1908                config: Rgba::rgb(220, 219, 215),
1909                other: Rgba::rgb(231, 228, 218),
1910            },
1911            Theme::SolarizedDark => Self {
1912                background: Rgba::rgb(0, 43, 54),
1913                land: Rgba::rgb(7, 54, 66),
1914                paper_fiber: Rgba::with_alpha(255, 255, 255, 0),
1915                outer_border: Rgba::with_alpha(147, 161, 161, 170),
1916                directory_border: Rgba::with_alpha(88, 110, 117, 90),
1917                file_border: Rgba::with_alpha(88, 110, 117, 35),
1918                label: Rgba::with_alpha(147, 161, 161, 170),
1919                direction_source: Rgba::rgb(220, 50, 47),
1920                direction_target: Rgba::rgb(38, 139, 210),
1921                elixir: Rgba::rgb(32, 65, 82),
1922                rust: Rgba::rgb(73, 55, 44),
1923                tests: Rgba::rgb(20, 73, 70),
1924                docs: Rgba::rgb(28, 60, 69),
1925                config: Rgba::rgb(48, 60, 64),
1926                other: Rgba::rgb(18, 55, 64),
1927            },
1928            Theme::SolarizedLight => Self {
1929                background: Rgba::rgb(253, 246, 227),
1930                land: Rgba::rgb(238, 232, 213),
1931                paper_fiber: Rgba::with_alpha(70, 62, 49, 0),
1932                outer_border: Rgba::with_alpha(88, 110, 117, 170),
1933                directory_border: Rgba::with_alpha(101, 123, 131, 80),
1934                file_border: Rgba::with_alpha(101, 123, 131, 35),
1935                label: Rgba::with_alpha(88, 110, 117, 160),
1936                direction_source: Rgba::rgb(220, 50, 47),
1937                direction_target: Rgba::rgb(38, 139, 210),
1938                elixir: Rgba::rgb(231, 222, 238),
1939                rust: Rgba::rgb(240, 219, 201),
1940                tests: Rgba::rgb(218, 235, 224),
1941                docs: Rgba::rgb(235, 230, 213),
1942                config: Rgba::rgb(226, 224, 211),
1943                other: Rgba::rgb(239, 233, 216),
1944            },
1945        }
1946    }
1947
1948    pub(crate) fn file_color(self, language: &str) -> Rgba {
1949        match language {
1950            "elixir" => self.elixir,
1951            "erlang" => self.elixir,
1952            "rust" => self.rust,
1953            "markdown" => self.docs,
1954            "config" | "data" => self.config,
1955            language if language.contains("test") => self.tests,
1956            _ => self.other,
1957        }
1958    }
1959}
1960
1961#[cfg(test)]
1962mod tests {
1963    use super::*;
1964
1965    #[test]
1966    fn utc_footer_timestamp_uses_stable_iso_style() {
1967        assert_eq!(format_utc_timestamp(0), "1970-01-01 00:00:00 UTC");
1968        assert_eq!(format_utc_timestamp(86_400), "1970-01-02 00:00:00 UTC");
1969    }
1970
1971    #[test]
1972    fn directional_palette_has_one_unambiguous_source_to_target_ramp() {
1973        let palette = Palette::for_theme(Theme::Night);
1974        let source = linear_rgb(palette.direction_source);
1975        let target = linear_rgb(palette.direction_target);
1976        assert_ne!(source, target);
1977        assert!(source[0] > target[0], "source is the pink end of the ramp");
1978        assert!(target[2] > source[2], "target is the cyan end of the ramp");
1979    }
1980
1981    #[test]
1982    fn night_treemap_uses_one_subtle_blueprint_family() {
1983        let palette = Palette::for_theme(Theme::Night);
1984        let fills = [
1985            palette.elixir,
1986            palette.rust,
1987            palette.tests,
1988            palette.docs,
1989            palette.config,
1990            palette.other,
1991        ];
1992        assert!(
1993            fills
1994                .iter()
1995                .all(|color| color.b >= color.g && color.g >= color.r)
1996        );
1997        for left in fills {
1998            for right in fills {
1999                assert!(left.r.abs_diff(right.r) <= 7);
2000                assert!(left.g.abs_diff(right.g) <= 7);
2001                assert!(left.b.abs_diff(right.b) <= 7);
2002            }
2003        }
2004    }
2005
2006    #[test]
2007    fn truncated_poster_labels_use_pdf_safe_ascii_ellipsis() {
2008        let font = load_label_font().expect("test font");
2009        let text = truncate_text_to_width(&font, "settings_table_model.ex", 12.0, 85.0)
2010            .expect("truncated label");
2011        assert!(text.is_ascii());
2012        assert!(text.ends_with("..."));
2013    }
2014
2015    #[test]
2016    fn unavailable_gpu_capabilities_fall_back_but_render_failures_do_not() {
2017        assert!(gpu_is_unavailable(&anyhow::anyhow!(
2018            "no compatible GPU adapter is available"
2019        )));
2020        assert!(gpu_is_unavailable(&anyhow::anyhow!(
2021            "adapter does not support blendable RGBA16Float density textures"
2022        )));
2023        assert!(gpu_is_unavailable(&anyhow::anyhow!(
2024            "adapter does not support 4x multisampled RGBA16Float density textures"
2025        )));
2026        assert!(!gpu_is_unavailable(&anyhow::anyhow!("GPU readback failed")));
2027    }
2028
2029    #[test]
2030    fn child_label_moves_below_an_overlapping_parent_label() {
2031        let container = Rect {
2032            x0: 0.0,
2033            y0: 0.0,
2034            x1: 200.0,
2035            y1: 100.0,
2036        };
2037        let parent = label_bounds(5.0, 16.0, 70.0, 11.0);
2038        let (baseline, child) =
2039            place_label(container, 5.0, 14.0, 9.0, 60.0, 3.0, &[parent]).unwrap();
2040
2041        assert!(baseline > 16.0);
2042        assert!(!child.overlaps(parent, 3.0));
2043        assert!(label_fits(container, child));
2044    }
2045
2046    #[test]
2047    fn label_is_omitted_when_no_collision_free_band_fits() {
2048        let container = Rect {
2049            x0: 0.0,
2050            y0: 0.0,
2051            x1: 100.0,
2052            y1: 24.0,
2053        };
2054        let parent = label_bounds(4.0, 13.0, 70.0, 10.0);
2055
2056        assert!(place_label(container, 4.0, 12.0, 9.0, 60.0, 3.0, &[parent]).is_none());
2057    }
2058
2059    #[test]
2060    fn small_file_parcels_receive_abbreviated_micro_labels() {
2061        let Some(font) = load_label_font() else {
2062            return;
2063        };
2064        let parcel = Rect {
2065            x0: 0.0,
2066            y0: 0.0,
2067            x1: 42.0,
2068            y1: 12.0,
2069        };
2070        let label = fit_file_label(&font, "a_very_long_source_filename.ex", parcel, 1.0, &[])
2071            .expect("small but readable parcel should have a label");
2072
2073        assert!(label.text.ends_with("..."));
2074        assert!(label.size >= 1.5);
2075        assert!(measure_text(&font, &label.text, label.size) <= parcel.width() as f32);
2076    }
2077
2078    #[test]
2079    fn microscopic_parcels_receive_a_compact_zoom_label() {
2080        let Some(font) = load_label_font() else {
2081            return;
2082        };
2083        let parcel = Rect {
2084            x0: 0.0,
2085            y0: 0.0,
2086            x1: 4.0,
2087            y1: 4.0,
2088        };
2089
2090        let label = fit_file_label(&font, "tiny.ex", parcel, 1.0, &[])
2091            .expect("even a microscopic parcel should retain a zoom label");
2092        assert!(!label.text.is_empty());
2093    }
2094
2095    #[test]
2096    fn narrow_tall_parcels_use_vertical_labels() {
2097        let Some(font) = load_label_font() else {
2098            return;
2099        };
2100        let parcel = Rect {
2101            x0: 0.0,
2102            y0: 0.0,
2103            x1: 12.0,
2104            y1: 70.0,
2105        };
2106        let label = fit_file_label(&font, "formatter.ex", parcel, 1.0, &[])
2107            .expect("tall parcel should have a rotated label");
2108
2109        assert!(matches!(label.placement, LabelPlacement::Vertical { .. }));
2110    }
2111
2112    #[test]
2113    fn density_exposure_preserves_small_graphs_and_lowers_large_graphs() {
2114        let options = RenderOptions::default();
2115        assert_eq!(effective_call_opacity(2_500, &options), 34);
2116        assert_eq!(effective_call_opacity(5_345, &options), 34);
2117        assert_eq!(effective_call_opacity(10_000, &options), 34);
2118        assert_eq!(effective_call_opacity(21_307, &options), 15);
2119        assert_eq!(effective_call_opacity(208_147, &options), 1);
2120
2121        let fixed = RenderOptions {
2122            density_aware_exposure: false,
2123            ..options
2124        };
2125        assert_eq!(effective_call_opacity(21_307, &fixed), 34);
2126    }
2127
2128    #[test]
2129    fn optical_density_is_order_independent_in_light_and_dark_themes() {
2130        let first = [Point { x: 4.0, y: 8.0 }, Point { x: 60.0, y: 55.0 }];
2131        let second = [Point { x: 5.0, y: 56.0 }, Point { x: 59.0, y: 7.0 }];
2132        for theme in [Theme::Architect, Theme::Night] {
2133            let palette = Palette::for_theme(theme);
2134            let mut forward = OpticalDensityLayer::new(64, 64).unwrap();
2135            forward.deposit_pencil_call(
2136                &first,
2137                palette.direction_source,
2138                palette.direction_target,
2139                34,
2140                1.4,
2141                11,
2142            );
2143            forward.deposit_pencil_call(
2144                &second,
2145                palette.direction_target,
2146                palette.direction_source,
2147                34,
2148                1.4,
2149                22,
2150            );
2151            let mut reverse = OpticalDensityLayer::new(64, 64).unwrap();
2152            reverse.deposit_pencil_call(
2153                &second,
2154                palette.direction_target,
2155                palette.direction_source,
2156                34,
2157                1.4,
2158                22,
2159            );
2160            reverse.deposit_pencil_call(
2161                &first,
2162                palette.direction_source,
2163                palette.direction_target,
2164                34,
2165                1.4,
2166                11,
2167            );
2168
2169            assert_eq!(
2170                forward.resolve().unwrap().data(),
2171                reverse.resolve().unwrap().data()
2172            );
2173        }
2174    }
2175
2176    #[test]
2177    fn repeated_routes_deposit_more_optical_density_in_every_theme() {
2178        let points = [Point { x: 4.0, y: 32.0 }, Point { x: 60.0, y: 32.0 }];
2179        for theme in [Theme::Architect, Theme::Night] {
2180            let palette = Palette::for_theme(theme);
2181            let mut single = OpticalDensityLayer::new(64, 64).unwrap();
2182            single.deposit_pencil_call(
2183                &points,
2184                palette.direction_source,
2185                palette.direction_target,
2186                34,
2187                1.4,
2188                11,
2189            );
2190            let single = single.resolve().unwrap();
2191            let mut double = OpticalDensityLayer::new(64, 64).unwrap();
2192            for _ in 0..2 {
2193                double.deposit_pencil_call(
2194                    &points,
2195                    palette.direction_source,
2196                    palette.direction_target,
2197                    34,
2198                    1.4,
2199                    11,
2200                );
2201            }
2202            let double = double.resolve().unwrap();
2203            let alpha = |pixmap: &Pixmap| {
2204                pixmap
2205                    .data()
2206                    .chunks_exact(4)
2207                    .map(|pixel| u64::from(pixel[3]))
2208                    .sum::<u64>()
2209            };
2210            assert!(alpha(&double) > alpha(&single));
2211        }
2212    }
2213}