1use crate::layout::{AddressRole, ComponentAddress};
4use crate::layout::{PhysicalTextAlignment, ResolvedTextPlan};
5use crate::Error;
6
7#[allow(
8 dead_code,
9 reason = "the complete canonical diagnostic order is shared by migrated and native owners"
10)]
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12#[non_exhaustive]
14pub enum FitKind {
15 Constraint,
17 Text,
19 Tick,
21 LegendOrGuide,
23 TrackOrResidual,
25 OverlayCollision,
27 SpecializedGeometry,
29 AssignedChild,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
34pub struct FitReason {
36 pub kind: FitKind,
38 pub address: ComponentAddress,
40 pub ordinal: u32,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub(crate) struct FitFailure {
46 pub(crate) reason: FitReason,
47 pub(crate) message: String,
48}
49
50impl std::fmt::Display for FitFailure {
51 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 write!(formatter, "layout fit {:?}: {}", self.reason, self.message)
53 }
54}
55
56impl FitFailure {
57 pub(crate) fn into_error(self) -> Error {
58 use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
59 let message = self.to_string();
60 Error::Render(
61 Diagnostic::new(
62 DiagnosticKind::LayoutConflict {
63 reason: self.reason,
64 },
65 message,
66 )
67 .with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
68 )
69 }
70
71 pub(crate) fn retain_least(slot: &mut Option<Self>, failure: Self) {
72 if slot
73 .as_ref()
74 .is_none_or(|current| failure.reason < current.reason)
75 {
76 *slot = Some(failure);
77 }
78 }
79}
80
81#[derive(Debug, Clone)]
82pub(crate) struct FitScope {
83 pub(crate) address: ComponentAddress,
84 pub(crate) ordinal: u32,
85}
86
87impl FitScope {
88 pub(crate) fn new(address: &ComponentAddress, ordinal: u32) -> Self {
89 Self {
90 address: address.clone(),
91 ordinal,
92 }
93 }
94 pub(crate) fn root() -> Self {
95 Self::new(&ComponentAddress::root(), 0)
96 }
97 pub(crate) fn child(&self, role: AddressRole, index: usize) -> Result<Self, Error> {
98 let index = u32::try_from(index)
99 .map_err(|_| Error::Render("fit address index overflowed".into()))?;
100 Ok(Self {
101 address: self.address.child(role, index)?,
102 ordinal: 0,
103 })
104 }
105 pub(crate) fn failure(&self, kind: FitKind, message: impl Into<String>) -> FitFailure {
106 FitFailure {
107 reason: FitReason {
108 kind,
109 address: self.address.clone(),
110 ordinal: self.ordinal,
111 },
112 message: message.into(),
113 }
114 }
115}
116
117pub(crate) enum FitOutcome<T> {
118 Measured(T),
119 Miss(FitFailure),
120}
121
122pub(crate) static ROOT_SCOPE: std::sync::LazyLock<FitScope> =
123 std::sync::LazyLock::new(FitScope::root);
124
125#[derive(Debug)]
126pub(crate) enum PlanError {
127 Fatal(Error),
128 Fit(FitFailure),
129}
130
131impl From<Error> for PlanError {
132 fn from(error: Error) -> Self {
133 Self::Fatal(error)
134 }
135}
136
137impl From<FitFailure> for PlanError {
138 fn from(failure: FitFailure) -> Self {
139 Self::Fit(failure)
140 }
141}
142
143impl PlanError {
144 pub(crate) fn into_error(self) -> Error {
145 match self {
146 Self::Fatal(error) => error,
147 Self::Fit(failure) => failure.into_error(),
148 }
149 }
150}
151
152pub(crate) fn outcome<T>(result: Result<T, PlanError>) -> Result<FitOutcome<T>, Error> {
153 match result {
154 Ok(value) => Ok(FitOutcome::Measured(value)),
155 Err(PlanError::Fit(failure)) => Ok(FitOutcome::Miss(failure)),
156 Err(PlanError::Fatal(error)) => Err(error),
157 }
158}
159
160pub(crate) fn measured<T>(result: Result<FitOutcome<T>, Error>) -> Result<T, PlanError> {
161 match result? {
162 FitOutcome::Measured(value) => Ok(value),
163 FitOutcome::Miss(failure) => Err(PlanError::Fit(failure)),
164 }
165}
166
167pub(crate) fn text<'a>(
168 theme: &crate::text::TextRequestContext<'_, '_>,
169 source: &str,
170 appearance: impl Into<crate::text::TextAppearance<'a>>,
171 width: f64,
172 alignment: PhysicalTextAlignment,
173 owner: &str,
174 scope: &FitScope,
175) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
176 let appearance = appearance.into();
177 if !appearance.hidden() {
178 theme.text.prepare_font_environment()?;
179 }
180 if width.is_finite() && width < 0.0 {
181 return Ok(FitOutcome::Miss(scope.failure(
182 FitKind::Constraint,
183 format!("{owner}: negative assigned text width"),
184 )));
185 }
186 super::text::request::measure(theme, source, appearance, width, alignment, owner, scope)
187}
188
189pub(crate) fn single_text<'a>(
191 theme: &crate::text::TextRequestContext<'_, '_>,
192 source: &str,
193 appearance: impl Into<crate::text::TextAppearance<'a>>,
194 width: f64,
195 alignment: PhysicalTextAlignment,
196 owner: &str,
197 scope: &FitScope,
198) -> Result<FitOutcome<ResolvedTextPlan>, Error> {
199 let appearance = appearance.into().require_single()?;
200 text(theme, source, appearance, width, alignment, owner, scope)
201}
202
203pub(crate) fn reserve<T>(values: &mut Vec<T>, count: usize, owner: &str) -> Result<(), Error> {
204 crate::operation::check()?;
205 values
206 .try_reserve_exact(count)
207 .map_err(|error| Error::Render(format!("{owner} allocation: {error}").into()))
208}
209
210pub(crate) fn collect<T>(
212 owner: &str,
213 values: impl Iterator<Item = Result<T, PlanError>>,
214) -> Result<Vec<T>, PlanError> {
215 let mut output = Vec::new();
216 let count = values.size_hint().1.ok_or_else(|| {
217 Error::Render(format!("{owner}: sibling collection has no finite admission bound").into())
218 })?;
219 reserve(&mut output, count, owner)?;
220 let mut miss = None;
221 for value in values {
222 match value {
223 Ok(value) => output.push(value),
224 Err(PlanError::Fit(failure)) => FitFailure::retain_least(&mut miss, failure),
225 Err(error) => return Err(error),
226 }
227 }
228 match miss {
229 Some(failure) => Err(failure.into()),
230 None => Ok(output),
231 }
232}
233
234#[expect(
235 clippy::cast_precision_loss,
236 reason = "intrinsic quantum widths are compared with root-bounded pixel assignments"
237)]
238pub(crate) fn intrinsic_widths<'a>(
239 theme: &crate::text::TextRequestContext<'_, '_>,
240 source: &str,
241 appearance: impl Into<crate::text::TextAppearance<'a>>,
242 owner: &str,
243) -> Result<(f64, f64), Error> {
244 let appearance = appearance.into();
245 if appearance.hidden() {
246 return Ok((0.0, 0.0));
247 }
248 let unwrapped = theme.measure_text(
249 source,
250 appearance.theme,
251 PhysicalTextAlignment::Start,
252 owner,
253 appearance.exact_override,
254 )?;
255 let requirements = unwrapped
256 .intrinsic_from_analysis(1)
257 .map_err(|error| Error::from(error).with_prefix(owner))?;
258 let floor_appearance = appearance
259 .layout
260 .and_then(|request| request.instructions().fit)
261 .map(|policy| {
262 policy
263 .bounds(appearance.theme.get_font_size())
264 .and_then(|(minimum, _)| appearance.theme.clone().font_size(minimum))
265 })
266 .transpose()?;
267 let floor_requirements = if let Some(style) = &floor_appearance {
268 theme
269 .measure_text(
270 source,
271 style,
272 PhysicalTextAlignment::Start,
273 owner,
274 appearance.exact_override,
275 )?
276 .intrinsic_from_analysis(1)
277 .map_err(|error| Error::from(error).with_prefix(owner))?
278 } else {
279 requirements
280 };
281 let hard = if appearance.layout.is_some_and(|request| {
282 request
283 .instructions()
284 .visibility
285 .as_ref()
286 .is_some_and(crate::text::TextVisibility::reduces)
287 || request
288 .instructions()
289 .overflow
290 .as_ref()
291 .is_some_and(|overflow| {
292 overflow.failure != crate::text::TextFailure::Error
293 || overflow.ellipsis.is_some()
294 })
295 }) {
296 0.0
297 } else if appearance.layout.is_some_and(|request| {
298 request.instructions().wrapping == Some(crate::text::TextWrapping::NoSoftWrap)
299 }) {
300 floor_requirements.natural_width_quanta as f64 / 1024.0
301 } else {
302 floor_requirements.hard_width_quanta as f64 / 1024.0
303 };
304 let hard = appearance
305 .layout
306 .and_then(|request| request.instructions().bounds)
307 .and_then(|bounds| bounds.width)
308 .map_or(hard, |maximum| hard.min(maximum.get()));
309 let natural = requirements
310 .natural_width_quanta
311 .max(requirements.preferred_width_quanta) as f64
312 / 1024.0;
313 if let Some(orientation) = appearance
314 .layout
315 .and_then(|request| request.instructions().orientation.as_ref())
316 {
317 let project = |angle: crate::text::TextRotation| {
318 let (sine, cosine) = crate::text::orientation::components(angle.0.get());
319 (
320 hard * cosine.abs() + unwrapped.height() * sine.abs(),
321 natural * cosine.abs() + unwrapped.height() * sine.abs(),
322 )
323 };
324 return match &orientation.0 {
325 crate::text::orientation::Orientation::Fixed(angle) => Ok(project(*angle)),
326 crate::text::orientation::Orientation::Automatic(angles) => Ok(angles
327 .iter()
328 .map(|&angle| project(angle))
329 .reduce(|a, b| (a.0.min(b.0), a.1.min(b.1)))
330 .unwrap_or((0.0, natural))),
331 crate::text::orientation::Orientation::Data(from, to) => theme
332 .reference
333 .as_ref()
334 .map_or(Ok((0.0, natural)), |frame| {
335 frame.rotation(from, to, theme).map(project)
336 }),
337 };
338 }
339 Ok((hard, natural))
340}