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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Local font fitting over certified metric cells, never a sampled-size quota.

pub(crate) mod stability;
#[cfg(test)]
mod tests;

use super::{ExactRational, PhysicalTextAlignment, ResolvedTextPlan, TextPlanError};
use crate::layout::fit::{FitOutcome, FitScope};
use crate::text::TextAppearance;
use crate::{
    text::{TextFailure, TextFitPriority, TextOverflow},
    theme::TextTheme,
    Error,
};
use std::sync::Arc;

/// The original preferred appearance and assignment are distinct from the
/// selected font size and display. They also make actual-group remeasurement
/// independent of formatters and source callbacks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FitInput {
    pub(crate) appearance: TextTheme,
    pub(crate) width: i64,
    pub(crate) exact_override: bool,
    pub(crate) height: Option<i64>,
    pub(crate) padding: Option<crate::layout::Insets>,
    contrast_role: Option<bool>,
}

#[expect(
    clippy::too_many_lines,
    reason = "the single local transaction orders complete/marked size programs, their certified exclusions and terminal floor handling"
)]
pub(crate) fn measure(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
    width: i64,
    alignment: PhysicalTextAlignment,
    owner: &str,
    scope: &FitScope,
) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
    let request = appearance.layout.expect("font fit request");
    let policy = request.instructions().fit.expect("font fit policy");
    let preferred = appearance.theme.get_font_size();
    let (minimum, maximum) = policy.bounds(preferred)?;
    let permitted = preferred.clamp(minimum, maximum);
    let mut complete = complete_request(request);
    complete.edit_instructions().fit = None;
    let mut marked = request.clone();
    marked.edit_instructions().fit = None;
    if let Some(overflow) = marked.edit_instructions().overflow.as_mut() {
        overflow.failure = TextFailure::Error;
    }
    let priority = request.instructions().fit_priority.unwrap_or_default();
    let ellipsis = request
        .instructions()
        .overflow
        .as_ref()
        .and_then(|overflow| overflow.ellipsis.as_ref());
    let mut basis_request = complete.clone();
    let instructions = basis_request.edit_instructions();
    instructions.bounds = None;
    instructions.orientation = None;
    instructions.wrapping = Some(crate::text::TextWrapping::NoSoftWrap);
    let basis_style = appearance.theme.clone().font_size(1.0)?;
    let basis_appearance = theme.theme.clone();
    let mut basis_theme = crate::text::TextRequestContext {
        theme: &basis_appearance,
        ..*theme
    };
    basis_theme.trial.height = None;
    basis_theme.trial.size_trace = None;
    basis_theme.trial.padding = None;
    let basis = match super::request::measure_current(
        &basis_theme,
        source,
        TextAppearance {
            theme: &basis_style,
            layout: Some(&basis_request),
            ..appearance
        },
        i64::MAX,
        alignment,
        owner,
        scope,
    )? {
        FitOutcome::Measured(plan) => plan,
        FitOutcome::Miss(miss) => return Ok(FitOutcome::Miss(miss)),
    };
    let evidence = BoundsEvidence::new(&basis, theme.text.prepared_font_environment()?, appearance)
        .map_err(metric_error)?;
    let selected = |layout: &crate::text::TextLayout, size: f64| -> Result<_, Error> {
        let style = appearance.theme.clone().font_size(size)?;
        let trace = Arc::new(stability::Stability::new(size, minimum));
        let trial_appearance = theme.theme.clone();
        let mut trial = crate::text::TextRequestContext {
            theme: &trial_appearance,
            ..*theme
        };
        trial.trial.size_trace = Some(&trace);
        let outcome = super::request::measure_unfitted(
            &trial,
            source,
            TextAppearance {
                theme: &style,
                layout: Some(layout),
                ..appearance
            },
            width,
            alignment,
            owner,
            scope,
        )?;
        Ok((outcome, trace))
    };
    let finish = |mut plan: ResolvedTextPlan| -> Result<_, Error> {
        // The selected glyphs are enough for capture. Do not keep trial analyses
        // (and their failed-size certificates) alive as an all-candidate cache.
        plan.1 = None;
        plan.payload_mut().fit_input = Some(Arc::new(FitInput {
            appearance: appearance.theme.clone(),
            width,
            exact_override: appearance.exact_override,
            height: theme.trial.height,
            padding: theme.trial.padding.cloned(),
            // These references identify deliberate appearance owners, never
            // equality inferred from equal current glyphs or preferred sizes.
            contrast_role: if std::ptr::eq(
                appearance.theme,
                theme
                    .typography
                    .get_annotations()
                    .get_contrast()
                    .get_light(),
            ) {
                Some(true)
            } else if std::ptr::eq(
                appearance.theme,
                theme.typography.get_annotations().get_contrast().get_dark(),
            ) {
                Some(false)
            } else {
                None
            },
        }));
        Ok(FitOutcome::Measured(plan.with_request(Some(request))))
    };
    if priority == TextFitPriority::PreferredSizeFirst && ellipsis.is_some() {
        if let (FitOutcome::Measured(plan), _) = selected(&marked, permitted)? {
            return finish(plan);
        }
    }
    for layout in std::iter::once(&complete).chain(ellipsis.map(|_| &marked)) {
        let Some(ceiling) = evidence.ceiling(
            layout,
            width,
            minimum,
            maximum,
            theme.trial.height,
            layout
                .instructions()
                .overflow
                .as_ref()
                .is_none_or(|overflow| overflow.ellipsis.is_none()),
        )?
        else {
            continue;
        };
        let target = permitted.min(ceiling);
        let mut proposal = target;
        if basis.width() > 0.0 {
            proposal = proposal.min(pixels(width) / basis.width());
        }
        if let Some(height) = layout
            .instructions()
            .bounds
            .and_then(|bounds| bounds.height)
        {
            proposal = proposal.min(height.get() / basis.height());
        }
        if let Some(width) = layout.instructions().bounds.and_then(|bounds| bounds.width) {
            if basis.width() > 0.0 {
                proposal = proposal.min(width.get() / basis.width());
            }
        }
        proposal = proposal.clamp(minimum, ceiling);
        // Endpoints and the real clamped preference are measured explicitly.
        for size in [ceiling, target, proposal, minimum] {
            if let (FitOutcome::Measured(plan), _) = selected(layout, size)? {
                return finish(plan);
            }
        }
        let mut size = ceiling;
        loop {
            let (outcome, trace) = selected(layout, size)?;
            if let FitOutcome::Measured(plan) = outcome {
                return finish(plan);
            }
            let lower = trace.lower().map_err(Error::from)?;
            if lower <= minimum {
                break;
            }
            // Every reached rounded metric, wrap decision and derived-view
            // decision is unchanged on [lower,size]. Exclude exactly that cell.
            // At least one positive finite bit pattern is removed each time.
            size = f64::from_bits(lower.to_bits() - 1);
        }
    }
    let style = appearance.theme.clone().font_size(minimum)?;
    let mut terminal = request.clone();
    terminal.edit_instructions().fit = None;
    let outcome = super::request::measure_unfitted(
        theme,
        source,
        TextAppearance {
            theme: &style,
            layout: Some(&terminal),
            ..appearance
        },
        width,
        alignment,
        owner,
        scope,
    )?;
    match outcome {
        FitOutcome::Measured(plan) => finish(plan),
        FitOutcome::Miss(miss) => Ok(FitOutcome::Miss(miss)),
    }
}

