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 normalize_input(props: &mut Props) -> Result<(), Error> {
233    if let Props::Input(input) = props {
234        if !input.multiline && input.value.contains(['\r', '\n']) {
235            return Err(Error::InvalidProps(
236                "single-line input cannot contain line breaks",
237            ));
238        }
239        if let std::borrow::Cow::Owned(value) = normalize_text(&input.value, input.multiline) {
240            input.value = value;
241        }
242    }
243    if let Props::Image(image) = props
244        && let std::borrow::Cow::Owned(source) = normalize_text(&image.source, true)
245    {
246        image.source = source;
247    }
248    Ok(())
249}
250
251fn exchange<T>(change: &mut Change<T>, target: &mut T, default: T) {
252    match change {
253        Change::Keep => {}
254        Change::Set(value) => std::mem::swap(value, target),
255        Change::Clear => *change = Change::Set(std::mem::replace(target, default)),
256    }
257}
258
259impl Storage {
260    /// Swap just the touched field into the inverse patch. Does not validate:
261    /// the same operation restores a previously valid descriptor on rollback.
262    pub(crate) fn swap_patch(&mut self, patch: &mut Patch) -> Result<(), Error> {
263        if matches!(
264            patch,
265            Patch::Classes(Change::Keep)
266                | Patch::Style(Change::Keep)
267                | Patch::Role(Change::Keep)
268                | Patch::Name(Change::Keep)
269                | Patch::Focus(Change::Keep)
270                | Patch::Item(Change::Keep)
271                | Patch::Semantics(Change::Keep)
272        ) {
273            return Ok(());
274        }
275        if matches!(
276            patch,
277            Patch::Classes(_)
278                | Patch::Style(_)
279                | Patch::Role(_)
280                | Patch::Name(_)
281                | Patch::Focus(_)
282                | Patch::Item(_)
283                | Patch::Semantics(_)
284        ) {
285            match patch {
286                Patch::Classes(change) => exchange(change, self.classes_mut(), Vec::new()),
287                Patch::Style(change) => match change {
288                    Change::Keep => {}
289                    Change::Set(style) => std::mem::swap(style.as_mut(), self.style_mut()),
290                    Change::Clear => {
291                        *change = Change::Set(Box::new(std::mem::take(self.style_mut())))
292                    }
293                },
294                Patch::Role(change) => exchange(change, self.role_mut(), None),
295                Patch::Name(change) => exchange(change, self.name_mut(), None),
296                Patch::Focus(change) => exchange(change, self.focus_mut(), FocusMode::default()),
297                Patch::Item(change) => exchange(change, self.item_mut(), None),
298                Patch::Semantics(change) => exchange(change, self.semantics_mut(), None),
299                _ => unreachable!(),
300            }
301            return Ok(());
302        }
303        match (patch, self.props_mut()) {
304            (Patch::Text(change), Props::Text(p)) => {
305                exchange(change, &mut p.content, String::new())
306            }
307            (Patch::TextKind(change), Props::Text(p)) => {
308                exchange(change, &mut p.kind, TextKind::default())
309            }
310            (Patch::Selectable(change), Props::Text(p)) => {
311                exchange(change, &mut p.selectable, true)
312            }
313            (Patch::Label(change), Props::File(p)) => {
314                exchange(change, &mut p.label, "Choose file".into())
315            }
316            (Patch::Enabled(change), Props::RichEditor(p)) => {
317                exchange(change, &mut p.enabled, true)
318            }
319            (Patch::RichDocument { document, revision }, Props::RichEditor(p)) => {
320                if !matches!(document, Change::Keep) {
321                    exchange(
322                        document,
323                        &mut p.document,
324                        std::rc::Rc::new(crate::RichDocument::default()),
325                    );
326                    std::mem::swap(revision, &mut p.revision);
327                }
328            }
329            (Patch::Enabled(change), Props::File(p)) => exchange(change, &mut p.enabled, true),
330            (
331                Patch::File {
332                    configuration,
333                    revision,
334                },
335                Props::File(p),
336            ) => {
337                if !matches!(configuration, Change::Keep) {
338                    match configuration {
339                        Change::Set(value) => std::mem::swap(value.as_mut(), &mut p.configuration),
340                        Change::Clear => {
341                            *configuration =
342                                Change::Set(Box::new(std::mem::take(&mut p.configuration)))
343                        }
344                        Change::Keep => {}
345                    }
346                    std::mem::swap(revision, &mut p.revision);
347                }
348            }
349            (Patch::Label(change), Props::Button(p)) => {
350                exchange(change, &mut p.label, String::new())
351            }
352            (Patch::Label(change), Props::Check(p)) => {
353                exchange(change, &mut p.label, String::new())
354            }
355            (Patch::Label(change), Props::Link(p)) => exchange(change, &mut p.label, String::new()),
356            (Patch::Enabled(change), Props::Button(p)) => exchange(change, &mut p.enabled, true),
357            (Patch::Enabled(change), Props::Check(p)) => exchange(change, &mut p.enabled, true),
358            (Patch::Enabled(change), Props::Input(p)) => exchange(change, &mut p.enabled, true),
359            (Patch::Value { value, revision }, Props::Input(p)) => {
360                if !matches!(value, Change::Keep) {
361                    exchange(value, &mut p.value, String::new());
362                    std::mem::swap(revision, &mut p.revision);
363                }
364            }
365            (Patch::Enabled(change), Props::Select(p)) => exchange(change, &mut p.enabled, true),
366            (Patch::SelectSelection { keys, revision }, Props::Select(p)) => {
367                if !matches!(keys, Change::Keep) {
368                    exchange(keys, &mut p.selection.keys, Vec::new());
369                    std::mem::swap(revision, &mut p.selection.revision);
370                }
371            }
372            (Patch::Purpose(change), Props::Input(p)) => {
373                exchange(change, &mut p.purpose, Purpose::default())
374            }
375            (Patch::Multiline(change), Props::Input(p)) => {
376                exchange(change, &mut p.multiline, false)
377            }
378            (Patch::Checked(change), Props::Check(p)) => exchange(change, &mut p.checked, false),
379            (Patch::CheckMode(change), Props::Check(p)) => {
380                exchange(change, &mut p.mode, CheckMode::default())
381            }
382            (Patch::Source { source, revision }, Props::Image(p)) => {
383                if !matches!(source, Change::Keep) {
384                    exchange(source, &mut p.source, String::new());
385                    std::mem::swap(revision, &mut p.revision);
386                }
387            }
388            (Patch::Alternative(change), Props::Image(p)) => {
389                exchange(change, &mut p.alternative, None)
390            }
391            (Patch::Graphic(change), Props::Graphic(p)) => match change {
392                Change::Keep => {}
393                Change::Set(value) => std::mem::swap(value.as_mut(), p),
394                Change::Clear => *change = Change::Set(Box::new(std::mem::take(p))),
395            },
396            (Patch::Target(change), Props::Link(p)) => {
397                exchange(change, &mut p.target, String::new())
398            }
399            _ => {
400                return Err(Error::InvalidProps(
401                    "property does not belong to this widget",
402                ));
403            }
404        }
405        Ok(())
406    }
407
408    pub(crate) fn patch_live(&mut self, inverse: &mut Patch) -> Result<(), Error> {
409        let fields_before = self.field_mask();
410        let value = matches!(inverse, Patch::Value { value, .. } if !matches!(value, Change::Keep));
411        let source =
412            matches!(inverse, Patch::Source { source, .. } if !matches!(source, Change::Keep));
413        let graphic = matches!(inverse, Patch::Graphic(change) if !matches!(change, Change::Keep));
414        let style = matches!(inverse, Patch::Style(change) if !matches!(change, Change::Keep));
415        let classes = matches!(inverse, Patch::Classes(change) if !matches!(change, Change::Keep));
416        self.swap_patch(inverse)?;
417        let result = (|| {
418            if let Patch::Semantics(Change::Set(previous)) = &inverse {
419                if let Some(next) = self
420                    .view()
421                    .semantics
422                    .as_ref()
423                    .and_then(|s| s.clipboard.as_ref())
424                {
425                    if let Some(old) = previous.as_ref().and_then(|s| s.clipboard.as_ref()) {
426                        next.validate_update(old)?
427                    } else {
428                        next.validate()?
429                    }
430                }
431                crate::swipe::revision(
432                    previous.as_ref().and_then(|s| s.swipe_capture),
433                    self.view().semantics.as_ref().and_then(|s| s.swipe_capture),
434                )?;
435                crate::presence::revision(
436                    previous.as_ref().and_then(|s| s.presence.as_deref()),
437                    self.view()
438                        .semantics
439                        .as_ref()
440                        .and_then(|s| s.presence.as_deref()),
441                )?;
442                crate::collapse::revision(
443                    previous.as_ref().and_then(|s| s.collapse.as_ref()),
444                    self.view()
445                        .semantics
446                        .as_ref()
447                        .and_then(|s| s.collapse.as_ref()),
448                )?;
449                crate::sheet::revision(
450                    previous.as_ref().and_then(|s| s.layer.as_ref()),
451                    self.view()
452                        .semantics
453                        .as_ref()
454                        .and_then(|s| s.layer.as_ref()),
455                )?;
456            }
457            if let (
458                Props::Select(select),
459                Patch::SelectSelection {
460                    keys: Change::Set(old),
461                    revision,
462                },
463            ) = (self.view().props, &inverse)
464            {
465                select.validate_selection(&select.selection.keys)?;
466                if select.selection.revision < *revision
467                    || select.selection.revision == *revision && select.selection.keys != *old
468                {
469                    return Err(Error::SelectRevision {
470                        current: *revision,
471                        incoming: select.selection.revision,
472                    });
473                }
474            }
475            if let (Props::Graphic(new), Patch::Graphic(Change::Set(old))) =
476                (self.view().props, &inverse)
477            {
478                new.transition_from(old)?;
479            }
480            if let (
481                Props::File(file),
482                Patch::File {
483                    configuration: Change::Set(old),
484                    revision,
485                },
486            ) = (self.view().props, &inverse)
487            {
488                file.configuration.validate()?;
489                if file.revision < *revision
490                    || file.revision == *revision && file.configuration != **old
491                {
492                    return Err(Error::InvalidProps(
493                        "file configuration changes must advance their revision",
494                    ));
495                }
496            }
497            if let (Props::File(file), Patch::Label(_)) = (self.view().props, &inverse) {
498                file.validate_label()?;
499            }
500            if graphic && let Props::Graphic(graphic) = self.view().props {
501                graphic.validate()?;
502            }
503            if matches!(inverse, Patch::Target(change) if !matches!(change, Change::Keep))
504                && let Props::Link(link) = self.view().props
505            {
506                link.validate()?;
507            }
508            let multiline_changed = matches!((self.view().props, &inverse), (Props::Input(input), Patch::Multiline(Change::Set(old))) if input.multiline != *old);
509            if value || source || multiline_changed {
510                normalize_input(self.props_mut())?;
511            }
512            if value
513                && let (
514                    Props::Input(input),
515                    Patch::Value {
516                        value: Change::Set(old),
517                        revision,
518                    },
519                ) = (self.view().props, &inverse)
520                && (input.revision < *revision
521                    || input.revision == *revision && input.value != *old)
522            {
523                return Err(Error::InputRevision {
524                    current: *revision,
525                    incoming: input.revision,
526                });
527            }
528            if source
529                && let (
530                    Props::Image(image),
531                    Patch::Source {
532                        source: Change::Set(old),
533                        revision,
534                    },
535                ) = (self.view().props, &inverse)
536                && (image.revision < *revision
537                    || image.revision == *revision && image.source != *old)
538            {
539                return Err(Error::ImageRevision {
540                    current: *revision,
541                    incoming: image.revision,
542                });
543            }
544            if let (
545                Patch::RichDocument {
546                    document: Change::Set(previous),
547                    revision,
548                },
549                Props::RichEditor(next),
550            ) = (&*inverse, self.view().props)
551            {
552                next.document.validate()?;
553                if next.revision < *revision
554                    || next.revision == *revision && next.document != *previous
555                {
556                    return Err(Error::InputRevision {
557                        current: *revision,
558                        incoming: next.revision,
559                    });
560                }
561            }
562            self.view().validate_fields(false, style, classes)
563        })();
564        if result.is_err() {
565            // The inverse owns only built-in field values, never application
566            // callbacks/options. Restoring it cannot run validation or I/O.
567            self.swap_patch(inverse)
568                .expect("same field restores its valid descriptor");
569            self.restore_fields(fields_before);
570        }
571        result
572    }
573}
574
575impl PartialEq for LiveDescriptor {
576    fn eq(&self, other: &Self) -> bool {
577        self.view() == other.view()
578    }
579}
580impl PartialEq<Descriptor> for LiveDescriptor {
581    fn eq(&self, other: &Descriptor) -> bool {
582        self.view() == other.view()
583    }
584}
585impl PartialEq<LiveDescriptor> for Descriptor {
586    fn eq(&self, other: &LiveDescriptor) -> bool {
587        self.view() == other.view()
588    }
589}