lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Resolve complete text constraints before parent geometry and frozen placement.

use super::ResolvedTextPlan;
use crate::layout::{
    fit::{self, FitOutcome, FitScope},
    PhysicalTextAlignment,
};
use crate::text::TextAppearance;
use crate::{
    text::{TextFailure, TextWrapping},
    Error,
};

#[expect(
    clippy::too_many_arguments,
    reason = "original occurrence eligibility is independent of the complete measured text request and assignment"
)]
pub(crate) fn measure_occurrence(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: i64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
    occurrence: (usize, &[usize]),
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    if appearance.includes(occurrence.0, occurrence.1) {
        measure_quanta(theme, source, appearance, width, alignment, owner, scope)
    } else {
        Ok(FitOutcome::Measured(ResolvedTextPlan::hidden_source(
            source, appearance, alignment, owner,
        )?))
    }
}

pub(crate) fn measure(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: f64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    measure_quanta(
        theme,
        source,
        appearance,
        capacity(width)?,
        alignment,
        owner,
        scope,
    )
}

/// A real parent row assignment, never an invented automatic-height constraint.
#[expect(
    clippy::too_many_arguments,
    reason = "the parent supplies an independent finite height in addition to the original text request"
)]
pub(crate) fn measure_height(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: f64,
    height: f64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    let Some(original) = appearance
        .layout
        .filter(|request| request.instructions().fit.is_some())
    else {
        return measure(theme, source, appearance, width, alignment, owner, scope);
    };
    let assigned_appearance = theme.theme.clone();
    let mut assigned = crate::text::TextRequestContext {
        theme: &assigned_appearance,
        ..*theme
    };
    assigned.trial.height = Some(capacity(height)?);
    Ok(
        match measure(
            &assigned, source, appearance, width, alignment, owner, scope,
        )? {
            FitOutcome::Measured(mut plan) => {
                if let Some(input) = plan.payload_mut().fit_input.as_mut() {
                    std::sync::Arc::make_mut(input).height = Some(capacity(height)?);
                }
                FitOutcome::Measured(plan.with_request(Some(original)))
            }
            FitOutcome::Miss(miss) => FitOutcome::Miss(miss),
        },
    )
}

pub(crate) fn measure_quanta(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: i64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    if !appearance.hidden()
        && appearance
            .layout
            .is_some_and(|request| request.instructions().fit.is_some())
    {
        return Ok(
            match super::font_fit::measure(
                theme, source, appearance, width, alignment, owner, scope,
            )? {
                FitOutcome::Measured(plan) => FitOutcome::Measured(plan.freeze_orientation()?),
                FitOutcome::Miss(miss) => FitOutcome::Miss(miss),
            },
        );
    }
    measure_unfitted(theme, source, appearance, width, alignment, owner, scope)
}

pub(super) fn measure_unfitted(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: i64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    let measured = if appearance.hidden() {
        None
    } else {
        appearance
            .layout
            .and_then(|request| request.instructions().overflow.as_ref())
            .and_then(|overflow| overflow.ellipsis.as_ref())
    };
    Ok(
        match if let Some(ellipsis) = measured {
            super::ellipsis::measure(
                theme, source, appearance, width, alignment, owner, scope, ellipsis,
            )?
        } else {
            measure_current(theme, source, appearance, width, alignment, owner, scope)?
        } {
            FitOutcome::Measured(plan) => FitOutcome::Measured(plan.freeze_orientation()?),
            FitOutcome::Miss(miss) => FitOutcome::Miss(miss),
        },
    )
}