/// Optimistic, exact design-space lower bounds prune only proven nonfits.
/// Rounded glyph origins move an ideal full-line ink span by at most one
/// quantum. A zero nominal lower bound is valid evidence, not a bad face.
struct BoundsEvidence {
    width: ExactRational,
    metric: ExactRational,
    paragraphs: usize,
    unbreakable: bool,
}
impl BoundsEvidence {
    fn new(
        basis: &ResolvedTextPlan,
        environment: &crate::font::canonical::PreparedFontEnvironment,
        appearance: TextAppearance<'_>,
    ) -> Result<Self, TextPlanError> {
        let mut width = ExactRational::ZERO;
        for line in &basis.lines {
            let mut pen_x = ExactRational::ZERO;
            let mut pen_y = ExactRational::ZERO;
            let mut ink: Option<super::ExactInk> = None;
            for run in &line.runs {
                for glyph in &run.glyphs {
                    if let Some(design) = glyph.design_ink {
                        let x = pen_x.add(
                            &ExactRational::design(
                                glyph.design_x_offset.into(),
                                1.0,
                                run.units_per_em,
                            )?,
                            "ideal glyph",
                        )?;
                        let y = pen_y.add(
                            &ExactRational::design(
                                glyph.design_y_offset.into(),
                                1.0,
                                run.units_per_em,
                            )?,
                            "ideal glyph",
                        )?;
                        let next =
                            super::exact_glyph_ink(design, 0, 0, 1.0.into(), run.units_per_em)?
                                .translated(&x, &y)?;
                        ink = Some(match ink {
                            Some(current) => current.union(next),
                            None => next,
                        });
                    }
                    pen_x = pen_x.add(
                        &ExactRational::design(
                            glyph.design_x_advance.into(),
                            1.0,
                            run.units_per_em,
                        )?,
                        "ideal pen",
                    )?;
                    pen_y = pen_y.add(
                        &ExactRational::design(
                            glyph.design_y_advance.into(),
                            1.0,
                            run.units_per_em,
                        )?,
                        "ideal pen",
                    )?;
                }
            }
            if let Some(ink) = ink {
                width = width.max(ink.right.add(&ink.left.negated()?, "ideal span")?);
            }
        }
        let metric = nominal_height_evidence(environment, &basis.source, appearance)?;
        let mut unbreakable = true;
        if let Some(analysis) = &basis.1 {
            for paragraph in &analysis.paragraphs {
                unbreakable &= super::legal_line_breaks_at_graphemes(
                    &basis.source[paragraph.span.range()],
                    &paragraph.grapheme_ends,
                )?
                .len()
                    <= 1;
            }
        }
        Ok(Self {
            width,
            metric,
            paragraphs: basis.lines.len(),
            unbreakable,
        })
    }
    fn ceiling(
        &self,
        request: &crate::text::TextLayout,
        width: i64,
        minimum: f64,
        maximum: f64,
        assigned_height: Option<i64>,
        complete: bool,
    ) -> Result<Option<f64>, Error> {
        let bounds = request.instructions().bounds;
        if bounds.and_then(|bounds| bounds.lines) == Some(0)
            || (complete
                && bounds
                    .and_then(|bounds| bounds.lines)
                    .is_some_and(|lines| lines < self.paragraphs))
        {
            return Ok(None);
        }
        let possible = |size: f64| -> Result<bool, TextPlanError> {
            let factor = ExactRational::design(1, size, 1024)?;
            // A reached marker can introduce a different face. Do not admit it
            // early, or use the original source's nominal floor for marked views.
            let metric = if complete {
                self.metric.clone()
            } else {
                ExactRational::ZERO
            }
            .multiply(&factor)?
            .multiply(&ExactRational::new(
                if complete {
                    i128::try_from(self.paragraphs)
                        .map_err(|_| TextPlanError::Arithmetic("font fit paragraph count"))?
                } else {
                    1
                },
                1,
            )?)?;
            if request.instructions().orientation.is_none()
                && assigned_height
                    .is_some_and(|height| metric.greater(&ExactRational::Small(height.into(), 1)))
            {
                return Ok(false);
            }
            if let Some(height) = bounds.and_then(|bounds| bounds.height) {
                if metric.greater(&ExactRational::design(
                    1,
                    height.get().max(f64::from_bits(1)),
                    1,
                )?) || height.get() == 0.0
                {
                    return Ok(false);
                }
            }
            if complete
                && (self.unbreakable
                    || bounds.and_then(|bounds| bounds.lines) == Some(self.paragraphs)
                    || request.instructions().wrapping
                        == Some(crate::text::TextWrapping::NoSoftWrap))
            {
                let span = self
                    .width
                    .multiply(&factor)?
                    .add(&ExactRational::new(-1, 1)?, "ideal span error")?;
                if let Some(bound) = bounds.and_then(|bounds| bounds.width) {
                    let limit = if bound.get() == 0.0 {
                        ExactRational::ZERO
                    } else {
                        ExactRational::design(1, bound.get(), 1)?
                    };
                    if span.greater(&limit) {
                        return Ok(false);
                    }
                }
                if request.instructions().orientation.is_none()
                    && span.greater(&ExactRational::new(width.into(), 1)?)
                {
                    return Ok(false);
                }
            }
            Ok(true)
        };
        if !possible(minimum).map_err(metric_error)? {
            return Ok(None);
        }
        if possible(maximum).map_err(metric_error)? {
            return Ok(Some(maximum));
        }
        let mut lo = minimum.to_bits();
        let mut hi = maximum.to_bits();
        while hi - lo > 1 {
            let middle = lo + (hi - lo) / 2;
            if possible(f64::from_bits(middle)).map_err(metric_error)? {
                lo = middle;
            } else {
                hi = middle;
            }
        }
        Ok(Some(f64::from_bits(lo)))
    }
}

