tvision_rs/data.rs
1//! Typed dialog-data transfer — the value currency moved between controls and
2//! the dialog that owns them, and the open seam for third-party components.
3//!
4//! A control exposes its current value as a [`FieldValue`] via the
5//! [`value`](crate::view::View::value)/[`set_value`](crate::view::View::set_value)
6//! pair on the [`View`](crate::view::View) trait. A dialog gathers the whole
7//! record by walking its children in order
8//! ([`Group::gather_data`](crate::view::Group::gather_data) →
9//! `Vec<Option<FieldValue>>`, the positional primitive;
10//! [`Group::gather_list`](crate::view::Group::gather_list) → one ordered
11//! [`FieldValue::List`]) and distributes edited values back the same way
12//! ([`Group::scatter_data`](crate::view::Group::scatter_data) /
13//! [`Group::scatter_list`](crate::view::Group::scatter_list)).
14//!
15//! [`FieldValue`] carries the well-known shapes a control transfers
16//! ([`Text`](FieldValue::Text), [`Int`](FieldValue::Int),
17//! [`Bool`](FieldValue::Bool), [`Bits`](FieldValue::Bits) for cluster controls,
18//! [`List`](FieldValue::List) for a whole record) plus
19//! [`Custom`](FieldValue::Custom) — the open escape for payloads a user-written
20//! component invents. `Color` is deliberately NOT a `FieldValue` (it is a
21//! 4-variant enum and rides the by-value `exec_view_with` path).
22//!
23//! **Extensibility:** see the [extensibility guide](../../../apps/extensibility.html)
24//! for the three open paths and the `Custom` / [`value_as`](FieldValue::value_as)
25//! contract (runtime-checked, fail-loud, typed at the edges).
26//!
27//! **Guide:** [Dialogs & data](../../../apps/dialogs.html).
28//!
29//! # Turbo Vision heritage
30//!
31//! The original moved dialog data through an untyped getter/setter protocol over a
32//! raw record (`getData`/`setData`/`dataSize`, anonymous `void*`). tvision-rs replaces
33//! that with this typed value currency (deviation D10); the `Custom` seam keeps the
34//! original's openness to arbitrary payloads without its loss of type safety.
35
36use std::any::Any;
37use std::fmt;
38use std::rc::Rc;
39
40/// Marker for a user-invented payload carried in [`FieldValue::Custom`].
41///
42/// Blanket-implemented for every `'static` type that is [`Debug`], so component
43/// authors implement nothing — they just put their type in a `FieldValue::custom`.
44/// `Debug` is required so a payload is inspectable (and so [`FieldValue`] keeps a
45/// derived `Debug`). The `as_any_rc` bridge lets the typed accessors downcast.
46pub trait CustomValue: Any + fmt::Debug {
47 /// Upcast `Rc<Self>` to `Rc<dyn Any>` so [`FieldValue::as_custom`] /
48 /// [`FieldValue::value_as`] can `downcast`.
49 fn as_any_rc(self: Rc<Self>) -> Rc<dyn Any>;
50}
51
52impl<T: Any + fmt::Debug> CustomValue for T {
53 fn as_any_rc(self: Rc<Self>) -> Rc<dyn Any> {
54 self
55 }
56}
57
58/// The typed unit of dialog data transfer (the D10 value currency).
59///
60/// Well-known shapes ([`Text`](FieldValue::Text)/[`Int`](FieldValue::Int)/
61/// [`Bool`](FieldValue::Bool)/[`Bits`](FieldValue::Bits)/[`List`](FieldValue::List))
62/// are fully type-checked and interoperate with framework controls and generic
63/// consumers. [`Custom`](FieldValue::Custom) is the open seam for user-invented
64/// payloads: the framework moves it opaquely and a consumer downcasts at the edge
65/// (runtime-checked; see [`value_as`](FieldValue::value_as)).
66#[derive(Clone, Debug)]
67pub enum FieldValue {
68 /// A text field's string contents, used by `InputLine::value` and
69 /// `Memo::value`. Produced during a dialog gather walk and consumed
70 /// during scatter. Replaces the raw `TMemoData` buffer that
71 /// `TMemo::getData`/`setData` filled in the original.
72 Text(String),
73 /// A numeric value — the currency for integer inputs and scrollbar positions.
74 /// Produced by numeric input controls and read by the broker when syncing a
75 /// scrollbar's current value into a scroller or list viewer.
76 Int(i32),
77 /// A single toggle control's on/off state. Contrast with [`Bits`](Self::Bits),
78 /// which carries a whole cluster's bitmask (multiple check boxes or radio
79 /// buttons packed into one `u32`).
80 Bool(bool),
81 /// A packed bit word — a cluster control's value (check boxes: a bitmask;
82 /// radio buttons: the selected index). Faithful to `TCluster::value`. NOT a
83 /// packed `Color` (`Color` is a 4-variant enum and rides the by-value path).
84 Bits(u32),
85 /// An ordered record — the typed image of C++ `getData(void *rec)`'s
86 /// offset-addressed child walk (positional, anonymous). See
87 /// [`Group::gather_list`](crate::view::Group::gather_list).
88 List(Vec<FieldValue>),
89 /// A user-invented payload, carried opaquely. Construct with
90 /// [`custom`](FieldValue::custom); read with [`value_as`](FieldValue::value_as)
91 /// (loud) or [`as_custom`](FieldValue::as_custom) (`Option`). Equality is
92 /// **pointer identity** (two `Custom`s are equal iff they share the `Rc`).
93 Custom(Rc<dyn CustomValue>),
94}
95
96impl FieldValue {
97 /// Wrap a user payload as [`Custom`](FieldValue::Custom).
98 ///
99 /// Recover the payload on the read side with [`value_as`](Self::value_as)
100 /// (descriptive error on mismatch — recommended) or [`as_custom`](Self::as_custom)
101 /// (`Option`). See the [extensibility guide](../../../apps/extensibility.html)
102 /// for the full open-exchange story.
103 pub fn custom<T: Any + fmt::Debug>(v: T) -> Self {
104 FieldValue::Custom(Rc::new(v))
105 }
106
107 /// Read a [`Custom`](FieldValue::Custom) payload as `T`, or `None` if this is
108 /// not a `Custom` of type `T` (fail closed). For a descriptive error instead,
109 /// use [`value_as`](Self::value_as).
110 pub fn as_custom<T: Any>(&self) -> Option<Rc<T>> {
111 match self {
112 FieldValue::Custom(rc) => rc.clone().as_any_rc().downcast::<T>().ok(),
113 _ => None,
114 }
115 }
116
117 /// Read a [`Custom`](FieldValue::Custom) payload as `T`, **loudly**: a type
118 /// mismatch returns a descriptive [`FieldTypeError`] (so stale producer/
119 /// consumer wiring announces itself at first execution) rather than a silent
120 /// `None`. This is the recommended accessor for third-party components.
121 pub fn value_as<T: Any>(&self) -> Result<Rc<T>, FieldTypeError> {
122 match self {
123 FieldValue::Custom(rc) => {
124 rc.clone()
125 .as_any_rc()
126 .downcast::<T>()
127 .map_err(|_| FieldTypeError {
128 expected: std::any::type_name::<T>(),
129 found: "a different Custom payload type",
130 })
131 }
132 other => Err(FieldTypeError {
133 expected: std::any::type_name::<T>(),
134 found: other.variant_name(),
135 }),
136 }
137 }
138
139 /// The variant name, for diagnostics.
140 fn variant_name(&self) -> &'static str {
141 match self {
142 FieldValue::Text(_) => "Text",
143 FieldValue::Int(_) => "Int",
144 FieldValue::Bool(_) => "Bool",
145 FieldValue::Bits(_) => "Bits",
146 FieldValue::List(_) => "List",
147 FieldValue::Custom(_) => "Custom",
148 }
149 }
150}
151
152impl PartialEq for FieldValue {
153 /// Scalars and `List` compare by value; `Custom` compares by **pointer
154 /// identity** (`Rc::ptr_eq`) — the framework cannot compare opaque user
155 /// payloads by value, so two `Custom`s are equal iff they share the `Rc`.
156 fn eq(&self, other: &Self) -> bool {
157 use FieldValue::*;
158 match (self, other) {
159 (Text(a), Text(b)) => a == b,
160 (Int(a), Int(b)) => a == b,
161 (Bool(a), Bool(b)) => a == b,
162 (Bits(a), Bits(b)) => a == b,
163 (List(a), List(b)) => a == b,
164 (Custom(a), Custom(b)) => Rc::ptr_eq(a, b),
165 _ => false,
166 }
167 }
168}
169
170/// A [`FieldValue::value_as`] type mismatch — names the expected type and the
171/// found variant/payload, so a contract mismatch fails loudly.
172#[derive(Debug, Clone, PartialEq)]
173pub struct FieldTypeError {
174 /// The Rust type the caller asked for (`std::any::type_name`).
175 pub expected: &'static str,
176 /// What was actually present (a variant name, or a different `Custom` type).
177 pub found: &'static str,
178}
179
180impl fmt::Display for FieldTypeError {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 write!(
183 f,
184 "FieldValue type mismatch: expected {}, found {}",
185 self.expected, self.found
186 )
187 }
188}
189
190impl std::error::Error for FieldTypeError {}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn text_variant_round_trips() {
198 let v = FieldValue::Text("hello".to_string());
199 assert_eq!(v, FieldValue::Text("hello".to_string()));
200 assert_ne!(v, FieldValue::Text("world".to_string()));
201 let FieldValue::Text(s) = v else {
202 panic!("expected Text");
203 };
204 assert_eq!(s, "hello");
205 }
206
207 #[test]
208 fn int_variant_round_trips() {
209 let v = FieldValue::Int(42);
210 assert_eq!(v, FieldValue::Int(42));
211 assert_ne!(v, FieldValue::Int(7));
212 // Distinct from Text even when "equal-looking".
213 assert_ne!(FieldValue::Int(0), FieldValue::Text("0".to_string()));
214 let FieldValue::Int(n) = v else {
215 panic!("expected Int");
216 };
217 assert_eq!(n, 42);
218 }
219
220 #[test]
221 fn new_scalar_variants_round_trip() {
222 assert_eq!(FieldValue::Bool(true), FieldValue::Bool(true));
223 assert_ne!(FieldValue::Bool(true), FieldValue::Bool(false));
224 assert_eq!(FieldValue::Bits(0b101), FieldValue::Bits(0b101));
225 assert_eq!(
226 FieldValue::List(vec![FieldValue::Int(1), FieldValue::Text("a".into())]),
227 FieldValue::List(vec![FieldValue::Int(1), FieldValue::Text("a".into())]),
228 );
229 // Distinct kinds never compare equal.
230 assert_ne!(FieldValue::Bool(true), FieldValue::Int(1));
231 assert_ne!(FieldValue::Bits(0), FieldValue::Int(0));
232 }
233
234 #[derive(Debug, PartialEq)]
235 struct DateRange {
236 start: i32,
237 end: i32,
238 }
239
240 #[test]
241 fn custom_round_trips_via_as_custom() {
242 let fv = FieldValue::custom(DateRange { start: 1, end: 9 });
243 let got = fv
244 .as_custom::<DateRange>()
245 .expect("downcast to the stored type");
246 assert_eq!(*got, DateRange { start: 1, end: 9 });
247 // Wrong type → None (fail closed).
248 assert!(fv.as_custom::<String>().is_none());
249 }
250
251 #[test]
252 fn value_as_is_loud_on_mismatch() {
253 let fv = FieldValue::custom(DateRange { start: 1, end: 9 });
254 assert!(fv.value_as::<DateRange>().is_ok(), "matching type succeeds");
255
256 // Wrong Custom type → descriptive error, not None.
257 let err = fv.value_as::<String>().unwrap_err();
258 assert!(
259 err.expected.contains("String"),
260 "names the expected type: {err}"
261 );
262
263 // A scalar read as a Custom → error naming the found variant.
264 let scalar = FieldValue::Int(3);
265 let err = scalar.value_as::<DateRange>().unwrap_err();
266 assert_eq!(err.found, "Int", "names the found variant");
267 }
268
269 #[test]
270 fn custom_equality_is_pointer_identity() {
271 let a = FieldValue::custom(DateRange { start: 1, end: 2 });
272 let b = a.clone(); // Rc clone — same allocation
273 let c = FieldValue::custom(DateRange { start: 1, end: 2 }); // distinct allocation
274 assert_eq!(a, b, "clones share the Rc, so they are equal by identity");
275 assert_ne!(
276 a, c,
277 "distinct allocations are not equal even with equal contents"
278 );
279 }
280}