Skip to main content

alpha2_model/
error.rs

1use crate::{
2    AudioNodeRef, BusId, ClipId, CompositionId, DataSetId, EffectProblem, EffectResourceId, NodeId,
3    TrackId,
4};
5use alpha2_media::SourceId;
6use std::fmt;
7
8/// What holds the shape or layout a [`ModelError::InvalidShape`] or
9/// [`ModelError::InvalidLayout`] names.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum ShapeOwner {
12    /// A generated source's shapes or layout generator.
13    Source(SourceId),
14    /// A clip's masks.
15    Clip(ClipId),
16    /// A composition node's shapes or layout generator, or its masks.
17    Node {
18        /// The composition.
19        composition: CompositionId,
20        /// The node.
21        node: NodeId,
22    },
23}
24
25impl fmt::Display for ShapeOwner {
26    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::Source(source) => write!(formatter, "source {source}"),
29            Self::Clip(clip) => write!(formatter, "clip {clip}"),
30            Self::Node { composition, node } => {
31                write!(formatter, "composition {composition} node {node}")
32            }
33        }
34    }
35}
36
37/// What holds the value a [`ModelError::InvalidDataBinding`] names.
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub enum DataOwner {
40    /// A clip's visual, masks or audio.
41    Clip(ClipId),
42    /// A track's bus or caption track.
43    Track(TrackId),
44    /// The master bus.
45    Master,
46    /// A bus.
47    Bus(BusId),
48    /// A timeline transition's effect.
49    Transition {
50        /// Its track.
51        track: TrackId,
52        /// Its first clip.
53        from: ClipId,
54        /// Its second clip.
55        to: ClipId,
56    },
57    /// A composition node's settings.
58    Node {
59        /// The composition.
60        composition: CompositionId,
61        /// The node.
62        node: NodeId,
63    },
64    /// A generated source's tree.
65    Source(SourceId),
66}
67
68impl fmt::Display for DataOwner {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::Clip(clip) => write!(formatter, "clip {clip}"),
72            Self::Track(track) => write!(formatter, "track {track}"),
73            Self::Master => formatter.write_str("the master bus"),
74            Self::Bus(bus) => write!(formatter, "bus {bus}"),
75            Self::Transition { track, from, to } => {
76                write!(formatter, "track {track} transition {from} to {to}")
77            }
78            Self::Node { composition, node } => {
79                write!(formatter, "composition {composition} node {node}")
80            }
81            Self::Source(source) => write!(formatter, "source {source}"),
82        }
83    }
84}
85
86/// What holds the effect a [`ModelError::InvalidEffect`] names.
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub enum EffectOwner {
89    /// A composition's effect, transition, generator or group node.
90    Node {
91        /// The composition.
92        composition: CompositionId,
93        /// The node.
94        node: NodeId,
95    },
96    /// A timeline transition.
97    Transition {
98        /// Its track.
99        track: TrackId,
100        /// The clip at progress zero.
101        from: ClipId,
102        /// The clip at progress one.
103        to: ClipId,
104    },
105    /// A generated source's effect generator.
106    Source(SourceId),
107}
108
109impl fmt::Display for EffectOwner {
110    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
111        match self {
112            Self::Node { composition, node } => {
113                write!(formatter, "composition {composition} node {node}")
114            }
115            Self::Transition { track, from, to } => {
116                write!(
117                    formatter,
118                    "the transition from {from} to {to} on track {track}"
119                )
120            }
121            Self::Source(source) => write!(formatter, "source {source}"),
122        }
123    }
124}
125
126impl fmt::Display for EffectProblem {
127    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
128        match self {
129            Self::UnknownBuiltin => formatter.write_str("is not a built-in"),
130            Self::Version { expected } => write!(formatter, "needs version {expected}"),
131            Self::Kind => formatter.write_str("is used as the wrong kind"),
132            Self::UnknownParam(name) => write!(formatter, "has no parameter {name}"),
133            Self::InvalidParam(name) => {
134                write!(
135                    formatter,
136                    "has a parameter {name} of the wrong type or out of range"
137                )
138            }
139            Self::Inputs => formatter.write_str("does not get exactly its declared inputs"),
140            Self::Resources => formatter.write_str("does not get exactly its declared resources"),
141        }
142    }
143}
144
145/// A document invariant violation.
146#[derive(Clone, Debug, Eq, PartialEq)]
147#[non_exhaustive]
148pub enum ModelError {
149    /// This build cannot interpret the document version.
150    UnsupportedSchemaVersion {
151        /// Version found in the decoded document.
152        found: u32,
153    },
154    /// The project has more than [`crate::MAX_DATA_SETS`] data sets.
155    TooManyDataSets {
156        /// Data sets in the document.
157        found: usize,
158        /// Largest accepted count.
159        maximum: usize,
160    },
161    /// Two data sets share one ID.
162    DuplicateDataSetId(DataSetId),
163    /// A data set breaks a rule of its kind.
164    InvalidDataSet {
165        /// The data set.
166        data: DataSetId,
167        /// What is wrong.
168        problem: crate::DataProblem,
169    },
170    /// A data binding, correction or caption words reference is unusable where it sits.
171    InvalidDataBinding {
172        /// What holds it.
173        owner: DataOwner,
174        /// The property, like `visual.position`, `masks[0].feather`, `effect.params.radius`,
175        /// `visual.correction` or `captions.from_words`.
176        at: String,
177        /// What is wrong.
178        problem: crate::BindingProblem,
179    },
180    /// At least one ID was empty.
181    EmptyIdentifier,
182    /// Two sources share one ID.
183    DuplicateSourceId(SourceId),
184    /// Two effect resources share one ID.
185    DuplicateEffectResourceId(EffectResourceId),
186    /// Two tracks share one ID.
187    DuplicateTrackId(TrackId),
188    /// Two clips share one ID.
189    DuplicateClipId(ClipId),
190    /// A source locator was empty.
191    EmptyLocator {
192        /// Source whose locator was empty.
193        source: SourceId,
194    },
195    /// A still image source says it has audio, which no image holds.
196    AudioOnImage {
197        /// The image source.
198        source: SourceId,
199    },
200    /// A source's provider does not fit it (wrong source kind, audio, or incoherent settings),
201    /// or a generated source has one.
202    InvalidProvider {
203        /// The source.
204        source: SourceId,
205    },
206    /// A source's fingerprint is malformed, or a generated source has one.
207    InvalidFingerprint {
208        /// The source.
209        source: SourceId,
210    },
211    /// A source declares a color whose dynamic range contradicts its transfer (HDR is exactly a
212    /// PQ or HLG transfer).
213    ContradictoryColor {
214        /// The source.
215        source: SourceId,
216    },
217    /// A generated source has no valid generator, or has a locator, color metadata or audio; or
218    /// another source has a generator.
219    InvalidGenerator {
220        /// The source.
221        source: SourceId,
222    },
223    /// A shapes content tree or mask outline breaks a limit, has a value out of range, or has
224    /// keyframes that cannot interpolate.
225    InvalidShape {
226        /// What holds the shape.
227        owner: ShapeOwner,
228        /// Where the problem lies, like `items[2].items[0].path` or `masks[1].shape.size`.
229        at: String,
230        /// What is wrong there.
231        problem: crate::ShapeProblem,
232    },
233    /// A layout tree breaks a limit or structure rule, has a value out of range, or has
234    /// keyframes that cannot interpolate.
235    InvalidLayout {
236        /// What holds the layout.
237        owner: ShapeOwner,
238        /// Where in it the problem lies, like `root.children[2].padding`.
239        at: String,
240        /// What is wrong there.
241        problem: crate::LayoutProblem,
242    },
243    /// A text generator's run has a style out of range once applied, or the runs draw in more
244    /// than [`crate::MAX_TEXT_FONT_SELECTIONS`] font selections from this run on.
245    InvalidTextRunStyle {
246        /// What holds the text generator.
247        owner: ShapeOwner,
248        /// The run's position among the text's runs.
249        run: usize,
250    },
251    /// An effect resource locator was empty.
252    EmptyEffectResourceLocator {
253        /// Resource whose locator was empty.
254        resource: EffectResourceId,
255    },
256    /// A clip effect references an absent effect resource.
257    UnknownEffectResource {
258        /// Clip containing the reference.
259        clip: ClipId,
260        /// Missing resource identity.
261        resource: EffectResourceId,
262    },
263    /// A clip has an empty source or timeline range.
264    EmptyClipRange {
265        /// Clip with an empty range.
266        clip: ClipId,
267    },
268    /// A clip starts before the project or source timeline origin.
269    NegativeClipRange {
270        /// Clip with a negative range start.
271        clip: ClipId,
272    },
273    /// Two clips overlap without one transition covering their intersection.
274    OverlappingClips {
275        /// Track containing the overlap.
276        track: TrackId,
277        /// First overlapping clip.
278        first: ClipId,
279        /// Second overlapping clip.
280        second: ClipId,
281    },
282    /// A clip refers to an absent source.
283    UnknownClipSource {
284        /// Clip containing the absent source reference.
285        clip: ClipId,
286        /// Referenced source that was not in the project.
287        source: SourceId,
288    },
289    /// A source cannot be placed on the selected track kind.
290    IncompatibleClipSource {
291        /// Clip containing the incompatible reference.
292        clip: ClipId,
293        /// Track that cannot accept the source kind.
294        track: TrackId,
295        /// Source with the incompatible kind.
296        source: SourceId,
297    },
298    /// A visual clip has non-finite values, invalid opacity, or unordered keyframes.
299    InvalidVisualProperties {
300        /// Clip containing the invalid presentation data.
301        clip: ClipId,
302    },
303    /// A clip has an invalid gain, pan, fade, or audio effect parameter.
304    InvalidAudioProperties {
305        /// Clip containing the invalid audio data.
306        clip: ClipId,
307    },
308    /// A track bus has an invalid gain, pan or effect parameter, or too many sends.
309    InvalidTrackAudio {
310        /// Track containing the invalid bus data.
311        track: TrackId,
312    },
313    /// The project master bus has an invalid gain, effect, or limiter parameter.
314    InvalidMasterAudio,
315    /// A bus has an invalid gain, pan or effect parameter, or too many sends.
316    InvalidAudioBus {
317        /// Bus containing the invalid data.
318        bus: BusId,
319    },
320    /// A send has an invalid gain.
321    InvalidAudioSend {
322        /// Track or bus the send is on.
323        from: AudioNodeRef,
324        /// Bus the send names.
325        to: BusId,
326    },
327    /// An output or send names a bus the project does not have.
328    UnknownAudioBus {
329        /// Track or bus whose output or send it is.
330        from: AudioNodeRef,
331        /// The missing bus.
332        bus: BusId,
333    },
334    /// Two buses share an id.
335    DuplicateAudioBus {
336        /// The repeated id.
337        bus: BusId,
338    },
339    /// Outputs, sends and effect keys lead from a track or bus back to itself.
340    AudioRoutingCycle {
341        /// The first track or bus, in document order, on a cycle.
342        node: AudioNodeRef,
343    },
344    /// The project holds more buses than [`crate::MAX_AUDIO_BUSES`].
345    TooManyAudioBuses {
346        /// Number supplied by the document.
347        found: usize,
348        /// Largest supported count.
349        maximum: usize,
350    },
351    /// An effect's `sidechain` names a track or bus the project does not have.
352    UnknownAudioSidechain {
353        /// Track or bus whose effect it is; `None` is the master.
354        owner: Option<AudioNodeRef>,
355        /// The missing track or bus.
356        sidechain: AudioNodeRef,
357    },
358    /// A clip names an absent composition.
359    UnknownComposition {
360        /// The clip.
361        clip: ClipId,
362        /// The composition it names.
363        composition: CompositionId,
364    },
365    /// A clip's composition has a non-positive scale, reaches a composition time past
366    /// [`alpha2_time::MAX_SERIALIZED_TICKS`] before the clip ends, or is on an audio clip.
367    InvalidClipComposition {
368        /// The clip.
369        clip: ClipId,
370    },
371    /// Two compositions share one ID.
372    DuplicateCompositionId(CompositionId),
373    /// A node ID contains `/`, which is reserved for joining the IDs of inlined group and media
374    /// nodes.
375    InvalidNodeId {
376        /// The composition.
377        composition: CompositionId,
378        /// The node ID.
379        node: NodeId,
380    },
381    /// Two nodes of one composition share an ID.
382    DuplicateNodeId {
383        /// The composition.
384        composition: CompositionId,
385        /// The repeated node ID.
386        node: NodeId,
387    },
388    /// A composition has more nodes than the renderer will schedule.
389    TooManyCompositionNodes {
390        /// The composition.
391        composition: CompositionId,
392        /// Number supplied by the document.
393        found: usize,
394        /// Largest supported count.
395        maximum: usize,
396    },
397    /// A node has an invalid setting: effect identity, version, parameter or value; transform,
398    /// progress, opacity or mask out of range; too many merge layers or masks; or a bypass on a
399    /// node without inputs.
400    InvalidNode {
401        /// The composition.
402        composition: CompositionId,
403        /// The node.
404        node: NodeId,
405    },
406    /// A node input names a node its composition does not have.
407    UnknownNodeInput {
408        /// The composition.
409        composition: CompositionId,
410        /// The node whose input it is.
411        node: NodeId,
412        /// The input: `input`, `from`, `to`, `matte`, `layers[i]`, or `inputs[i]`.
413        input: String,
414        /// The node named.
415        target: NodeId,
416    },
417    /// A node depends on its own output.
418    CompositionCycle {
419        /// The composition.
420        composition: CompositionId,
421        /// A node on the cycle.
422        node: NodeId,
423    },
424    /// A composition's output names a node it does not have.
425    UnknownCompositionOutput {
426        /// The composition.
427        composition: CompositionId,
428        /// The node named.
429        node: NodeId,
430    },
431    /// A media node names an absent source or one that is not visual.
432    InvalidNodeSource {
433        /// The composition.
434        composition: CompositionId,
435        /// The node.
436        node: NodeId,
437        /// The source named.
438        source: SourceId,
439    },
440    /// A composition's group inputs are unnamed, repeated or too many, or a control names no
441    /// effect setting of its nodes or repeats one.
442    InvalidCompositionPorts {
443        /// The composition.
444        composition: CompositionId,
445    },
446    /// A group node names an absent composition.
447    UnknownGroupComposition {
448        /// The composition holding the group node.
449        composition: CompositionId,
450        /// The group node.
451        node: NodeId,
452        /// The composition it names.
453        target: CompositionId,
454    },
455    /// A time offset node reads what has no other time.
456    InvalidTimeOffset {
457        /// The composition.
458        composition: CompositionId,
459        /// The time offset node.
460        node: NodeId,
461        /// What its input reaches.
462        problem: crate::TimeOffsetProblem,
463    },
464    /// A composition uses itself through group nodes or composition sources.
465    CompositionUsesItself {
466        /// A composition on the loop.
467        composition: CompositionId,
468    },
469    /// Compositions nest, through group nodes, composition sources or time offset nodes, more
470    /// than [`crate::MAX_COMPOSITION_DEPTH`] deep.
471    CompositionNestedTooDeep {
472        /// The first such composition, in document order.
473        composition: CompositionId,
474        /// Deepest supported nesting.
475        maximum: usize,
476    },
477    /// The compositions draw more than [`crate::MAX_INLINED_NODES`] nodes, counting each group
478    /// node and composition-source media node as the nodes it draws and each time offset node
479    /// as the nodes it draws again.
480    TooManyInlinedNodes {
481        /// Largest supported count.
482        maximum: usize,
483    },
484    /// The clips at one instant draw more than [`crate::MAX_FRAME_INLINED_NODES`] composition
485    /// nodes together.
486    FrameDrawsTooManyNodes {
487        /// The first clip, in document order, starting at the first such instant.
488        clip: ClipId,
489        /// The nodes the clips at that instant draw.
490        found: u64,
491        /// Largest supported count.
492        maximum: usize,
493    },
494    /// A composition source names an absent composition, or has what only a host-supplied
495    /// source has.
496    InvalidCompositionSource {
497        /// The source.
498        source: SourceId,
499    },
500    /// An adjustment source has more than an ID and its kind: a locator, generator,
501    /// composition, color, fingerprint, provider or audio.
502    InvalidAdjustmentSource {
503        /// The source.
504        source: SourceId,
505    },
506    /// A transition from or to an adjustment clip is not `alpha2.transition.fade`.
507    InvalidAdjustmentTransition {
508        /// The track holding the transition.
509        track: TrackId,
510        /// The adjustment clip it names, its `from_clip` first.
511        clip: ClipId,
512    },
513    /// An effect, transition or generator under [`crate::BUILTIN_EFFECT_PREFIX`] that does not
514    /// match its built-in definition.
515    InvalidEffect {
516        /// Where it is used.
517        owner: Box<EffectOwner>,
518        /// The effect id.
519        id: String,
520        /// How it fails its definition.
521        problem: EffectProblem,
522    },
523    /// A node's effect references an absent effect resource.
524    UnknownNodeResource {
525        /// The composition.
526        composition: CompositionId,
527        /// The node.
528        node: NodeId,
529        /// The resource named.
530        resource: EffectResourceId,
531    },
532    /// A generated source's effect generator references an absent effect resource.
533    UnknownSourceResource {
534        /// The source.
535        source: SourceId,
536        /// The resource named.
537        resource: EffectResourceId,
538    },
539    /// A clip has more than [`crate::MAX_CLIP_MASKS`] masks, a mask with a negative or
540    /// non-finite value, or masks on an audio track.
541    InvalidClipMask {
542        /// Clip carrying the invalid mask.
543        clip: ClipId,
544    },
545    /// A caption track has no captions, has clips or transitions, or has invalid cues or style;
546    /// or another track has captions.
547    InvalidCaptions {
548        /// The track.
549        track: TrackId,
550    },
551    /// A caption cue names a style its track does not have.
552    UnknownCaptionStyle {
553        /// The track.
554        track: TrackId,
555        /// The cue's position among the track's cues.
556        cue: usize,
557        /// The style it names.
558        name: String,
559    },
560    /// A caption cue's style (its track's with the cue's patch applied), or the style of one of
561    /// its runs over it, is out of range, or its runs draw in more than
562    /// [`crate::MAX_TEXT_FONT_SELECTIONS`] font selections.
563    InvalidCaptionCueStyle {
564        /// The track.
565        track: TrackId,
566        /// The cue's position among the track's cues.
567        cue: usize,
568    },
569    /// A clip's time map cannot be played: a freeze outside the source range, or a curve
570    /// with unusable keyframes.
571    InvalidTimeMap {
572        /// The clip.
573        clip: ClipId,
574        /// What is wrong with it.
575        problem: crate::TimeMapProblem,
576    },
577    /// A looping clip makes more than [`crate::MAX_LOOP_PASSES`] passes.
578    TooManyLoopPasses {
579        /// The clip.
580        clip: ClipId,
581        /// Its passes, rounded up.
582        found: u64,
583        /// The most passes a clip makes.
584        maximum: u64,
585    },
586    /// A clip's matte names no visual clip, itself, a clip with its own matte, an adjustment
587    /// clip, or a clip in a transition; or an audio or adjustment clip has a matte.
588    InvalidMatte {
589        /// Clip whose matte is invalid.
590        clip: ClipId,
591    },
592    /// A clip outside a video track sets a frame interpolation.
593    InvalidFrameInterpolation {
594        /// Clip whose frame interpolation is invalid.
595        clip: ClipId,
596    },
597    /// A transition is not contained in two distinct visual clips on its track.
598    InvalidClipTransition {
599        /// Track containing the invalid transition.
600        track: TrackId,
601    },
602    /// Transitions active at one instant lead from clip to clip in a circle, leaving no clip to
603    /// show.
604    TransitionCycle {
605        /// Track containing the transitions.
606        track: TrackId,
607        /// An instant they are all active.
608        at: alpha2_time::MediaTime,
609    },
610    /// Two clips have more than one transition between them, in either direction.
611    DuplicateTransition {
612        /// Track containing the transitions.
613        track: TrackId,
614        /// The transition's first clip.
615        first: ClipId,
616        /// The transition's second clip.
617        second: ClipId,
618    },
619    /// A caption track derives more than [`crate::MAX_DERIVED_CUES`] cues from its words, or maps
620    /// more than [`crate::MAX_DATA_WORDS`] words through its clips.
621    TooManyDerivedCues {
622        /// The caption track.
623        track: TrackId,
624    },
625    /// A time lies past [`alpha2_time::MAX_SERIALIZED_TICKS`] either way, which no document holds.
626    UnwritableTime {
627        /// The time, in ticks.
628        ticks: i64,
629    },
630    /// The project has more than [`crate::MAX_EFFECT_RESOURCES`] effect resources.
631    TooManyEffectResources {
632        /// Number supplied by the document.
633        found: usize,
634        /// Largest supported count.
635        maximum: usize,
636    },
637    /// The project contains too many compositions.
638    TooManyCompositions {
639        /// Number supplied by the document.
640        found: usize,
641        /// Largest supported count.
642        maximum: usize,
643    },
644    /// The source table exceeds the bounded project resource budget.
645    TooManySources {
646        /// Number supplied by the document.
647        found: usize,
648        /// Largest supported count.
649        maximum: usize,
650    },
651    /// The timeline contains too many tracks.
652    TooManyTracks {
653        /// Number supplied by the document.
654        found: usize,
655        /// Largest supported count.
656        maximum: usize,
657    },
658    /// The timeline contains too many clips in total.
659    TooManyClips {
660        /// Number supplied by the document.
661        found: usize,
662        /// Largest supported count.
663        maximum: usize,
664    },
665    /// More audio effects hold state at once than [`crate::MAX_AUDIO_EFFECTS`] (see
666    /// [`crate::Project::audio_effect_load`]).
667    TooManyAudioEffects {
668        /// The most effects holding state at once.
669        found: usize,
670        /// Largest supported count.
671        maximum: usize,
672        /// The earliest timeline position, in ticks, at which `found` hold state.
673        at_ticks: i64,
674    },
675    /// The audio effects hold more than [`crate::MAX_AUDIO_DELAY_MS`] of delay at once (see
676    /// [`crate::Project::audio_effect_load`]).
677    TooMuchAudioDelay {
678        /// The most milliseconds held at once, rounded up.
679        found_ms: u64,
680        /// Largest supported total.
681        maximum_ms: u32,
682        /// The earliest timeline position, in ticks, at which `found_ms` is held.
683        at_ticks: i64,
684    },
685    /// One track contains too many clips.
686    TooManyClipsOnTrack {
687        /// Track containing the excessive clip list.
688        track: TrackId,
689        /// Number supplied by the document.
690        found: usize,
691        /// Largest supported count.
692        maximum: usize,
693    },
694    /// A caption track holds more than [`crate::MAX_CLIPS_PER_TRACK`] cues.
695    TooManyCaptionCues {
696        /// The caption track.
697        track: TrackId,
698        /// Number supplied by the document.
699        found: usize,
700        /// Largest supported count.
701        maximum: usize,
702    },
703    /// One track contains too many transitions.
704    TooManyTransitions {
705        /// Track containing the excessive transition list.
706        track: TrackId,
707        /// Number supplied by the document.
708        found: usize,
709        /// Largest supported count.
710        maximum: usize,
711    },
712    /// Width or height was zero.
713    ZeroCanvasDimension,
714    /// A canvas edge exceeds the portable GPU-independent limit.
715    CanvasDimensionTooLarge {
716        /// Supplied width.
717        width: u32,
718        /// Supplied height.
719        height: u32,
720        /// Largest supported edge.
721        maximum: u32,
722    },
723    /// The canvas area exceeds the bounded pixel budget.
724    CanvasPixelBudgetExceeded {
725        /// Supplied pixel area.
726        pixels: u64,
727        /// Largest supported pixel area.
728        maximum: u64,
729    },
730    /// A background component is non-finite or outside `0..=1`.
731    InvalidBackground,
732    /// The color pipeline's HDR peak is outside [`crate::HDR_PEAK_NITS_RANGE`].
733    InvalidColorPipeline,
734    /// A field of the project's shutter is out of range.
735    InvalidShutter(crate::ShutterProblem),
736    /// The project sample rate is outside the supported DSP interval.
737    UnsupportedSampleRate {
738        /// Supplied rate.
739        found: u32,
740        /// Smallest supported rate.
741        minimum: u32,
742        /// Largest supported rate.
743        maximum: u32,
744    },
745}
746
747/// The document object a [`ModelError`] is about, by id.
748#[derive(Clone, Copy, Debug, Eq, PartialEq)]
749#[non_exhaustive]
750pub enum ErrorSubject<'a> {
751    /// A timeline clip.
752    Clip(&'a ClipId),
753    /// A media source.
754    Source(&'a SourceId),
755    /// A track.
756    Track(&'a TrackId),
757    /// A composition.
758    Composition(&'a CompositionId),
759    /// A data set.
760    DataSet(&'a DataSetId),
761    /// An effect resource.
762    EffectResource(&'a EffectResourceId),
763    /// An audio bus.
764    Bus(&'a BusId),
765}
766
767impl ModelError {
768    /// The document object this error is about, or `None` for one about the whole project.
769    ///
770    /// An overlap names its second clip, a duplicate transition its track.
771    #[must_use]
772    #[expect(clippy::too_many_lines, reason = "one arm per subject")]
773    pub const fn subject(&self) -> Option<ErrorSubject<'_>> {
774        use ErrorSubject::{Bus, Clip, Composition, DataSet, EffectResource, Source, Track};
775        Some(match self {
776            Self::UnsupportedSchemaVersion { .. }
777            | Self::TooManyDataSets { .. }
778            | Self::EmptyIdentifier
779            | Self::InvalidMasterAudio
780            | Self::TooManyInlinedNodes { .. }
781            | Self::TooManyCompositions { .. }
782            | Self::TooManyEffectResources { .. }
783            | Self::UnwritableTime { .. }
784            | Self::TooManySources { .. }
785            | Self::TooManyTracks { .. }
786            | Self::TooManyClips { .. }
787            | Self::TooManyAudioEffects { .. }
788            | Self::TooMuchAudioDelay { .. }
789            | Self::TooManyAudioBuses { .. }
790            | Self::UnknownAudioSidechain { owner: None, .. }
791            | Self::ZeroCanvasDimension
792            | Self::CanvasDimensionTooLarge { .. }
793            | Self::CanvasPixelBudgetExceeded { .. }
794            | Self::InvalidBackground
795            | Self::InvalidColorPipeline
796            | Self::InvalidShutter(_)
797            | Self::UnsupportedSampleRate { .. } => return None,
798            Self::DuplicateDataSetId(data) | Self::InvalidDataSet { data, .. } => DataSet(data),
799            Self::InvalidDataBinding { owner, .. } => match owner {
800                DataOwner::Clip(clip) | DataOwner::Transition { from: clip, .. } => Clip(clip),
801                DataOwner::Track(track) => Track(track),
802                DataOwner::Master => return None,
803                DataOwner::Bus(bus) => Bus(bus),
804                DataOwner::Node { composition, .. } => Composition(composition),
805                DataOwner::Source(source) => Source(source),
806            },
807            Self::InvalidShape { owner, .. }
808            | Self::InvalidLayout { owner, .. }
809            | Self::InvalidTextRunStyle { owner, .. } => match owner {
810                ShapeOwner::Source(source) => Source(source),
811                ShapeOwner::Clip(clip) => Clip(clip),
812                ShapeOwner::Node { composition, .. } => Composition(composition),
813            },
814            Self::InvalidEffect { owner, .. } => match &**owner {
815                EffectOwner::Node { composition, .. } => Composition(composition),
816                EffectOwner::Transition { from, .. } => Clip(from),
817                EffectOwner::Source(source) => Source(source),
818            },
819            Self::DuplicateSourceId(source)
820            | Self::EmptyLocator { source }
821            | Self::AudioOnImage { source }
822            | Self::InvalidProvider { source }
823            | Self::InvalidFingerprint { source }
824            | Self::ContradictoryColor { source }
825            | Self::InvalidGenerator { source }
826            | Self::UnknownSourceResource { source, .. }
827            | Self::InvalidCompositionSource { source }
828            | Self::InvalidAdjustmentSource { source } => Source(source),
829            Self::DuplicateEffectResourceId(resource)
830            | Self::EmptyEffectResourceLocator { resource } => EffectResource(resource),
831            Self::InvalidAudioBus { bus } | Self::DuplicateAudioBus { bus } => Bus(bus),
832            Self::InvalidAudioSend { from: node, .. }
833            | Self::UnknownAudioBus { from: node, .. }
834            | Self::UnknownAudioSidechain {
835                owner: Some(node), ..
836            }
837            | Self::AudioRoutingCycle { node } => match node {
838                AudioNodeRef::Track(track) => Track(track),
839                AudioNodeRef::Bus(bus) => Bus(bus),
840            },
841            Self::DuplicateTrackId(track)
842            | Self::InvalidTrackAudio { track }
843            | Self::InvalidCaptions { track }
844            | Self::UnknownCaptionStyle { track, .. }
845            | Self::InvalidCaptionCueStyle { track, .. }
846            | Self::InvalidClipTransition { track }
847            | Self::TransitionCycle { track, .. }
848            | Self::DuplicateTransition { track, .. }
849            | Self::TooManyClipsOnTrack { track, .. }
850            | Self::TooManyCaptionCues { track, .. }
851            | Self::TooManyDerivedCues { track }
852            | Self::TooManyTransitions { track, .. } => Track(track),
853            Self::DuplicateClipId(clip)
854            | Self::UnknownEffectResource { clip, .. }
855            | Self::EmptyClipRange { clip }
856            | Self::NegativeClipRange { clip }
857            | Self::OverlappingClips { second: clip, .. }
858            | Self::UnknownClipSource { clip, .. }
859            | Self::IncompatibleClipSource { clip, .. }
860            | Self::InvalidVisualProperties { clip }
861            | Self::InvalidAudioProperties { clip }
862            | Self::UnknownComposition { clip, .. }
863            | Self::InvalidClipComposition { clip }
864            | Self::FrameDrawsTooManyNodes { clip, .. }
865            | Self::InvalidClipMask { clip }
866            | Self::InvalidTimeMap { clip, .. }
867            | Self::TooManyLoopPasses { clip, .. }
868            | Self::InvalidAdjustmentTransition { clip, .. }
869            | Self::InvalidMatte { clip }
870            | Self::InvalidFrameInterpolation { clip } => Clip(clip),
871            Self::DuplicateCompositionId(composition)
872            | Self::InvalidNodeId { composition, .. }
873            | Self::DuplicateNodeId { composition, .. }
874            | Self::TooManyCompositionNodes { composition, .. }
875            | Self::InvalidNode { composition, .. }
876            | Self::UnknownNodeInput { composition, .. }
877            | Self::CompositionCycle { composition, .. }
878            | Self::UnknownCompositionOutput { composition, .. }
879            | Self::InvalidNodeSource { composition, .. }
880            | Self::InvalidCompositionPorts { composition }
881            | Self::UnknownGroupComposition { composition, .. }
882            | Self::InvalidTimeOffset { composition, .. }
883            | Self::CompositionUsesItself { composition }
884            | Self::CompositionNestedTooDeep { composition, .. }
885            | Self::UnknownNodeResource { composition, .. } => Composition(composition),
886        })
887    }
888
889    /// The diagnostic code of this error, `model.` and the variant's name in snake case.
890    #[must_use]
891    pub const fn code(&self) -> &'static alpha2_diagnose::Code {
892        crate::diagnose::codes::model_error_code(self)
893    }
894}
895
896impl fmt::Display for ModelError {
897    #[allow(clippy::too_many_lines)]
898    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
899        match self {
900            Self::UnsupportedSchemaVersion { found } => {
901                write!(formatter, "unsupported schema version {found}")
902            }
903            Self::EmptyIdentifier => formatter.write_str("document contains an empty identifier"),
904            Self::DuplicateSourceId(id) => write!(formatter, "duplicate source ID {id}"),
905            Self::DuplicateEffectResourceId(id) => {
906                write!(formatter, "duplicate effect resource ID {id}")
907            }
908            Self::DuplicateTrackId(id) => write!(formatter, "duplicate track ID {id}"),
909            Self::DuplicateClipId(id) => write!(formatter, "duplicate clip ID {id}"),
910            Self::EmptyLocator { source } => {
911                write!(formatter, "source {source} has an empty locator")
912            }
913            Self::AudioOnImage { source } => {
914                write!(
915                    formatter,
916                    "source {source} is a still image and has no audio"
917                )
918            }
919            Self::InvalidGenerator { source } => {
920                write!(formatter, "source {source} has an invalid generator")
921            }
922            Self::InvalidShape { owner, at, problem } => {
923                write!(formatter, "{owner} has an invalid shape: {at} {problem}")
924            }
925            Self::InvalidLayout { owner, at, problem } => {
926                write!(formatter, "{owner} has an invalid layout: {at} {problem}")
927            }
928            Self::InvalidTextRunStyle { owner, run } => {
929                write!(
930                    formatter,
931                    "{owner} has text run {run} with a style out of range"
932                )
933            }
934            Self::ContradictoryColor { source } => write!(
935                formatter,
936                "source {source} declares a dynamic range its transfer contradicts"
937            ),
938            Self::InvalidFingerprint { source } => {
939                write!(formatter, "source {source} has an invalid fingerprint")
940            }
941            Self::InvalidProvider { source } => {
942                write!(formatter, "source {source} has an invalid provider")
943            }
944            Self::EmptyEffectResourceLocator { resource } => {
945                write!(formatter, "effect resource {resource} has an empty locator")
946            }
947            Self::UnknownEffectResource { clip, resource } => {
948                write!(
949                    formatter,
950                    "clip {clip} references unknown effect resource {resource}"
951                )
952            }
953            Self::EmptyClipRange { clip } => write!(formatter, "clip {clip} has an empty range"),
954            Self::NegativeClipRange { clip } => {
955                write!(formatter, "clip {clip} has a range before timeline origin")
956            }
957            Self::OverlappingClips {
958                track,
959                first,
960                second,
961            } => write!(
962                formatter,
963                "clips {first} and {second} overlap without a covering transition on track {track}"
964            ),
965            Self::UnknownClipSource { clip, source } => {
966                write!(formatter, "clip {clip} references unknown source {source}")
967            }
968            Self::IncompatibleClipSource {
969                clip,
970                track,
971                source,
972            } => {
973                write!(
974                    formatter,
975                    "clip {clip} cannot use source {source} on track {track}"
976                )
977            }
978            Self::InvalidVisualProperties { clip } => {
979                write!(formatter, "clip {clip} has invalid visual properties")
980            }
981            Self::InvalidAudioProperties { clip } => {
982                write!(formatter, "clip {clip} has invalid audio properties")
983            }
984            Self::InvalidTrackAudio { track } => {
985                write!(formatter, "track {track} has invalid audio bus settings")
986            }
987            Self::InvalidMasterAudio => {
988                write!(formatter, "the project master bus is invalid")
989            }
990            Self::InvalidAudioBus { bus } => {
991                write!(formatter, "bus {bus} has invalid audio bus settings")
992            }
993            Self::InvalidAudioSend { from, to } => {
994                write!(formatter, "{from} has an invalid send to bus {to}")
995            }
996            Self::UnknownAudioBus { from, bus } => {
997                write!(formatter, "{from} routes to unknown bus {bus}")
998            }
999            Self::DuplicateAudioBus { bus } => write!(formatter, "duplicate bus id {bus}"),
1000            Self::AudioRoutingCycle { node } => {
1001                write!(formatter, "{node} is on an audio routing cycle")
1002            }
1003            Self::TooManyAudioBuses { found, maximum } => {
1004                write!(
1005                    formatter,
1006                    "project has {found} audio buses; the maximum is {maximum}"
1007                )
1008            }
1009            Self::UnknownAudioSidechain {
1010                owner: Some(owner),
1011                sidechain,
1012            } => write!(formatter, "{owner} keys an effect from unknown {sidechain}"),
1013            Self::UnknownAudioSidechain {
1014                owner: None,
1015                sidechain,
1016            } => write!(
1017                formatter,
1018                "the master bus keys an effect from unknown {sidechain}"
1019            ),
1020            Self::UnknownComposition { clip, composition } => {
1021                write!(
1022                    formatter,
1023                    "clip {clip} references unknown composition {composition}"
1024                )
1025            }
1026            Self::InvalidClipComposition { clip } => {
1027                write!(
1028                    formatter,
1029                    "clip {clip} has an invalid composition reference"
1030                )
1031            }
1032            Self::DuplicateCompositionId(id) => write!(formatter, "duplicate composition ID {id}"),
1033            Self::InvalidNodeId { composition, node } => {
1034                write!(
1035                    formatter,
1036                    "composition {composition} has node ID {node}, which has a `/`"
1037                )
1038            }
1039            Self::DuplicateNodeId { composition, node } => {
1040                write!(
1041                    formatter,
1042                    "composition {composition} has duplicate node ID {node}"
1043                )
1044            }
1045            Self::TooManyCompositionNodes {
1046                composition,
1047                found,
1048                maximum,
1049            } => write!(
1050                formatter,
1051                "composition {composition} has {found} nodes; the maximum is {maximum}"
1052            ),
1053            Self::InvalidNode { composition, node } => {
1054                write!(
1055                    formatter,
1056                    "node {node} of composition {composition} has an invalid setting"
1057                )
1058            }
1059            Self::UnknownNodeInput {
1060                composition,
1061                node,
1062                input,
1063                target,
1064            } => write!(
1065                formatter,
1066                "input {input} of node {node} in composition {composition} names unknown node {target}"
1067            ),
1068            Self::CompositionCycle { composition, node } => write!(
1069                formatter,
1070                "node {node} of composition {composition} depends on its own output"
1071            ),
1072            Self::UnknownCompositionOutput { composition, node } => write!(
1073                formatter,
1074                "composition {composition} outputs unknown node {node}"
1075            ),
1076            Self::InvalidNodeSource {
1077                composition,
1078                node,
1079                source,
1080            } => write!(
1081                formatter,
1082                "node {node} of composition {composition} cannot show source {source}"
1083            ),
1084            Self::InvalidCompositionPorts { composition } => write!(
1085                formatter,
1086                "composition {composition} has invalid group inputs or controls"
1087            ),
1088            Self::UnknownGroupComposition {
1089                composition,
1090                node,
1091                target,
1092            } => write!(
1093                formatter,
1094                "group node {node} of composition {composition} names unknown composition {target}"
1095            ),
1096            Self::InvalidTimeOffset {
1097                composition,
1098                node,
1099                problem,
1100            } => write!(
1101                formatter,
1102                "time offset node {node} of composition {composition} {problem}"
1103            ),
1104            Self::CompositionUsesItself { composition } => {
1105                write!(formatter, "composition {composition} uses itself")
1106            }
1107            Self::CompositionNestedTooDeep {
1108                composition,
1109                maximum,
1110            } => write!(
1111                formatter,
1112                "composition {composition} nests compositions and time offsets more than {maximum} deep"
1113            ),
1114            Self::TooManyInlinedNodes { maximum } => write!(
1115                formatter,
1116                "compositions draw more than {maximum} nodes, counting each group and composition source as the nodes it draws and each time offset as the nodes it draws again"
1117            ),
1118            Self::FrameDrawsTooManyNodes {
1119                clip,
1120                found,
1121                maximum,
1122            } => write!(
1123                formatter,
1124                "the clips on the timeline where clip {clip} starts draw {found} composition nodes; a frame draws at most {maximum}"
1125            ),
1126            Self::InvalidCompositionSource { source } => {
1127                write!(
1128                    formatter,
1129                    "source {source} is not a valid composition source"
1130                )
1131            }
1132            Self::InvalidAdjustmentSource { source } => write!(
1133                formatter,
1134                "source {source} is not a valid adjustment source: it has only an id and its kind"
1135            ),
1136            Self::InvalidAdjustmentTransition { track, clip } => write!(
1137                formatter,
1138                "a transition on track {track} names adjustment clip {clip}, which only fades"
1139            ),
1140            Self::InvalidEffect { owner, id, problem } => {
1141                write!(formatter, "effect {id} in {owner} {problem}")
1142            }
1143            Self::UnknownNodeResource {
1144                composition,
1145                node,
1146                resource,
1147            } => write!(
1148                formatter,
1149                "node {node} of composition {composition} references unknown effect resource {resource}"
1150            ),
1151            Self::UnknownSourceResource { source, resource } => write!(
1152                formatter,
1153                "source {source} references unknown effect resource {resource}"
1154            ),
1155            Self::InvalidClipMask { clip } => write!(formatter, "clip {clip} has an invalid mask"),
1156            Self::InvalidMatte { clip } => write!(formatter, "clip {clip} has an invalid matte"),
1157            Self::InvalidFrameInterpolation { clip } => write!(
1158                formatter,
1159                "clip {clip} sets a frame interpolation outside a video track"
1160            ),
1161            Self::InvalidCaptions { track } => {
1162                write!(formatter, "track {track} has invalid captions")
1163            }
1164            Self::UnknownCaptionStyle { track, cue, name } => write!(
1165                formatter,
1166                "cue {cue} of track {track} names style {name:?}, which the track does not have"
1167            ),
1168            Self::InvalidCaptionCueStyle { track, cue } => write!(
1169                formatter,
1170                "cue {cue} of track {track} has a style out of range once its patch is applied"
1171            ),
1172            Self::InvalidTimeMap { clip, problem } => {
1173                use crate::TimeMapProblem as Problem;
1174                match problem {
1175                    Problem::FreezeOutsideSource => {
1176                        write!(formatter, "clip {clip} freezes outside its source range")
1177                    }
1178                    Problem::KeyframeCount { found } => write!(
1179                        formatter,
1180                        "the time curve of clip {clip} takes 2 to {} keyframes, not {found}",
1181                        crate::MAX_KEYFRAMES
1182                    ),
1183                    Problem::TimeOrder { keyframe } => write!(
1184                        formatter,
1185                        "keyframe {keyframe} of clip {clip}'s time curve is not after the one \
1186                         before it"
1187                    ),
1188                    Problem::OutsideSource { keyframe } => write!(
1189                        formatter,
1190                        "keyframe {keyframe} of clip {clip}'s time curve is outside its source \
1191                         range"
1192                    ),
1193                    Problem::Interpolation { keyframe } => write!(
1194                        formatter,
1195                        "keyframe {keyframe} of clip {clip}'s time curve has an invalid \
1196                         interpolation"
1197                    ),
1198                    Problem::Passes { found } => write!(
1199                        formatter,
1200                        "clip {clip}'s time curve plays {found} segments; the maximum is {}",
1201                        crate::MAX_KEYFRAMES
1202                    ),
1203                }
1204            }
1205            Self::TooManyLoopPasses {
1206                clip,
1207                found,
1208                maximum,
1209            } => write!(
1210                formatter,
1211                "clip {clip} loops {found} times; the maximum is {maximum}"
1212            ),
1213            Self::InvalidClipTransition { track } => {
1214                write!(formatter, "track {track} has an invalid clip transition")
1215            }
1216            Self::TransitionCycle { track, at } => write!(
1217                formatter,
1218                "transitions on track {track} active at {} ticks lead from clip to clip in a circle",
1219                at.ticks()
1220            ),
1221            Self::DuplicateTransition {
1222                track,
1223                first,
1224                second,
1225            } => write!(
1226                formatter,
1227                "clips {first} and {second} have more than one transition on track {track}"
1228            ),
1229            Self::TooManyDerivedCues { track } => write!(
1230                formatter,
1231                "track {track} derives more than {} caption cues or maps more than {} words",
1232                crate::MAX_DERIVED_CUES,
1233                crate::MAX_DATA_WORDS
1234            ),
1235            Self::UnwritableTime { ticks } => write!(
1236                formatter,
1237                "a time of {ticks} ticks is beyond {} either way",
1238                alpha2_time::MAX_SERIALIZED_TICKS
1239            ),
1240            Self::TooManyEffectResources { found, maximum } => write!(
1241                formatter,
1242                "project has {found} effect resources; the maximum is {maximum}"
1243            ),
1244            Self::TooManyCompositions { found, maximum } => write!(
1245                formatter,
1246                "project has {found} compositions; the maximum is {maximum}"
1247            ),
1248            Self::TooManySources { found, maximum } => {
1249                write!(
1250                    formatter,
1251                    "project has {found} sources; the maximum is {maximum}"
1252                )
1253            }
1254            Self::TooManyTracks { found, maximum } => {
1255                write!(
1256                    formatter,
1257                    "project has {found} tracks; the maximum is {maximum}"
1258                )
1259            }
1260            Self::TooManyClips { found, maximum } => {
1261                write!(
1262                    formatter,
1263                    "project has {found} clips; the maximum is {maximum}"
1264                )
1265            }
1266            Self::TooManyAudioEffects {
1267                found,
1268                maximum,
1269                at_ticks,
1270            } => write!(
1271                formatter,
1272                "project has {found} audio effects holding state at tick {at_ticks}; the maximum at once is {maximum}"
1273            ),
1274            Self::TooMuchAudioDelay {
1275                found_ms,
1276                maximum_ms,
1277                at_ticks,
1278            } => write!(
1279                formatter,
1280                "project audio effects hold {found_ms} ms of delay at tick {at_ticks}; the maximum at once is {maximum_ms} ms"
1281            ),
1282            Self::TooManyClipsOnTrack {
1283                track,
1284                found,
1285                maximum,
1286            } => write!(
1287                formatter,
1288                "track {track} has {found} clips; the maximum is {maximum}"
1289            ),
1290            Self::TooManyCaptionCues {
1291                track,
1292                found,
1293                maximum,
1294            } => write!(
1295                formatter,
1296                "track {track} has {found} caption cues; the maximum is {maximum}"
1297            ),
1298            Self::TooManyTransitions {
1299                track,
1300                found,
1301                maximum,
1302            } => write!(
1303                formatter,
1304                "track {track} has {found} transitions; the maximum is {maximum}"
1305            ),
1306            Self::ZeroCanvasDimension => formatter.write_str("canvas dimensions must be positive"),
1307            Self::CanvasDimensionTooLarge {
1308                width,
1309                height,
1310                maximum,
1311            } => write!(
1312                formatter,
1313                "canvas {width}x{height} exceeds the maximum edge {maximum}"
1314            ),
1315            Self::CanvasPixelBudgetExceeded { pixels, maximum } => write!(
1316                formatter,
1317                "canvas has {pixels} pixels; the maximum is {maximum}"
1318            ),
1319            Self::InvalidBackground => {
1320                formatter.write_str("background color components must be finite and within 0..=1")
1321            }
1322            Self::InvalidColorPipeline => {
1323                formatter.write_str("the HDR peak must be within 100..=10000 nits")
1324            }
1325            Self::InvalidShutter(problem) => problem.fmt(formatter),
1326            Self::TooManyDataSets { found, maximum } => write!(
1327                formatter,
1328                "project has {found} data sets; the maximum is {maximum}"
1329            ),
1330            Self::DuplicateDataSetId(data) => write!(formatter, "duplicate data set id {data}"),
1331            Self::InvalidDataSet { data, problem } => {
1332                write!(formatter, "data set {data} {problem}")
1333            }
1334            Self::InvalidDataBinding { owner, at, problem } => {
1335                write!(formatter, "{owner} {at} {problem}")
1336            }
1337            Self::UnsupportedSampleRate {
1338                found,
1339                minimum,
1340                maximum,
1341            } => write!(
1342                formatter,
1343                "sample rate {found} is outside {minimum}..={maximum}"
1344            ),
1345        }
1346    }
1347}
1348
1349impl std::error::Error for ModelError {}
1350
1351/// Failure while decoding a serialized project document.
1352#[derive(Debug)]
1353#[non_exhaustive]
1354pub enum ProjectLoadError {
1355    /// The JSON input exceeded the parser byte budget.
1356    TooLarge {
1357        /// Supplied UTF-8 byte length.
1358        bytes: usize,
1359        /// Largest accepted byte length.
1360        maximum: usize,
1361    },
1362    /// JSON syntax or shape was invalid.
1363    Json(serde_json::Error),
1364    /// The decoded document violated a model invariant.
1365    InvalidProject(ModelError),
1366}
1367
1368impl fmt::Display for ProjectLoadError {
1369    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1370        match self {
1371            Self::TooLarge { bytes, maximum } => {
1372                write!(
1373                    formatter,
1374                    "project JSON is {bytes} bytes; the maximum is {maximum}"
1375                )
1376            }
1377            Self::Json(error) => write!(formatter, "invalid project JSON: {error}"),
1378            Self::InvalidProject(error) => write!(formatter, "invalid project: {error}"),
1379        }
1380    }
1381}
1382
1383impl std::error::Error for ProjectLoadError {
1384    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1385        match self {
1386            Self::TooLarge { .. } => None,
1387            Self::Json(error) => Some(error),
1388            Self::InvalidProject(error) => Some(error),
1389        }
1390    }
1391}
1392
1393/// Why [`crate::Project::to_json`] wrote no document.
1394#[derive(Debug)]
1395#[non_exhaustive]
1396pub enum ProjectWriteError {
1397    /// The document would be longer than any loader accepts.
1398    TooLarge {
1399        /// Largest accepted byte length, which the document passes.
1400        maximum: usize,
1401    },
1402    /// Serialization failed.
1403    Json(serde_json::Error),
1404}
1405
1406impl fmt::Display for ProjectWriteError {
1407    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1408        match self {
1409            Self::TooLarge { maximum } => write!(
1410                formatter,
1411                "the project JSON would be longer than {maximum} bytes, the maximum a project loads with"
1412            ),
1413            Self::Json(error) => write!(formatter, "the project does not serialize: {error}"),
1414        }
1415    }
1416}
1417
1418impl std::error::Error for ProjectWriteError {
1419    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1420        match self {
1421            Self::TooLarge { .. } => None,
1422            Self::Json(error) => Some(error),
1423        }
1424    }
1425}