Skip to main content

glory_render/props/
live.rs

1//! Independent instance payloads over immutable declarations. Field patches
2//! detach metadata separately; ordinary nodes retain a single owned descriptor.
3use super::*;
4use crate::Plan;
5
6#[derive(Clone, Debug)]
7enum Storage {
8    // No shared declaration exists for a one-off Create.
9    Owned(Box<Descriptor>),
10    Planned(Instance),
11}
12
13/// Instance state contains no Style, class strings, options or semantics until
14/// that particular field changes. Every Memory owns its own mutable payload.
15#[derive(Clone, Debug)]
16struct Instance {
17    props: Props,
18    plan: Plan,
19    index: usize,
20    fields: Option<Box<Fields>>,
21}
22
23#[derive(Clone, Debug, Default)]
24struct Fields {
25    classes: Option<Vec<String>>,
26    style: Option<Box<Style>>,
27    role: Option<Option<Role>>,
28    name: Option<Option<String>>,
29    focus: Option<FocusMode>,
30    item: Option<Option<ItemPosition>>,
31    semantics: Option<Option<Box<crate::Semantics>>>,
32}
33impl Instance {
34    fn declaration(&self) -> &Descriptor {
35        &self.plan.nodes()[self.index].descriptor
36    }
37    #[inline(always)]
38    fn view(&self) -> DescriptorView<'_> {
39        let base = self.declaration();
40        let f = self.fields.as_deref();
41        DescriptorView {
42            props: &self.props,
43            classes: f.and_then(|f| f.classes.as_ref()).unwrap_or(&base.classes),
44            style: f.and_then(|f| f.style.as_deref()).unwrap_or(&base.style),
45            role: f.and_then(|f| f.role).unwrap_or(base.role),
46            name: f.and_then(|f| f.name.as_ref()).unwrap_or(&base.name),
47            focus: f.and_then(|f| f.focus).unwrap_or(base.focus),
48            item: f.and_then(|f| f.item).unwrap_or(base.item),
49            semantics: f
50                .and_then(|f| f.semantics.as_ref())
51                .unwrap_or(&base.semantics),
52            options: &base.options,
53        }
54    }
55}
56impl Storage {
57    pub(crate) fn owned(d: Descriptor) -> Self {
58        Self::Owned(Box::new(d))
59    }
60    pub(crate) fn plan(plan: &Plan, index: usize) -> Self {
61        Self::Planned(Instance {
62            props: plan.nodes()[index].descriptor.props.clone(),
63            plan: plan.clone(),
64            index,
65            fields: None,
66        })
67    }
68    #[inline]
69    pub fn view(&self) -> DescriptorView<'_> {
70        match self {
71            Self::Owned(d) => d.view(),
72            Self::Planned(i) => i.view(),
73        }
74    }
75    fn props_mut(&mut self) -> &mut Props {
76        match self {
77            Self::Owned(d) => &mut d.props,
78            Self::Planned(i) => &mut i.props,
79        }
80    }
81    pub(crate) fn field_mask(&self) -> u8 {
82        match self {
83            Self::Owned(_) => 0,
84            Self::Planned(i) => i.fields.as_ref().map_or(0, |f| {
85                u8::from(f.classes.is_some())
86                    | u8::from(f.style.is_some()) << 1
87                    | u8::from(f.role.is_some()) << 2
88                    | u8::from(f.name.is_some()) << 3
89                    | u8::from(f.focus.is_some()) << 4
90                    | u8::from(f.item.is_some()) << 5
91                    | u8::from(f.semantics.is_some()) << 6
92            }),
93        }
94    }
95    pub(crate) fn restore_fields(&mut self, mask: u8) {
96        if let Self::Planned(i) = self {
97            if let Some(f) = i.fields.as_mut() {
98                if mask & 1 == 0 {
99                    f.classes = None;
100                }
101                if mask & 2 == 0 {
102                    f.style = None;
103                }
104                if mask & 4 == 0 {
105                    f.role = None;
106                }
107                if mask & 8 == 0 {
108                    f.name = None;
109                }
110                if mask & 16 == 0 {
111                    f.focus = None;
112                }
113                if mask & 32 == 0 {
114                    f.item = None;
115                }
116                if mask & 64 == 0 {
117                    f.semantics = None;
118                }
119            }
120            if mask == 0 {
121                i.fields = None;
122            }
123        }
124    }
125    fn classes_mut(&mut self) -> &mut Vec<String> {
126        match self {
127            Self::Owned(d) => &mut d.classes,
128            Self::Planned(i) => i
129                .fields
130                .get_or_insert_with(Default::default)
131                .classes
132                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.classes.clone()),
133        }
134    }
135    fn style_mut(&mut self) -> &mut Style {
136        match self {
137            Self::Owned(d) => &mut d.style,
138            Self::Planned(i) => i
139                .fields
140                .get_or_insert_with(Default::default)
141                .style
142                .get_or_insert_with(|| Box::new(i.plan.nodes()[i.index].descriptor.style.clone()))
143                .as_mut(),
144        }
145    }
146    fn role_mut(&mut self) -> &mut Option<Role> {
147        match self {
148            Self::Owned(d) => &mut d.role,
149            Self::Planned(i) => i
150                .fields
151                .get_or_insert_with(Default::default)
152                .role
153                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.role),
154        }
155    }
156    fn name_mut(&mut self) -> &mut Option<String> {
157        match self {
158            Self::Owned(d) => &mut d.name,
159            Self::Planned(i) => i
160                .fields
161                .get_or_insert_with(Default::default)
162                .name
163                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.name.clone()),
164        }
165    }
166    fn focus_mut(&mut self) -> &mut FocusMode {
167        match self {
168            Self::Owned(d) => &mut d.focus,
169            Self::Planned(i) => i
170                .fields
171                .get_or_insert_with(Default::default)
172                .focus
173                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.focus),
174        }
175    }
176    fn item_mut(&mut self) -> &mut Option<ItemPosition> {
177        match self {
178            Self::Owned(d) => &mut d.item,
179            Self::Planned(i) => i
180                .fields
181                .get_or_insert_with(Default::default)
182                .item
183                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.item),
184        }
185    }
186    fn semantics_mut(&mut self) -> &mut Option<Box<crate::Semantics>> {
187        match self {
188            Self::Owned(d) => &mut d.semantics,
189            Self::Planned(i) => i
190                .fields
191                .get_or_insert_with(Default::default)
192                .semantics
193                .get_or_insert_with(|| i.plan.nodes()[i.index].descriptor.semantics.clone()),
194        }
195    }
196}
197
198#[derive(Clone, Debug)]
199pub struct LiveDescriptor(Storage);
200impl LiveDescriptor {
201    pub(crate) fn owned(d: Descriptor) -> Self {
202        Self(Storage::owned(d))
203    }
204    pub(crate) fn plan(plan: &Plan, index: usize) -> Self {
205        Self(Storage::plan(plan, index))
206    }
207    #[inline]
208    pub fn view(&self) -> DescriptorView<'_> {
209        self.0.view()
210    }
211    pub(crate) fn pending_external_options(&self) -> bool {
212        matches!(&self.0, Storage::Planned(instance) if instance.index == 0 && crate::choice::plan_external_options(&instance.plan))
213    }
214    pub(crate) fn field_mask(&self) -> u8 {
215        self.0.field_mask()
216    }
217    pub(crate) fn restore_fields(&mut self, mask: u8) {
218        self.0.restore_fields(mask);
219    }
220    pub(crate) fn swap_patch(&mut self, patch: &mut Patch) -> Result<(), Error> {
221        self.0.swap_patch(patch)
222    }
223    pub(crate) fn patch_live(&mut self, patch: &mut Patch) -> Result<(), Error> {
224        self.0.patch_live(patch)
225    }
226}
227impl<'a> From<&'a LiveDescriptor> for DescriptorView<'a> {
228    fn from(d: &'a LiveDescriptor) -> Self {
229        d.view()
230    }
231}
232fn exchange<T>(change: &mut Change<T>, target: &mut T, default: T) {
233    match change {
234        Change::Keep => {}
235        Change::Set(value) => std::mem::swap(value, target),
236        Change::Clear => *change = Change::Set(std::mem::replace(target, default)),
237    }
238}
239
240impl Storage {
241    /// Swap just the touched field into the inverse patch. Does not validate:
242    /// the same operation restores a previously valid descriptor on rollback.
243    pub(crate) fn swap_patch(&mut self, patch: &mut Patch) -> Result<(), Error> {
244        if matches!(
245            patch,
246            Patch::Classes(Change::Keep)
247                | Patch::Style(Change::Keep)
248                | Patch::Role(Change::Keep)
249                | Patch::Name(Change::Keep)
250                | Patch::Focus(Change::Keep)
251                | Patch::Item(Change::Keep)
252                | Patch::Semantics(Change::Keep)
253        ) {
254            return Ok(());
255        }
256        if matches!(
257            patch,
258            Patch::Classes(_)
259                | Patch::Style(_)
260                | Patch::Role(_)
261                | Patch::Name(_)
262                | Patch::Focus(_)
263                | Patch::Item(_)
264                | Patch::Semantics(_)
265        ) {
266            match patch {
267                Patch::Classes(change) => exchange(change, self.classes_mut(), Vec::new()),
268                Patch::Style(change) => match change {
269                    Change::Keep => {}
270                    Change::Set(style) => std::mem::swap(style.as_mut(), self.style_mut()),
271                    Change::Clear => {
272                        *change = Change::Set(Box::new(std::mem::take(self.style_mut())))
273                    }
274                },
275                Patch::Role(change) => exchange(change, self.role_mut(), None),
276                Patch::Name(change) => exchange(change, self.name_mut(), None),
277                Patch::Focus(change) => exchange(change, self.focus_mut(), FocusMode::default()),
278                Patch::Item(change) => exchange(change, self.item_mut(), None),
279                Patch::Semantics(change) => exchange(change, self.semantics_mut(), None),
280                _ => unreachable!(),
281            }
282            return Ok(());
283        }
284        match (patch, self.props_mut()) {
285            (Patch::Text(change), Props::Text(p)) => {
286                exchange(change, &mut p.content, String::new())
287            }
288            (Patch::TextKind(change), Props::Text(p)) => {
289                exchange(change, &mut p.kind, TextKind::default())
290            }
291            (Patch::Selectable(change), Props::Text(p)) => {
292                exchange(change, &mut p.selectable, true)
293            }
294            (Patch::Label(change), Props::File(p)) => {
295                exchange(change, &mut p.label, "Choose file".into())
296            }
297            (Patch::Enabled(change), Props::RichEditor(p)) => {
298                exchange(change, &mut p.enabled, true)
299            }
300            (Patch::RichDocument { document, revision }, Props::RichEditor(p)) => {
301                if !matches!(document, Change::Keep) {
302                    exchange(
303                        document,
304                        &mut p.document,
305                        std::rc::Rc::new(crate::RichDocument::default()),
306                    );
307                    std::mem::swap(revision, &mut p.revision);
308                }
309            }
310            (Patch::Enabled(change), Props::File(p)) => exchange(change, &mut p.enabled, true),
311            (
312                Patch::File {
313                    configuration,
314                    revision,
315                },
316                Props::File(p),
317            ) => {
318                if !matches!(configuration, Change::Keep) {
319                    match configuration {
320                        Change::Set(value) => std::mem::swap(value.as_mut(), &mut p.configuration),
321                        Change::Clear => {
322                            *configuration =
323                                Change::Set(Box::new(std::mem::take(&mut p.configuration)))
324                        }
325                        Change::Keep => {}
326                    }
327                    std::mem::swap(revision, &mut p.revision);
328                }
329            }
330            (Patch::Label(change), Props::Button(p)) => {
331                exchange(change, &mut p.label, String::new())
332            }
333            (Patch::Label(change), Props::Check(p)) => {
334                exchange(change, &mut p.label, String::new())
335            }
336            (Patch::Label(change), Props::Link(p)) => exchange(change, &mut p.label, String::new()),
337            (Patch::Enabled(change), Props::Button(p)) => exchange(change, &mut p.enabled, true),
338            (Patch::Enabled(change), Props::Check(p)) => exchange(change, &mut p.enabled, true),
339            (Patch::Enabled(change), Props::Input(p)) => exchange(change, &mut p.enabled, true),
340            (Patch::Value { value, revision }, Props::Input(p)) => {
341                if !matches!(value, Change::Keep) {
342                    exchange(value, &mut p.value, String::new());
343                    std::mem::swap(revision, &mut p.revision);
344                }
345            }
346            (Patch::Enabled(change), Props::Select(p)) => exchange(change, &mut p.enabled, true),
347            (Patch::SelectSelection { keys, revision }, Props::Select(p)) => {
348                if !matches!(keys, Change::Keep) {
349                    exchange(keys, &mut p.selection.keys, Vec::new());
350                    std::mem::swap(revision, &mut p.selection.revision);
351                }
352            }
353            (Patch::Purpose(change), Props::Input(p)) => {
354                exchange(change, &mut p.purpose, Purpose::default())
355            }
356            (Patch::Multiline(change), Props::Input(p)) => {
357                exchange(change, &mut p.multiline, false)
358            }
359            (Patch::Checked(change), Props::Check(p)) => exchange(change, &mut p.checked, false),
360            (Patch::CheckMode(change), Props::Check(p)) => {
361                exchange(change, &mut p.mode, CheckMode::default())
362            }
363            (Patch::Source { source, revision }, Props::Image(p)) => {
364                if !matches!(source, Change::Keep) {
365                    exchange(source, &mut p.source, String::new());
366                    std::mem::swap(revision, &mut p.revision);
367                }
368            }
369            (Patch::Alternative(change), Props::Image(p)) => {
370                exchange(change, &mut p.alternative, None)
371            }
372            (Patch::Graphic(change), Props::Graphic(p)) => match change {
373                Change::Keep => {}
374                Change::Set(value) => std::mem::swap(value.as_mut(), p),
375                Change::Clear => *change = Change::Set(Box::new(std::mem::take(p))),
376            },
377            (Patch::Target(change), Props::Link(p)) => {
378                exchange(change, &mut p.target, String::new())
379            }
380            _ => {
381                return Err(Error::InvalidProps(
382                    "property does not belong to this widget",
383                ));
384            }
385        }
386        Ok(())
387    }
388
389    pub(crate) fn patch_live(&mut self, inverse: &mut Patch) -> Result<(), Error> {
390        let fields_before = self.field_mask();
391        let value = matches!(inverse, Patch::Value { value, .. } if !matches!(value, Change::Keep));
392        let source =
393            matches!(inverse, Patch::Source { source, .. } if !matches!(source, Change::Keep));
394        let graphic = matches!(inverse, Patch::Graphic(change) if !matches!(change, Change::Keep));
395        let style = matches!(inverse, Patch::Style(change) if !matches!(change, Change::Keep));
396        let classes = matches!(inverse, Patch::Classes(change) if !matches!(change, Change::Keep));
397        self.swap_patch(inverse)?;
398        let result = (|| {
399            if let Patch::Semantics(Change::Set(previous)) = &inverse {
400                if let Some(next) = self
401                    .view()
402                    .semantics
403                    .as_ref()
404                    .and_then(|s| s.clipboard.as_ref())
405                {
406                    if let Some(old) = previous.as_ref().and_then(|s| s.clipboard.as_ref()) {
407                        next.validate_update(old)?
408                    } else {
409                        next.validate()?
410                    }
411                }
412                crate::swipe::revision(
413                    previous.as_ref().and_then(|s| s.swipe_capture),
414                    self.view().semantics.as_ref().and_then(|s| s.swipe_capture),
415                )?;
416                crate::presence::revision(
417                    previous.as_ref().and_then(|s| s.presence.as_deref()),
418                    self.view()
419                        .semantics
420                        .as_ref()
421                        .and_then(|s| s.presence.as_deref()),
422                )?;
423                crate::collapse::revision(
424                    previous.as_ref().and_then(|s| s.collapse.as_ref()),
425                    self.view()
426                        .semantics
427                        .as_ref()
428                        .and_then(|s| s.collapse.as_ref()),
429                )?;
430                crate::sheet::revision(
431                    previous.as_ref().and_then(|s| s.layer.as_ref()),
432                    self.view()
433                        .semantics
434                        .as_ref()
435                        .and_then(|s| s.layer.as_ref()),
436                )?;
437            }
438            if let (
439                Props::Select(select),
440                Patch::SelectSelection {
441                    keys: Change::Set(old),
442                    revision,
443                },
444            ) = (self.view().props, &inverse)
445            {
446                select.validate_selection(&select.selection.keys)?;
447                select.selection.validate_revision(*revision, old)?;
448            }
449            if let (Props::Graphic(new), Patch::Graphic(Change::Set(old))) =
450                (self.view().props, &inverse)
451            {
452                new.transition_from(old)?;
453            }
454            if let (
455                Props::File(file),
456                Patch::File {
457                    configuration: Change::Set(old),
458                    revision,
459                },
460            ) = (self.view().props, &inverse)
461            {
462                file.configuration.validate()?;
463                if file.revision < *revision
464                    || file.revision == *revision && file.configuration != **old
465                {
466                    return Err(Error::InvalidProps(
467                        "file configuration changes must advance their revision",
468                    ));
469                }
470            }
471            if let (Props::File(file), Patch::Label(_)) = (self.view().props, &inverse) {
472                file.validate_label()?;
473            }
474            if graphic && let Props::Graphic(graphic) = self.view().props {
475                graphic.validate()?;
476            }
477            if matches!(inverse, Patch::Target(change) if !matches!(change, Change::Keep))
478                && let Props::Link(link) = self.view().props
479            {
480                link.validate()?;
481            }
482            let multiline_changed = matches!((self.view().props, &inverse), (Props::Input(input), Patch::Multiline(Change::Set(old))) if input.multiline != *old);
483            if value || source || multiline_changed {
484                normalize_input(self.props_mut())?;
485            }
486            if value
487                && let (
488                    Props::Input(input),
489                    Patch::Value {
490                        value: Change::Set(old),
491                        revision,
492                    },
493                ) = (self.view().props, &inverse)
494                && (input.revision < *revision
495                    || input.revision == *revision && input.value != *old)
496            {
497                return Err(Error::InputRevision {
498                    current: *revision,
499                    incoming: input.revision,
500                });
501            }
502            if source
503                && let (
504                    Props::Image(image),
505                    Patch::Source {
506                        source: Change::Set(old),
507                        revision,
508                    },
509                ) = (self.view().props, &inverse)
510                && (image.revision < *revision
511                    || image.revision == *revision && image.source != *old)
512            {
513                return Err(Error::ImageRevision {
514                    current: *revision,
515                    incoming: image.revision,
516                });
517            }
518            if let (
519                Patch::RichDocument {
520                    document: Change::Set(previous),
521                    revision,
522                },
523                Props::RichEditor(next),
524            ) = (&*inverse, self.view().props)
525            {
526                next.document.validate()?;
527                if next.revision < *revision
528                    || next.revision == *revision && next.document != *previous
529                {
530                    return Err(Error::InputRevision {
531                        current: *revision,
532                        incoming: next.revision,
533                    });
534                }
535            }
536            self.view().validate_fields(false, style, classes)
537        })();
538        if result.is_err() {
539            // The inverse owns only built-in field values, never application
540            // callbacks/options. Restoring it cannot run validation or I/O.
541            self.swap_patch(inverse)
542                .expect("same field restores its valid descriptor");
543            self.restore_fields(fields_before);
544        }
545        result
546    }
547}
548
549impl PartialEq for LiveDescriptor {
550    fn eq(&self, other: &Self) -> bool {
551        self.view() == other.view()
552    }
553}
554impl PartialEq<Descriptor> for LiveDescriptor {
555    fn eq(&self, other: &Descriptor) -> bool {
556        self.view() == other.view()
557    }
558}
559impl PartialEq<LiveDescriptor> for Descriptor {
560    fn eq(&self, other: &LiveDescriptor) -> bool {
561        self.view() == other.view()
562    }
563}