/// Closed over this actual source's selected units, discretionary hyphen and
/// possible primary-only empty/control lines, not every candidate in the stack
/// or previously admitted source. Every participating face contributes, even 0.
fn nominal_height_evidence(
    environment: &crate::font::canonical::PreparedFontEnvironment,
    source: &str,
    appearance: TextAppearance<'_>,
) -> Result<ExactRational, TextPlanError> {
    use crate::font::canonical::{selection_units, ScalarFaceSelection};
    let pair = environment
        .prepared_pair(
            appearance.theme.get_stack(),
            appearance.theme.get_weight().into(),
        )?
        .ok_or(TextPlanError::MissingPreparedPair)?;
    let mut metric: Option<ExactRational> = None;
    let mut include = |identity| -> Result<(), TextPlanError> {
        let metrics = environment.face_metrics(identity)?;
        let height = i64::from(metrics.ascender).max(0) - i64::from(metrics.descender).min(0);
        let next = ExactRational::design(height, 1.0, metrics.units_per_em)?;
        metric = Some(metric.take().map_or(next.clone(), |prior| prior.min(next)));
        Ok(())
    };
    for unit in selection_units(source) {
        for scalar in unit.chars() {
            if let ScalarFaceSelection::Face(identity) = pair.selection_for_unit(unit, scalar)? {
                include(identity)?;
            }
        }
    }
    if source.contains('\u{ad}') {
        if let ScalarFaceSelection::Face(identity) = pair.selection_for_unit("-", '-')? {
            include(identity)?;
        }
    }
    if source.chars().any(crate::text::is_nonpainting_control)
        || super::mandatory_paragraph_seeds(source)?
            .iter()
            .any(|seed| seed.span.range().is_empty())
    {
        include(pair.primary)?;
    }
    Ok(metric.unwrap_or(ExactRational::ZERO))
}
fn metric_error(error: TextPlanError) -> Error {
    Error::from(error).with_prefix("font fit metric evidence")
}

