1use std::cell::RefCell;
6
7use aylis_core::messages::{t, tf};
8use aylis_core::platform::LocaleInfo;
9use aylis_core::{Component, ComponentId, Error, PropEnum, PropInfo, PropKind, PropValue, Result, TextAlign};
10
11use crate::expr::Expr;
12use crate::mask::Mask;
13
14use crate::format::{date_time_pattern, format_date_time, format_number, parse_date_time, parse_number, plain_number, split};
15use crate::value::{Date, DateTime, Decimal, Rounding, Time, Timestamp, Value};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum FieldType {
20 #[default]
21 String,
22 Memo,
24 Integer,
25 Float,
26 Currency,
28 Boolean,
29 Date,
30 Time,
31 DateTime,
32 Blob,
33 AutoInc,
36 Timestamp,
39}
40
41impl FieldType {
42 pub const ALL: [FieldType; 12] = [
43 FieldType::String,
44 FieldType::Memo,
45 FieldType::Integer,
46 FieldType::Float,
47 FieldType::Currency,
48 FieldType::Boolean,
49 FieldType::Date,
50 FieldType::Time,
51 FieldType::DateTime,
52 FieldType::Blob,
53 FieldType::AutoInc,
54 FieldType::Timestamp,
55 ];
56
57 pub fn is_numeric(self) -> bool {
58 matches!(self, FieldType::Integer | FieldType::Float | FieldType::Currency | FieldType::AutoInc)
59 }
60}
61
62impl PropEnum for FieldType {
63 const NAMES: &'static [&'static str] =
64 &["string", "memo", "integer", "float", "currency", "boolean", "date", "time", "datetime", "blob", "auto_inc", "timestamp"];
65
66 fn from_index(index: usize) -> Option<Self> {
67 FieldType::ALL.get(index).copied()
68 }
69
70 fn index(self) -> usize {
71 self as usize
72 }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77pub enum FieldKind {
78 #[default]
80 Data,
81 Calculated,
84 Lookup,
87}
88
89impl PropEnum for FieldKind {
90 const NAMES: &'static [&'static str] = &["data", "calculated", "lookup"];
91
92 fn from_index(index: usize) -> Option<Self> {
93 [FieldKind::Data, FieldKind::Calculated, FieldKind::Lookup].get(index).copied()
94 }
95
96 fn index(self) -> usize {
97 self as usize
98 }
99}
100
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103pub enum CharCase {
104 #[default]
105 Normal,
106 Upper,
107 Lower,
108}
109
110impl PropEnum for CharCase {
111 const NAMES: &'static [&'static str] = &["normal", "upper", "lower"];
112
113 fn from_index(index: usize) -> Option<Self> {
114 [CharCase::Normal, CharCase::Upper, CharCase::Lower].get(index).copied()
115 }
116
117 fn index(self) -> usize {
118 self as usize
119 }
120}
121
122pub type GetTextFn = dyn Fn(&Value, bool) -> String;
123pub type SetTextFn = dyn Fn(&str) -> std::result::Result<Value, String>;
124pub type ValidateFn = dyn Fn(&Value) -> std::result::Result<(), String>;
125pub type CalculateFn = dyn Fn(&dyn Fn(&str) -> Value) -> Value;
127
128pub struct Field {
134 pub field_name: String,
136 pub field_type: FieldType,
137 pub size: usize,
139 pub scale: u8,
141 pub rounding: Rounding,
145 pub display_label: String,
146 pub display_width: f32,
148 pub display_format: String,
149 pub edit_format: String,
150 pub alignment: Option<TextAlign>,
152 pub required: bool,
153 pub read_only: bool,
154 pub visible: bool,
155 pub min: Option<f64>,
156 pub max: Option<f64>,
157 pub default_value: String,
159 pub display_values: String,
161 pub char_case: CharCase,
162 pub kind: FieldKind,
163 pub expression: String,
165 pub lookup_data_set: Option<ComponentId>,
167 pub key_fields: String,
169 pub lookup_key_fields: String,
171 pub lookup_result_field: String,
173 pub edit_mask: String,
175 pub sensitive: bool,
178 parsed: RefCell<Option<std::result::Result<Expr, String>>>,
179 calculate: Option<Box<CalculateFn>>,
180 get_text: Option<Box<GetTextFn>>,
181 set_text: Option<Box<SetTextFn>>,
182 validate: Option<Box<ValidateFn>>,
183 remote_texts: RefCell<std::collections::HashMap<String, String>>,
185 pending_texts: RefCell<Vec<Value>>,
187}
188
189impl Default for Field {
190 fn default() -> Self {
191 Self {
192 field_name: String::new(),
193 field_type: FieldType::String,
194 size: 0,
195 scale: 2,
196 rounding: Rounding::HalfUp,
197 display_label: String::new(),
198 display_width: 0.0,
199 display_format: String::new(),
200 edit_format: String::new(),
201 alignment: None,
202 required: false,
203 read_only: false,
204 visible: true,
205 min: None,
206 max: None,
207 default_value: String::new(),
208 display_values: String::new(),
209 char_case: CharCase::Normal,
210 kind: FieldKind::Data,
211 expression: String::new(),
212 lookup_data_set: None,
213 key_fields: String::new(),
214 lookup_key_fields: String::new(),
215 lookup_result_field: String::new(),
216 edit_mask: String::new(),
217 sensitive: false,
218 parsed: RefCell::new(None),
219 calculate: None,
220 get_text: None,
221 set_text: None,
222 validate: None,
223 remote_texts: RefCell::default(),
224 pending_texts: RefCell::default(),
225 }
226 }
227}
228
229impl Field {
230 pub fn new(name: impl Into<String>, field_type: FieldType) -> Self {
231 Self { field_name: name.into(), field_type, ..Default::default() }
232 }
233
234 pub fn label(mut self, label: impl Into<String>) -> Self {
235 self.display_label = label.into();
236 self
237 }
238
239 pub fn size(mut self, size: usize) -> Self {
240 self.size = size;
241 self
242 }
243
244 pub fn format(mut self, display_format: impl Into<String>) -> Self {
245 self.display_format = display_format.into();
246 self
247 }
248
249 pub fn align(mut self, alignment: TextAlign) -> Self {
251 self.alignment = Some(alignment);
252 self
253 }
254
255 pub fn width(mut self, display_width: f32) -> Self {
257 self.display_width = display_width;
258 self
259 }
260
261 pub fn required(mut self) -> Self {
262 self.required = true;
263 self
264 }
265
266 pub fn read_only(mut self) -> Self {
267 self.read_only = true;
268 self
269 }
270
271 pub fn min(mut self, min: f64) -> Self {
272 self.min = Some(min);
273 self
274 }
275
276 pub fn max(mut self, max: f64) -> Self {
277 self.max = Some(max);
278 self
279 }
280
281 pub fn default_value(mut self, text: impl Into<String>) -> Self {
282 self.default_value = text.into();
283 self
284 }
285
286 pub fn display_values(mut self, values: impl Into<String>) -> Self {
287 self.display_values = values.into();
288 self
289 }
290
291 pub fn char_case(mut self, char_case: CharCase) -> Self {
292 self.char_case = char_case;
293 self
294 }
295
296 pub fn on_get_text(mut self, f: impl Fn(&Value, bool) -> String + 'static) -> Self {
299 self.get_text = Some(Box::new(f));
300 self
301 }
302
303 pub fn on_set_text(mut self, f: impl Fn(&str) -> std::result::Result<Value, String> + 'static) -> Self {
305 self.set_text = Some(Box::new(f));
306 self
307 }
308
309 pub(crate) fn has_set_text(&self) -> bool {
311 self.set_text.is_some()
312 }
313
314 pub fn on_validate(mut self, f: impl Fn(&Value) -> std::result::Result<(), String> + 'static) -> Self {
316 self.validate = Some(Box::new(f));
317 self
318 }
319
320 pub fn calculated(mut self, expression: impl Into<String>) -> Self {
323 self.kind = FieldKind::Calculated;
324 self.expression = expression.into();
325 self
326 }
327
328 pub fn on_calculate(mut self, f: impl Fn(&dyn Fn(&str) -> Value) -> Value + 'static) -> Self {
330 self.kind = FieldKind::Calculated;
331 self.calculate = Some(Box::new(f));
332 self
333 }
334
335 pub fn lookup(mut self, data_set: ComponentId, key_field: &str, lookup_key: &str, result: &str) -> Self {
338 self.kind = FieldKind::Lookup;
339 self.lookup_data_set = Some(data_set);
340 self.key_fields = key_field.into();
341 self.lookup_key_fields = lookup_key.into();
342 self.lookup_result_field = result.into();
343 self
344 }
345
346 pub fn mask(mut self, mask: impl Into<String>) -> Self {
348 self.edit_mask = mask.into();
349 self
350 }
351
352 pub fn compute(&self, get: &dyn Fn(&str) -> Option<Value>) -> Value {
354 if let Some(f) = &self.calculate {
355 return f(&|name| get(name).unwrap_or_default());
356 }
357 if self.expression.trim().is_empty() {
358 return Value::Null;
359 }
360 let mut cache = self.parsed.borrow_mut();
361 let parsed = cache.get_or_insert_with(|| Expr::parse(&self.expression));
362 match parsed {
363 Ok(expr) => expr.eval(get).ok().and_then(|v| self.coerce(v).ok()).unwrap_or_default(),
364 Err(_) => Value::Null,
365 }
366 }
367
368 pub fn expression_error(&self) -> Option<String> {
370 if self.kind != FieldKind::Calculated || self.calculate.is_some() || self.expression.trim().is_empty() {
371 return None;
372 }
373 Expr::parse(&self.expression).err()
374 }
375
376 pub fn caption(&self) -> &str {
377 if self.display_label.is_empty() { &self.field_name } else { &self.display_label }
378 }
379
380 pub fn alignment(&self) -> TextAlign {
381 self.alignment.unwrap_or(if self.field_type.is_numeric() { TextAlign::Trailing } else { TextAlign::Leading })
382 }
383
384 pub fn is_read_only(&self) -> bool {
385 self.read_only || self.field_type == FieldType::AutoInc || self.kind != FieldKind::Data
386 }
387
388 fn bool_texts(&self) -> (String, String) {
389 let default = t("Sim;Não");
390 let values = if self.display_values.is_empty() { &default } else { &self.display_values };
391 let (t, f) = values.split_once(';').unwrap_or((values, ""));
392 (t.to_string(), f.to_string())
393 }
394
395 pub(crate) fn remote_text(&self, value: &Value) -> (Option<String>, bool) {
399 let key = crate::json::value_to_json(value).to_string();
400 if let Some(text) = self.remote_texts.borrow().get(&key) {
401 return (Some(text.clone()), false);
402 }
403 let mut pending = self.pending_texts.borrow_mut();
404 let first = pending.is_empty();
405 if !pending.contains(value) {
406 pending.push(value.clone());
407 }
408 (None, first)
409 }
410
411 pub(crate) fn take_pending_texts(&self) -> Vec<Value> {
413 std::mem::take(&mut *self.pending_texts.borrow_mut())
414 }
415
416 pub(crate) fn store_texts(&self, texts: impl IntoIterator<Item = (Value, String)>) {
418 let mut cache = self.remote_texts.borrow_mut();
419 for (value, text) in texts {
420 cache.insert(crate::json::value_to_json(&value).to_string(), text);
421 }
422 }
423
424 pub fn clear_texts(&self) {
426 self.remote_texts.borrow_mut().clear();
427 }
428
429 pub fn text_of(&self, value: &Value, display: bool, locale: &LocaleInfo) -> String {
431 if let Some(f) = &self.get_text {
432 return f(value, display);
433 }
434 let format = if display || self.edit_format.is_empty() { &self.display_format } else { &self.edit_format };
435 if let (Some(mask), Value::String(s)) = (Mask::parse(&self.edit_mask), value) {
436 return mask.display(s);
437 }
438 match value {
439 Value::Null => String::new(),
440 Value::Bool(b) => {
441 let (t, f) = self.bool_texts();
442 if *b { t } else { f }
443 }
444 Value::String(s) => s.clone(),
445 Value::Int(_) | Value::Float(_) | Value::Decimal(_) => {
446 let number = match (value, self.field_type) {
447 (_, FieldType::Currency) => value.as_decimal().and_then(|d| d.round(self.scale, self.rounding)),
448 (Value::Float(f), _) => Decimal::from_f64(*f, 10).map(trim),
449 _ => value.as_decimal(),
450 };
451 let Some(number) = number else { return value.to_string() };
452 if display && !format.is_empty() {
453 format_number(number, format, locale)
454 } else if display && self.field_type == FieldType::Currency {
455 format_number(number, &format!("#,##0.{}", "0".repeat(self.scale as usize)), locale)
456 } else if !display && !self.edit_format.is_empty() {
457 format_number(number, &self.edit_format, locale)
458 } else {
459 plain_number(number, locale)
460 }
461 }
462 Value::Date(d) => format_date_time(Some(*d), None, self.pattern(format, &locale.short_date_format)),
463 Value::Time(t) => format_date_time(None, Some(*t), self.pattern(format, &locale.long_time_format)),
464 Value::DateTime(dt) => {
465 let (d, t) = split(*dt);
466 format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
467 }
468 Value::Timestamp(ts) => {
470 let (d, t) = split(ts.to_local());
471 format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
472 }
473 Value::Blob(b) => format!("({} bytes)", b.len()),
474 }
475 }
476
477 fn pattern<'a>(&self, format: &'a str, fallback: &'a str) -> &'a str {
478 if format.is_empty() { fallback } else { format }
479 }
480
481 fn to_scale(&self, value: Decimal) -> std::result::Result<Decimal, String> {
484 value.round(self.scale, self.rounding).ok_or_else(|| tf("{0}: o valor {1} não cabe", &[&self.caption(), &value.to_string()]))
485 }
486
487 pub fn parse_text(&self, text: &str, locale: &LocaleInfo) -> std::result::Result<Value, String> {
489 if let Some(f) = &self.set_text {
490 return f(text);
491 }
492 let trimmed = text.trim();
493 if trimmed.is_empty() && self.field_type != FieldType::String && self.field_type != FieldType::Memo {
494 return Ok(Value::Null);
495 }
496 let caption = self.caption();
497 if let Some(mask) = Mask::parse(&self.edit_mask) {
498 let stored = mask.stored(text);
499 if stored.is_empty() {
500 return Ok(Value::Null);
501 }
502 if !mask.is_complete(text) {
503 return Err(tf("{0} incompleto: '{1}'", &[&caption, &mask.apply(text)]));
504 }
505 return Ok(Value::String(stored));
506 }
507 match self.field_type {
508 FieldType::String | FieldType::Memo => {
509 if text.is_empty() {
510 return Ok(Value::Null);
511 }
512 Ok(Value::String(match self.char_case {
513 CharCase::Normal => text.to_string(),
514 CharCase::Upper => text.to_uppercase(),
515 CharCase::Lower => text.to_lowercase(),
516 }))
517 }
518 FieldType::Integer | FieldType::AutoInc => parse_number(trimmed, locale)
519 .filter(|d| d.rescale(0) == *d)
520 .and_then(|d| d.to_i64())
521 .map(Value::Int)
522 .ok_or_else(|| tf("'{0}' não é um número inteiro válido para {1}", &[&text, &caption])),
523 FieldType::Float => parse_number(trimmed, locale)
524 .map(|d| Value::Float(d.to_f64()))
525 .ok_or_else(|| tf("'{0}' não é um número válido para {1}", &[&text, &caption])),
526 FieldType::Currency => parse_number(trimmed, locale)
527 .ok_or_else(|| tf("'{0}' não é um valor válido para {1}", &[&text, &caption]))
528 .and_then(|d| self.to_scale(d).map(Value::Decimal)),
529 FieldType::Boolean => {
530 let (t, f) = self.bool_texts();
531 let lower = trimmed.to_lowercase();
532 if lower == t.to_lowercase() || ["true", "1", "sim", "s", "yes"].contains(&lower.as_str()) {
533 Ok(Value::Bool(true))
534 } else if lower == f.to_lowercase() || ["false", "0", "não", "nao", "n", "no"].contains(&lower.as_str()) {
535 Ok(Value::Bool(false))
536 } else {
537 Err(tf("'{0}' não é {1} nem {2}", &[&text, &t, &f]))
538 }
539 }
540 FieldType::Date => {
541 let pattern = self.pattern(&self.display_format, &locale.short_date_format);
542 parse_date_time(trimmed, pattern)
543 .and_then(|(d, _)| d)
544 .map(Value::Date)
545 .ok_or_else(|| tf("'{0}' não é uma data válida ({1})", &[&text, &pattern]))
546 }
547 FieldType::Time => {
548 let pattern = self.pattern(&self.display_format, &locale.long_time_format);
549 parse_date_time(trimmed, pattern)
550 .and_then(|(_, t)| t)
551 .or_else(|| Time::parse_iso(trimmed))
552 .map(Value::Time)
553 .ok_or_else(|| tf("'{0}' não é uma hora válida ({1})", &[&text, &pattern]))
554 }
555 FieldType::DateTime | FieldType::Timestamp => {
556 let full = date_time_pattern(locale);
557 let pattern = self.pattern(&self.display_format, &full);
558 let typed = parse_date_time(trimmed, pattern)
559 .and_then(|(d, t)| Some(DateTime::new(d?, t.unwrap_or_default())))
560 .or_else(|| {
561 let date_only = parse_date_time(trimmed, &locale.short_date_format)?.0?;
562 Some(DateTime::new(date_only, Time::default()))
563 })
564 .ok_or_else(|| tf("'{0}' não é uma data/hora válida ({1})", &[&text, &pattern]))?;
565 Ok(if self.field_type == FieldType::Timestamp { Value::Timestamp(Timestamp::from_local(typed)) } else { Value::DateTime(typed) })
567 }
568 FieldType::Blob => Err(tf("{0} não pode ser digitado", &[&caption])),
569 }
570 }
571
572 pub fn coerce(&self, value: Value) -> std::result::Result<Value, String> {
575 let wrong = |v: &Value| format!("{} não aceita valor do tipo {}", self.caption(), v.kind_name());
577 Ok(match (self.field_type, value) {
578 (FieldType::Integer | FieldType::AutoInc, Value::Int(i)) => Value::Int(i),
579 (FieldType::Float, Value::Float(f)) => Value::Float(f),
580 (_, Value::Null) => Value::Null,
581 (FieldType::String | FieldType::Memo, Value::String(s)) => Value::String(s),
582 (FieldType::Integer | FieldType::AutoInc, v) => Value::Int(v.as_i64().ok_or_else(|| wrong(&v))?),
583 (FieldType::Float, v) => Value::Float(v.as_f64().ok_or_else(|| wrong(&v))?),
584 (FieldType::Currency, v) => Value::Decimal(self.to_scale(v.as_decimal().ok_or_else(|| wrong(&v))?)?),
585 (FieldType::Boolean, Value::Bool(b)) => Value::Bool(b),
586 (FieldType::Date, v) => Value::Date(v.as_date().ok_or_else(|| wrong(&v))?),
587 (FieldType::Time, Value::Time(t)) => Value::Time(t),
588 (FieldType::DateTime, Value::DateTime(dt)) => Value::DateTime(dt),
589 (FieldType::DateTime, Value::Date(d)) => Value::DateTime(DateTime::new(d, Time::default())),
590 (FieldType::DateTime, Value::Timestamp(ts)) => Value::DateTime(ts.to_local()),
591 (FieldType::Timestamp, Value::Timestamp(ts)) => Value::Timestamp(ts),
592 (FieldType::Timestamp, Value::DateTime(dt)) => Value::Timestamp(Timestamp::from_local(dt)),
594 (FieldType::Timestamp, Value::Date(d)) => Value::Timestamp(Timestamp::from_local(DateTime::new(d, Time::default()))),
595 (FieldType::Blob, Value::Blob(b)) => Value::Blob(b),
596 (_, v) => return Err(wrong(&v)),
597 })
598 }
599
600 pub fn check(&self, value: &Value) -> std::result::Result<(), String> {
603 let caption = self.caption();
604 if let Value::String(s) = value {
605 if self.size > 0 && s.chars().count() > self.size {
606 return Err(tf("{0}: no máximo {1} caracteres", &[&caption, &self.size]));
607 }
608 }
609 if let Some(number) = value.as_f64().filter(|_| self.field_type.is_numeric()) {
610 if self.min.is_some_and(|min| number < min) {
611 return Err(tf("{0}: o mínimo é {1}", &[&caption, &self.min.unwrap_or_default()]));
612 }
613 if self.max.is_some_and(|max| number > max) {
614 return Err(tf("{0}: o máximo é {1}", &[&caption, &self.max.unwrap_or_default()]));
615 }
616 }
617 match &self.validate {
618 Some(f) => f(value),
619 None => Ok(()),
620 }
621 }
622
623 pub fn initial_value(&self, locale: &LocaleInfo) -> Value {
625 if self.default_value.is_empty() {
626 return Value::Null;
627 }
628 let v = match self.field_type {
629 FieldType::Date => Date::parse_iso(&self.default_value).map(Value::Date),
630 FieldType::Time => Time::parse_iso(&self.default_value).map(Value::Time),
631 FieldType::DateTime => DateTime::parse_iso(&self.default_value).map(Value::DateTime),
632 FieldType::Timestamp => Timestamp::parse_iso(&self.default_value).map(Value::Timestamp),
633 FieldType::Float | FieldType::Currency | FieldType::Integer => {
634 Decimal::parse(&self.default_value).map(Value::Decimal).and_then(|v| self.coerce(v).ok())
635 }
636 FieldType::Boolean => Some(Value::Bool(matches!(self.default_value.to_lowercase().as_str(), "true" | "1" | "sim"))),
637 _ => None,
638 };
639 v.or_else(|| self.parse_text(&self.default_value, locale).ok()).unwrap_or(Value::Null)
640 }
641}
642
643fn trim(d: Decimal) -> Decimal {
645 let mut d = d;
646 while d.scale() > 0 && d.mantissa() % 10 == 0 {
647 d = Decimal::new(d.mantissa() / 10, d.scale() - 1);
648 }
649 d
650}
651
652const FIELD_PROPS: &[PropInfo] = &[
653 PropInfo::new("field_name", PropKind::String, "Data"),
654 PropInfo::new("type", PropKind::Enum(FieldType::NAMES), "Data"),
655 PropInfo::new("size", PropKind::Int, "Data"),
656 PropInfo::new("scale", PropKind::Int, "Data"),
657 PropInfo::new("rounding", PropKind::Enum(Rounding::NAMES), "Data"),
658 PropInfo::new("display_label", PropKind::String, "Appearance"),
659 PropInfo::new("display_width", PropKind::Float, "Appearance"),
660 PropInfo::new("display_format", PropKind::String, "Appearance"),
661 PropInfo::new("edit_format", PropKind::String, "Appearance"),
662 PropInfo::new("alignment", PropKind::Enum(<TextAlign as PropEnum>::NAMES), "Appearance"),
663 PropInfo::new("required", PropKind::Bool, "Behavior"),
664 PropInfo::new("read_only", PropKind::Bool, "Behavior"),
665 PropInfo::new("visible", PropKind::Bool, "Behavior"),
666 PropInfo::new("min", PropKind::Float, "Behavior"),
667 PropInfo::new("max", PropKind::Float, "Behavior"),
668 PropInfo::new("default_value", PropKind::String, "Data"),
669 PropInfo::new("display_values", PropKind::String, "Appearance"),
670 PropInfo::new("char_case", PropKind::Enum(CharCase::NAMES), "Behavior"),
671 PropInfo::new("edit_mask", PropKind::String, "Behavior"),
672 PropInfo::new("sensitive", PropKind::Bool, "Behavior"),
673 PropInfo::new("kind", PropKind::Enum(FieldKind::NAMES), "Data"),
674 PropInfo::new("expression", PropKind::String, "Data"),
675 PropInfo::new("lookup_data_set", PropKind::Component, "Lookup"),
676 PropInfo::new("key_fields", PropKind::String, "Lookup"),
677 PropInfo::new("lookup_key_fields", PropKind::String, "Lookup"),
678 PropInfo::new("lookup_result_field", PropKind::String, "Lookup"),
679 PropInfo::new("on_change", PropKind::Event, "Events"),
680 PropInfo::new("on_get_text", PropKind::Event, "Events"),
683 PropInfo::new("on_set_text", PropKind::Event, "Events"),
685 PropInfo::new("on_validate", PropKind::Event, "Events"),
686];
687
688impl Component for Field {
689 fn class_name(&self) -> &'static str {
690 "Field"
691 }
692
693 fn notification(&mut self, freed: ComponentId) {
694 if self.lookup_data_set == Some(freed) {
695 self.lookup_data_set = None;
696 }
697 }
698
699 fn props(&self) -> &'static [PropInfo] {
700 FIELD_PROPS
701 }
702
703 fn get_prop(&self, name: &str) -> Option<PropValue> {
704 let opt = |v: Option<f64>| v.map_or(PropValue::Null, PropValue::Float);
705 Some(match name {
706 "field_name" => self.field_name.clone().into(),
707 "type" => PropValue::enum_value(self.field_type),
708 "size" => PropValue::Int(self.size as i64),
709 "scale" => PropValue::Int(self.scale as i64),
710 "rounding" => PropValue::enum_value(self.rounding),
711 "display_label" => self.display_label.clone().into(),
712 "display_width" => self.display_width.into(),
713 "display_format" => self.display_format.clone().into(),
714 "edit_format" => self.edit_format.clone().into(),
715 "alignment" => self.alignment.map_or(PropValue::Null, PropValue::enum_value),
716 "required" => self.required.into(),
717 "read_only" => self.read_only.into(),
718 "sensitive" => self.sensitive.into(),
719 "visible" => self.visible.into(),
720 "min" => opt(self.min),
721 "max" => opt(self.max),
722 "default_value" => self.default_value.clone().into(),
723 "display_values" => self.display_values.clone().into(),
724 "char_case" => PropValue::enum_value(self.char_case),
725 "edit_mask" => self.edit_mask.clone().into(),
726 "kind" => PropValue::enum_value(self.kind),
727 "expression" => self.expression.clone().into(),
728 "lookup_data_set" => PropValue::Component(self.lookup_data_set),
729 "key_fields" => self.key_fields.clone().into(),
730 "lookup_key_fields" => self.lookup_key_fields.clone().into(),
731 "lookup_result_field" => self.lookup_result_field.clone().into(),
732 _ => return None,
733 })
734 }
735
736 fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
737 let opt = |v: &PropValue| -> Result<Option<f64>> {
738 match v {
739 PropValue::Null => Ok(None),
740 v => v.to_f64().map(Some),
741 }
742 };
743 match name {
744 "field_name" => self.field_name = value.to_str()?.to_string(),
745 "type" => self.field_type = value.to_enum()?,
746 "size" => self.size = value.to_i64()?.max(0) as usize,
747 "scale" => self.scale = value.to_i64()?.clamp(0, 18) as u8,
748 "rounding" => self.rounding = value.to_enum()?,
749 "display_label" => self.display_label = value.to_str()?.to_string(),
750 "display_width" => self.display_width = value.to_f32()?,
751 "display_format" => self.display_format = value.to_str()?.to_string(),
752 "edit_format" => self.edit_format = value.to_str()?.to_string(),
753 "alignment" => {
754 self.alignment = match value {
755 PropValue::Null => None,
756 v => Some(v.to_enum()?),
757 }
758 }
759 "required" => self.required = value.to_bool()?,
760 "read_only" => self.read_only = value.to_bool()?,
761 "sensitive" => self.sensitive = value.to_bool()?,
762 "visible" => self.visible = value.to_bool()?,
763 "min" => self.min = opt(&value)?,
764 "max" => self.max = opt(&value)?,
765 "default_value" => self.default_value = value.to_str()?.to_string(),
766 "display_values" => self.display_values = value.to_str()?.to_string(),
767 "char_case" => self.char_case = value.to_enum()?,
768 "edit_mask" => self.edit_mask = value.to_str()?.to_string(),
769 "kind" => self.kind = value.to_enum()?,
770 "expression" => {
771 self.expression = value.to_str()?.to_string();
772 *self.parsed.borrow_mut() = None;
773 }
774 "lookup_data_set" => self.lookup_data_set = value.to_component()?,
775 "key_fields" => self.key_fields = value.to_str()?.to_string(),
776 "lookup_key_fields" => self.lookup_key_fields = value.to_str()?.to_string(),
777 "lookup_result_field" => self.lookup_result_field = value.to_str()?.to_string(),
778 _ => return Err(Error::UnknownProperty(name.to_string())),
779 }
780 Ok(())
781 }
782}