#[expect(
    clippy::too_many_lines,
    clippy::cast_precision_loss,
    reason = "one complete text request resolves independent spatial/line constraints and its explicit terminal action"
)]
pub(super) fn measure_current(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: i64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    if appearance.hidden() {
        return Ok(FitOutcome::Measured(ResolvedTextPlan::hidden_source(
            source,
            appearance,
            appearance
                .layout
                .and_then(|layout| layout.alignment)
                .map_or(alignment, Into::into),
            owner,
        )?));
    }
    let request = appearance.layout.unwrap_or(&crate::text::TextLayout::EMPTY);
    let mut width = width;
    let mut assigned_height = theme.trial.height;
    if let Some(insets) = theme.trial.padding {
        let padding = |size: f64, horizontal: bool| -> Result<i64, super::TextPlanError> {
            let resolved = insets.resolve(crate::theme::LocalMetric::css_pixels(size)?, None)?;
            let total = if horizontal {
                resolved.horizontal()
            } else {
                resolved.vertical()
            };
            Ok(total
                .round(crate::layout::kernel::SpatialRounding::Ceil)?
                .quanta())
        };
        let size = appearance.theme.get_font_size();
        let h = padding(size, true).map_err(Error::from)?;
        let v = padding(size, false).map_err(Error::from)?;
        if let Some(trace) = &theme.trial.size_trace {
            trace
                .observe(h, |size| padding(size, true))
                .map_err(Error::from)?;
            trace
                .observe(v, |size| padding(size, false))
                .map_err(Error::from)?;
        }
        width = width.saturating_sub(h).max(0);
        assigned_height = assigned_height.map(|height| height.saturating_sub(v).max(0));
    }
    if let Some(crate::text::orientation::Orientation::Data(from, to)) = request
        .instructions()
        .orientation
        .as_ref()
        .map(|orientation| &orientation.0)
    {
        let frame = theme.reference.as_ref().ok_or_else(|| {
            Error::Data("data text direction requires actual scientific axes".into())
        })?;
        let resolved = request.clone().rotation(frame.rotation(from, to, theme)?);
        return Ok(
            match measure_quanta(
                theme,
                source,
                TextAppearance {
                    layout: Some(&resolved),
                    ..appearance
                },
                width,
                alignment,
                owner,
                scope,
            )? {
                FitOutcome::Measured(plan) => {
                    FitOutcome::Measured(plan.with_request(Some(request)))
                }
                FitOutcome::Miss(miss) => FitOutcome::Miss(miss),
            },
        );
    }
    let instructions = request.instructions();
    let rotated = match instructions
        .orientation
        .as_ref()
        .map(|orientation| &orientation.0)
    {
        Some(crate::text::orientation::Orientation::Fixed(rotation)) => Some(rotation.0.get()),
        Some(crate::text::orientation::Orientation::Data(..)) => {
            return Err(Error::Data(
                "data direction has no actual scientific projection".into(),
            ))
        }
        Some(crate::text::orientation::Orientation::Automatic(..)) => {
            return Err(Error::Data(
                "automatic orientation requires an actual tick group".into(),
            ))
        }
        None => None,
    };
    let assigned = width;
    let bounds = instructions.bounds;
    let width = bounds
        .and_then(|bounds| bounds.width)
        .map_or(Ok(width), |bound| bound_capacity(bound.get(), width))?;
    let height = bounds
        .and_then(|bounds| bounds.height)
        .map_or(Ok(i64::MAX), |bound| bound_capacity(bound.get(), i64::MAX))?;
    let alignment = request.alignment.map_or(alignment, Into::into);
    let wrap = instructions.wrapping != Some(TextWrapping::NoSoftWrap);
    let failure = instructions
        .overflow
        .as_ref()
        .map_or(TextFailure::Error, |overflow| overflow.failure);
    let hidden = instructions
        .visibility
        .as_ref()
        .is_some_and(|visibility| visibility.hidden);
    let maximum = if wrap {
        let projected = if let Some(angle) = rotated {
            let (_, cosine) = crate::text::orientation::components(angle);
            if cosine == 0.0 {
                i64::MAX
            } else {
                bound_capacity((assigned as f64 / 1024.0) / cosine.abs(), i64::MAX)?
            }
        } else {
            width
        };
        projected.min(
            bounds
                .and_then(|bounds| bounds.width)
                .map_or(Ok(i64::MAX), |bound| bound_capacity(bound.get(), i64::MAX))?,
        )
    } else {
        i64::MAX
    };
    let planned = fit::outcome(theme.plan_text_quanta_scoped(
        source,
        appearance.theme,
        maximum,
        alignment,
        owner,
        appearance.exact_override,
        instructions.direction.unwrap_or_default(),
        scope,
    ))?;
    let (plan, miss) = match planned {
        FitOutcome::Measured(plan) => (plan, None),
        FitOutcome::Miss(miss) if failure != TextFailure::Error || hidden => (
            theme
                .plan_text_quanta_scoped(
                    source,
                    appearance.theme,
                    i64::MAX,
                    alignment,
                    owner,
                    appearance.exact_override,
                    instructions.direction.unwrap_or_default(),
                    scope,
                )
                .map_err(fit::PlanError::into_error)?,
            Some(miss),
        ),
        FitOutcome::Miss(miss) => return Ok(FitOutcome::Miss(miss)),
    };
    let mut plan = plan.with_request(appearance.layout);
    if let Some(angle) = rotated.filter(|_| wrap) {
        let (sine, cosine) = crate::text::orientation::components(angle);
        let mut previous = maximum;
        loop {
            if cosine == 0.0 {
                break;
            }
            let available = assigned as f64 / 1024.0 - plan.height() * sine.abs();
            let next = bound_capacity((available / cosine.abs()).max(0.0), previous)?;
            if next >= previous {
                break;
            }
            match fit::outcome(theme.plan_text_quanta_scoped(
                source,
                appearance.theme,
                next,
                alignment,
                owner,
                appearance.exact_override,
                instructions.direction.unwrap_or_default(),
                scope,
            ))? {
                FitOutcome::Measured(value) => {
                    plan = value.with_request(appearance.layout);
                    previous = next;
                }
                FitOutcome::Miss(_) => break,
            }
        }
    }
    if hidden {
        return Ok(FitOutcome::Measured(plan.hide()?));
    }
    let physical_width = if rotated.is_some() {
        let placement = super::placement::at(
            &plan,
            crate::render::backend::Point2D::new(0.0, 0.0),
            crate::text::TextAnchor::center(),
            0.0,
            false,
            None,
        )?;
        super::placement::logical_bounds(placement, &plan)?.width()
    } else {
        plan.width()
    };
    let physical_height = if let Some(angle) = rotated {
        let (sine, cosine) = crate::text::orientation::components(angle);
        plan.width() * sine.abs() + plan.height() * cosine.abs()
    } else {
        plan.height()
    };
    let fits = miss.is_none()
        && physical_width <= assigned as f64 / 1024.0
        && bounds
            .and_then(|bounds| bounds.width)
            .is_none_or(|bound| plan.width() <= bound.get())
        && plan.height_quanta <= height
        && assigned_height.is_none_or(|height| physical_height <= height as f64 / 1024.0)
        && bounds
            .and_then(|bounds| bounds.lines)
            .is_none_or(|limit| plan.lines.len() <= limit);
    if fits {
        return Ok(FitOutcome::Measured(plan));
    }
    match failure {
        TextFailure::Error => Ok(FitOutcome::Miss(miss.unwrap_or_else(|| {
            scope.failure(
                fit::FitKind::Text,
                format!("{owner}: complete text exceeds its declared bounds (projected width {physical_width}, assigned width {})",assigned as f64/1024.0),
            )
        }))),
        TextFailure::Hide => Ok(FitOutcome::Measured(plan.hide()?)),
        TextFailure::Visible => Ok(FitOutcome::Measured(plan)),
        TextFailure::Clip => {
            let lines = bounds
                .and_then(|bounds| bounds.lines)
                .map_or(height, |count| {
                    if count == 0 {
                        0
                    } else {
                        i64::try_from(count)
                            .ok()
                            .and_then(|count| plan.line_pitch_quanta.checked_mul(count))
                            .unwrap_or(i64::MAX)
                            .min(height)
                    }
                });
            Ok(FitOutcome::Measured(plan.clip_to(width, lines)))
        }
    }
}

fn capacity(value: f64) -> Result<i64, Error> {
    super::maximum_width_quanta(value).map_err(Error::from)
}

#[expect(
    clippy::cast_precision_loss,
    reason = "a larger finite caller maximum does not consume geometry beyond the actual representable capacity"
)]
fn bound_capacity(value: f64, assigned: i64) -> Result<i64, Error> {
    if value >= assigned as f64 / 1024.0 {
        Ok(assigned)
    } else {
        capacity(value).map(|limit| assigned.min(limit))
    }
}