#[expect(
    clippy::cast_precision_loss,
    reason = "the actual assignment is represented in canonical text quanta"
)]
fn pixels(value: i64) -> f64 {
    value as f64 / 1024.0
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GroupMember {
    source: String,
    input: Arc<FitInput>,
    request: crate::text::TextLayout,
}

/// Called by one actual role before its selected metrics allocate geometry.
/// Independent slots never call this together. Different contrast appearances
/// remain different groups even when their preferred sizes happen to match.
#[expect(
    clippy::too_many_lines,
    reason = "actual group membership, common interval and joint certified trials are frozen together"
)]
pub(crate) fn uniform(
    theme: &crate::text::TextRequestContext<'_, '_>,
    plans: &mut [ResolvedTextPlan],
    scope: &FitScope,
) -> Result<(), crate::layout::fit::PlanError> {
    let mut visited = crate::data::source::collect_source(plans.iter().map(|_| Ok(false)))?;
    for start in 0..plans.len() {
        if visited[start] || !is_uniform(&plans[start]) {
            continue;
        }
        let indices = crate::data::source::collect_source(
            (start..plans.len())
                .filter(|&index| {
                    is_uniform(&plans[index]) && same_appearance(&plans[start], &plans[index])
                })
                .map(Ok),
        )?;
        for &index in &indices {
            visited[index] = true;
        }
        let mut minimum = 0.0_f64;
        let mut maximum = f64::MAX;
        let mut target = f64::MAX;
        let mut members = Vec::new();
        crate::data::source::reserve_source(&mut members, indices.len())?;
        for &index in &indices {
            let plan = &plans[index];
            let input = plan.fit_input.as_ref().expect("uniform fit input");
            let request = plan.request.as_ref().expect("uniform request");
            let (lower, upper) = request
                .instructions()
                .fit
                .expect("uniform fit")
                .bounds(input.appearance.get_font_size())?;
            minimum = minimum.max(lower);
            maximum = maximum.min(upper);
            target = target.min(plan.style.font_size);
            members.push(GroupMember {
                source: crate::data::source::copy_source_string(plan.original_source())?,
                input: Arc::clone(input),
                request: request.clone(),
            });
        }
        if minimum > maximum {
            return Err(scope
                .failure(
                    crate::layout::fit::FitKind::Text,
                    "uniform text group has no common permitted font size",
                )
                .into());
        }
        target = target.clamp(minimum, maximum);
        if indices
            .iter()
            .all(|&index| plans[index].style.font_size.to_bits() == target.to_bits())
        {
            let identity = crate::data::source::source_arc((scope.address.clone(), members))?;
            for &index in &indices {
                plans[index].payload_mut().fit_group = Some(Arc::clone(&identity));
            }
            continue;
        }
        let mut accepted = None;
        for abbreviated in [false, true] {
            if abbreviated
                && !members.iter().any(|member| {
                    member
                        .request
                        .instructions()
                        .overflow
                        .as_ref()
                        .is_some_and(|overflow| overflow.ellipsis.is_some())
                })
            {
                continue;
            }
            let mut initial = Some(target);
            let mut size = target;
            loop {
                let trace = Arc::new(stability::Stability::new(size, minimum));
                let trial_appearance = theme.theme.clone();
                let mut trial = crate::text::TextRequestContext {
                    theme: &trial_appearance,
                    ..*theme
                };
                trial.trial.size_trace = Some(&trace);
                let mut selected = Vec::new();
                crate::data::source::reserve_source(&mut selected, indices.len())?;
                let mut miss = false;
                for (&index, member) in indices.iter().zip(&members) {
                    let mut request = member.request.clone();
                    trial.trial.height = member.input.height;
                    trial.trial.padding = member.input.padding.as_ref();
                    request.edit_instructions().fit = None;
                    if abbreviated
                        || (member.request.instructions().fit_priority
                            == Some(TextFitPriority::PreferredSizeFirst)
                            && size.to_bits()
                                == member
                                    .input
                                    .appearance
                                    .get_font_size()
                                    .clamp(minimum, maximum)
                                    .to_bits())
                    {
                        if let Some(overflow) = request.edit_instructions().overflow.as_mut() {
                            overflow.failure = TextFailure::Error;
                        }
                    } else {
                        request = complete_request(&request);
                    }
                    let style = member.input.appearance.clone().font_size(size)?;
                    match super::request::measure_unfitted(
                        &trial,
                        &member.source,
                        TextAppearance {
                            theme: &style,
                            exact_override: member.input.exact_override,
                            layout: Some(&request),
                        },
                        member.input.width,
                        plans[index].style.alignment,
                        &plans[index].style.provenance.owner,
                        scope,
                    )? {
                        FitOutcome::Measured(mut plan) => {
                            plan.1 = None;
                            plan.payload_mut().fit_input = Some(Arc::clone(&member.input));
                            selected.push(plan.with_request(Some(&member.request)));
                        }
                        FitOutcome::Miss(_) => miss = true,
                    }
                }
                if !miss {
                    accepted = Some(selected);
                    break;
                }
                if initial.take().is_some() {
                    size = maximum;
                    continue;
                }
                let lower = trace.lower().map_err(metric_error)?;
                if lower <= minimum {
                    break;
                }
                size = f64::from_bits(lower.to_bits() - 1);
            }
            if accepted.is_some() {
                break;
            }
        }
        let selected = if let Some(selected) = accepted {
            selected
        } else {
            crate::layout::fit::collect(
                "uniform text floor",
                indices.iter().zip(&members).map(|(&index, member)| {
                    let request = member
                        .request
                        .clone()
                        .fit(crate::text::TextFit::range(minimum, minimum)?);
                    let result = super::request::measure_quanta(
                        theme,
                        &member.source,
                        TextAppearance {
                            theme: &member.input.appearance,
                            exact_override: member.input.exact_override,
                            layout: Some(&request),
                        },
                        member.input.width,
                        plans[index].style.alignment,
                        &plans[index].style.provenance.owner,
                        scope,
                    )?;
                    crate::layout::fit::measured(Ok(result))
                        .map(|plan| plan.with_request(Some(&member.request)))
                }),
            )?
        };
        let identity = crate::data::source::source_arc((scope.address.clone(), members))?;
        for (&index, mut plan) in indices.iter().zip(selected) {
            plan.payload_mut().fit_group = Some(Arc::clone(&identity));
            plans[index] = plan.freeze_orientation()?;
        }
    }
    Ok(())
}

fn is_uniform(plan: &ResolvedTextPlan) -> bool {
    plan.fit_group.is_none()
        && plan.fit_input.is_some()
        && plan
            .request
            .as_ref()
            .and_then(|request| request.instructions().fit)
            .is_some_and(|fit| fit.grouping == crate::text::TextFitGrouping::Uniform)
}

pub(crate) fn uniform_options(
    theme: &crate::text::TextRequestContext<'_, '_>,
    plans: &mut [Option<ResolvedTextPlan>],
    scope: &FitScope,
) -> Result<(), crate::layout::fit::PlanError> {
    let mut selected =
        crate::data::source::collect_source(plans.iter().flatten().cloned().map(Ok))?;
    uniform(theme, &mut selected, scope)?;
    for (target, plan) in plans.iter_mut().filter(|plan| plan.is_some()).zip(selected) {
        *target = Some(plan);
    }
    Ok(())
}

pub(crate) fn uniform_placed(
    theme: &crate::text::TextRequestContext<'_, '_>,
    text: &mut [crate::render::backend::PlacedText],
    scope: &FitScope,
) -> Result<(), crate::layout::fit::PlanError> {
    if !text.iter().any(|text| is_uniform(&text.plan)) {
        return Ok(());
    }
    let mut plans =
        crate::data::source::collect_source(text.iter().map(|text| Ok(text.plan.clone())))?;
    uniform(theme, &mut plans, scope)?;
    for (text, plan) in text.iter_mut().zip(plans) {
        text.placement = super::placement::remeasure(text.placement, &text.plan, &plan)?;
        text.plan = plan;
    }
    Ok(())
}
fn same_appearance(a: &ResolvedTextPlan, b: &ResolvedTextPlan) -> bool {
    if a.fit_input.as_ref().expect("fit input").contrast_role
        != b.fit_input.as_ref().expect("fit input").contrast_role
    {
        return false;
    }
    let a = &a.fit_input.as_ref().expect("fit input").appearance;
    let b = &b.fit_input.as_ref().expect("fit input").appearance;
    a.get_stack() == b.get_stack()
        && a.get_color() == b.get_color()
        && a.get_weight() == b.get_weight()
        && a.get_line_height().to_bits() == b.get_line_height().to_bits()
}

pub(crate) fn minimum_height(
    theme: &crate::text::TextRequestContext<'_, '_>,
    source: &str,
    appearance: TextAppearance<'_>,
) -> Result<Option<i64>, Error> {
    let Some(request) = appearance
        .layout
        .filter(|request| request.instructions().fit.is_some())
    else {
        return Ok(None);
    };
    if appearance.hidden()
        || request.instructions().orientation.is_some()
        || request
            .instructions()
            .overflow
            .as_ref()
            .is_some_and(|overflow| overflow.failure != TextFailure::Error)
    {
        return Ok(Some(0));
    }
    let minimum = request
        .instructions()
        .fit
        .expect("fit policy")
        .bounds(appearance.theme.get_font_size())?
        .0;
    let environment = theme.text.prepared_font_environment()?;
    if request
        .instructions()
        .overflow
        .as_ref()
        .is_some_and(|overflow| overflow.ellipsis.is_some())
    {
        return Ok(Some(0));
    }
    let metric = nominal_height_evidence(environment, source, appearance).map_err(metric_error)?;
    let count = super::mandatory_paragraph_seeds(source)
        .map_err(metric_error)?
        .len();
    let count = i128::try_from(count)
        .map_err(|_| Error::Render("text minimum paragraph count overflow".into()))?;
    Ok(Some(
        metric
            .multiply(&ExactRational::design(1, minimum, 1024).map_err(metric_error)?)
            .map_err(metric_error)?
            .multiply(&ExactRational::new(count, 1).map_err(metric_error)?)
            .map_err(metric_error)?
            .ceil_i64("minimum text height")
            .map_err(metric_error)?,
    ))
}

pub(crate) fn assign_height(
    theme: &crate::text::TextRequestContext<'_, '_>,
    plan: &ResolvedTextPlan,
    height: f64,
    scope: &FitScope,
) -> Result<ResolvedTextPlan, crate::layout::fit::PlanError> {
    let Some(input) = &plan.fit_input else {
        return Ok(plan.clone());
    };
    let assigned_appearance = theme.theme.clone();
    let mut assigned = crate::text::TextRequestContext {
        theme: &assigned_appearance,
        ..*theme
    };
    assigned.trial.padding = input.padding.as_ref();
    crate::layout::fit::measured(super::request::measure_height(
        &assigned,
        plan.original_source(),
        TextAppearance {
            theme: &input.appearance,
            exact_override: input.exact_override,
            layout: plan.request.as_ref(),
        },
        pixels(input.width),
        height,
        plan.style.alignment,
        &plan.style.provenance.owner,
        scope,
    ))
}

pub(crate) fn hard_height(
    theme: &crate::text::TextRequestContext<'_, '_>,
    plan: &ResolvedTextPlan,
) -> Result<(f64, f64), Error> {
    let Some(input) = &plan.fit_input else {
        return Ok((plan.occupied_size().1, plan.style.font_size));
    };
    let request = plan.request.as_ref().expect("fitted request");
    let size = request
        .instructions()
        .fit
        .expect("fitted policy")
        .bounds(input.appearance.get_font_size())?
        .0;
    let height = minimum_height(
        theme,
        plan.original_source(),
        TextAppearance {
            theme: &input.appearance,
            exact_override: input.exact_override,
            layout: Some(request),
        },
    )?
    .unwrap_or(plan.occupied_height_quanta());
    Ok((pixels(height), size))
}

fn complete_request(request: &crate::text::TextLayout) -> crate::text::TextLayout {
    let mut complete = request.clone().overflow(TextOverflow::complete());
    if let Some(lines) = request
        .instructions()
        .overflow
        .as_ref()
        .and_then(|overflow| overflow.ellipsis.as_ref())
        .and_then(|ellipsis| ellipsis.lines)
    {
        let bounds = complete
            .instructions()
            .bounds
            .unwrap_or(crate::text::TextBounds {
                width: None,
                height: None,
                lines: None,
            });
        complete.edit_instructions().bounds = Some(crate::text::TextBounds {
            lines: Some(bounds.lines.map_or(lines, |value| value.min(lines))),
            ..bounds
        });
    }
    complete
}