1use std::fmt;
5
6use aylis_core::{Component, ComponentId, EventCtx, PropEnum, Ui, properties};
7
8use crate::field::FieldKind;
9use crate::store::ColumnStore;
10use crate::value::Value;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum DataSetState {
15 #[default]
16 Inactive,
17 Browse,
18 Edit,
19 Insert,
20}
21
22impl DataSetState {
23 pub fn is_editing(self) -> bool {
24 matches!(self, DataSetState::Edit | DataSetState::Insert)
25 }
26}
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum ApplyMode {
31 #[default]
33 Cached,
34 OnPost,
36}
37
38impl PropEnum for ApplyMode {
39 const NAMES: &'static [&'static str] = &["cached", "on_post"];
40
41 fn from_index(index: usize) -> Option<Self> {
42 [ApplyMode::Cached, ApplyMode::OnPost].get(index).copied()
43 }
44
45 fn index(self) -> usize {
46 self as usize
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum RowStatus {
53 Unmodified,
54 Modified,
55 Inserted,
56}
57
58#[derive(Clone, Debug, PartialEq)]
60pub struct Row {
61 pub id: u64,
63 pub(crate) data: RowData,
66 pub status: RowStatus,
67 pub original: Option<Box<Vec<Value>>>,
69 pub error: Option<Box<String>>,
71}
72
73#[derive(Clone, Debug, PartialEq)]
75pub(crate) enum RowData {
76 Stored(u32),
78 Owned(Box<Vec<Value>>),
79}
80
81#[derive(Clone, Copy)]
83pub(crate) enum Src<'a> {
84 Slice(&'a [Value]),
85 Store(&'a ColumnStore, u32),
86}
87
88impl Src<'_> {
89 pub(crate) fn get(&self, col: usize) -> Value {
90 match self {
91 Src::Slice(v) => v.get(col).cloned().unwrap_or_default(),
92 Src::Store(s, row) => s.get(*row, col),
93 }
94 }
95}
96
97pub(crate) fn src<'a>(store: &'a ColumnStore, row: &'a Row) -> Src<'a> {
99 match &row.data {
100 RowData::Stored(i) => Src::Store(store, *i),
101 RowData::Owned(v) => Src::Slice(v),
102 }
103}
104
105pub(crate) fn owned<'a>(store: &ColumnStore, row: &'a mut Row) -> &'a mut Vec<Value> {
107 if let RowData::Stored(i) = row.data {
108 row.data = RowData::Owned(Box::new(store.row(i)));
109 }
110 match &mut row.data {
111 RowData::Owned(v) => v,
112 RowData::Stored(_) => unreachable!("convertido acima"),
113 }
114}
115
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum ChangeKind {
119 Insert,
120 Update,
121 Delete,
122}
123
124impl ChangeKind {
125 pub fn name(self) -> &'static str {
126 match self {
127 ChangeKind::Insert => "insert",
128 ChangeKind::Update => "update",
129 ChangeKind::Delete => "delete",
130 }
131 }
132}
133
134#[derive(Clone, Debug, PartialEq)]
136pub struct Change {
137 pub reference: u64,
140 pub kind: ChangeKind,
141 pub data_set: String,
143 pub key: Vec<(String, Value)>,
145 pub old: Vec<(String, Value)>,
147 pub new: Vec<(String, Value)>,
149 pub master: Option<MasterLink>,
152}
153
154#[derive(Clone, Debug, PartialEq)]
156pub struct MasterLink {
157 pub data_set: String,
158 pub reference: u64,
160 pub fields: Vec<(String, String)>,
162}
163
164pub(crate) fn new_row_id() -> u64 {
167 use std::sync::atomic::{AtomicU64, Ordering};
168 static NEXT: AtomicU64 = AtomicU64::new(1);
169 NEXT.fetch_add(1, Ordering::Relaxed)
170}
171
172#[derive(Clone, Debug, Default, PartialEq)]
174pub struct ApplyResult {
175 pub reference: u64,
176 pub error: Option<String>,
178 pub values: Vec<(String, Value)>,
180}
181
182impl ApplyResult {
183 pub fn ok(reference: u64) -> Self {
184 Self { reference, ..Default::default() }
185 }
186
187 pub fn with_value(mut self, field: &str, value: impl Into<Value>) -> Self {
188 self.values.push((field.to_string(), value.into()));
189 self
190 }
191
192 pub fn error(reference: u64, message: impl Into<String>) -> Self {
193 Self { reference, error: Some(message.into()), values: Vec::new() }
194 }
195}
196
197#[derive(Clone, Debug, PartialEq, Eq)]
199pub struct DataError {
200 pub message: String,
201 pub field: Option<String>,
203 pub waiting: bool,
206}
207
208impl DataError {
209 pub fn new(message: impl Into<String>) -> Self {
210 Self { message: message.into(), field: None, waiting: false }
211 }
212
213 pub fn on_field(field: &str, message: impl Into<String>) -> Self {
214 Self { message: message.into(), field: Some(field.to_string()), waiting: false }
215 }
216
217 pub fn waiting() -> Self {
219 Self { message: "a gravação espera a resposta do backend".into(), field: None, waiting: true }
220 }
221}
222
223impl fmt::Display for DataError {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str(&self.message)
226 }
227}
228
229impl std::error::Error for DataError {}
230
231impl From<String> for DataError {
232 fn from(message: String) -> Self {
233 DataError::new(message)
234 }
235}
236
237impl From<&str> for DataError {
238 fn from(message: &str) -> Self {
239 DataError::new(message)
240 }
241}
242
243pub type DataResult<T = ()> = Result<T, DataError>;
244
245#[derive(Clone, Debug, PartialEq, Eq)]
247pub enum DataEvent {
248 ActiveChanged,
250 DataSetChanged,
252 Scrolled,
254 RecordChanged(Option<String>),
256 StateChanged,
258 UpdateData,
260}
261
262#[derive(Clone, Debug, PartialEq)]
265pub struct DataMessage {
266 pub data_set: ComponentId,
267 pub event: DataEvent,
268}
269
270pub(crate) type DataSetHook = dyn FnMut(&mut Ui, ComponentId) -> Result<(), String>;
271pub(crate) type FetchHook = dyn FnMut(&mut Ui, ComponentId, usize);
272pub(crate) type ApplyHandler = dyn FnMut(&[Change]) -> Vec<ApplyResult>;
273pub(crate) type FilterHook = dyn Fn(&dyn Fn(&str) -> Value) -> bool;
275
276#[derive(Default)]
277pub(crate) struct Hooks {
278 pub(crate) on_new_record: Option<Box<DataSetHook>>,
279 pub(crate) before_post: Option<Box<DataSetHook>>,
280 pub(crate) after_post: Option<Box<DataSetHook>>,
281 pub(crate) before_delete: Option<Box<DataSetHook>>,
282 pub(crate) after_scroll: Option<Box<DataSetHook>>,
283 pub(crate) apply: Option<Box<ApplyHandler>>,
284 pub(crate) fetch: Option<Box<FetchHook>>,
285 pub(crate) filter_record: Option<Box<FilterHook>>,
286}
287
288#[derive(Clone, Debug)]
290pub(crate) struct Column {
291 pub(crate) field: ComponentId,
292 pub(crate) name: String,
293 pub(crate) kind: FieldKind,
294}
295
296#[derive(Default)]
303pub struct ClientDataSet {
304 pub key_fields: String,
306 pub apply_mode: ApplyMode,
307 pub read_only: bool,
308 pub filter: String,
311 pub filtered: bool,
312 pub index_field_names: String,
315 pub indexes: String,
317 pub index_name: String,
320 pub params: String,
323 pub status_filter: String,
326 pub master_source: Option<ComponentId>,
328 pub master_fields: String,
331 pub apply_separately: bool,
334 pub(crate) param_values: Vec<(String, Value)>,
336 pub(crate) hidden: Vec<Row>,
338 pub(crate) needs_refilter: bool,
339 pub(crate) wants_open: bool,
342 pub(crate) columns: Vec<Column>,
343 pub(crate) column_index: std::collections::HashMap<String, usize>,
346 pub(crate) rows: Vec<Row>,
347 pub(crate) store: ColumnStore,
349 pub(crate) deleted: Vec<Row>,
350 pub(crate) cursor: usize,
351 pub(crate) bof: bool,
352 pub(crate) eof: bool,
353 pub(crate) state: DataSetState,
354 pub(crate) buffer: Option<Vec<Value>>,
355 pub(crate) insert_at: usize,
356 pub(crate) next_temp_key: i64,
357 pub(crate) disabled: u32,
358 pub(crate) pending_notify: bool,
359 pub(crate) pending_error: Option<String>,
360 pub(crate) field_errors: Vec<(String, String)>,
362 pub(crate) awaiting_text: Vec<String>,
365 pub(crate) post_deferred: bool,
367 pub(crate) asking: Option<Asking>,
370 pub(crate) answered: Option<Asking>,
371 pub(crate) applying: bool,
374 pub(crate) apply_errors: usize,
375 pub record_total: i64,
378 pub max_records: i64,
381 pub(crate) has_more: bool,
383 pub(crate) fetching: bool,
384 pub(crate) partial_notice: String,
387 pub(crate) querying: bool,
390 pub(crate) hooks: Hooks,
391}
392
393impl ClientDataSet {
394 pub fn new() -> Self {
395 Self::default()
396 }
397
398 pub fn partial_notice(&self) -> &str {
401 &self.partial_notice
402 }
403
404 pub fn with_key(mut self, key_fields: &str) -> Self {
405 self.key_fields = key_fields.to_string();
406 self
407 }
408
409 pub fn with_apply_mode(mut self, mode: ApplyMode) -> Self {
410 self.apply_mode = mode;
411 self
412 }
413
414 pub fn state(&self) -> DataSetState {
415 self.state
416 }
417
418 pub fn is_active(&self) -> bool {
419 self.state != DataSetState::Inactive
420 }
421
422 pub fn rows(&self) -> &[Row] {
423 &self.rows
424 }
425
426 pub fn deleted_rows(&self) -> &[Row] {
427 &self.deleted
428 }
429
430 pub(crate) fn column(&self, name: &str) -> Option<usize> {
431 if let Some(&i) = self.column_index.get(name) {
432 return Some(i);
433 }
434 if name.bytes().any(|b| b.is_ascii_uppercase()) {
435 if let Some(&i) = self.column_index.get(&name.to_ascii_lowercase()) {
436 return Some(i);
437 }
438 }
439 self.columns.iter().position(|c| c.name.eq_ignore_ascii_case(name))
441 }
442
443 pub(crate) fn set_columns(&mut self, columns: Vec<Column>) {
445 self.column_index = columns.iter().enumerate().rev().map(|(i, c)| (c.name.to_ascii_lowercase(), i)).collect();
446 self.columns = columns;
447 }
448
449 pub(crate) fn current(&self) -> Option<Src<'_>> {
451 match &self.buffer {
452 Some(b) => Some(Src::Slice(b)),
453 None => self.rows.get(self.cursor).map(|r| src(&self.store, r)),
454 }
455 }
456
457 pub fn row_values(&self, row: &Row) -> Vec<Value> {
460 match &row.data {
461 RowData::Stored(i) => self.store.row(*i),
462 RowData::Owned(v) => v.as_ref().clone(),
463 }
464 }
465
466 pub fn storage_bytes(&self) -> usize {
468 self.store.approx_bytes()
469 }
470
471 fn active_prop(&self) -> bool {
472 self.is_active() || self.wants_open
473 }
474
475 pub fn effective_index(&self) -> Result<String, String> {
477 if self.index_name.trim().is_empty() {
478 return Ok(self.index_field_names.clone());
479 }
480 self.index_names()
481 .into_iter()
482 .zip(self.indexes.split('|'))
483 .find(|(n, _)| n.eq_ignore_ascii_case(self.index_name.trim()))
484 .map(|(_, def)| def.split_once('=').map_or("", |(_, fields)| fields).trim().to_string())
485 .ok_or_else(|| format!("índice '{}' não existe em indexes", self.index_name.trim()))
486 }
487
488 pub fn index_names(&self) -> Vec<String> {
490 self.indexes.split('|').filter(|d| !d.trim().is_empty()).map(|d| d.split_once('=').map_or(d, |(n, _)| n).trim().to_string()).collect()
491 }
492
493 pub fn param(&self, name: &str) -> Option<Value> {
496 if let Some((_, v)) = self.param_values.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)) {
497 return Some(v.clone());
498 }
499 let (_, text) = self.params.split(';').filter_map(|p| p.split_once('=')).find(|(n, _)| n.trim().eq_ignore_ascii_case(name))?;
500 let text = text.trim();
501 Some(if let Ok(i) = text.parse::<i64>() {
502 Value::Int(i)
503 } else if let Ok(x) = text.parse::<f64>() {
504 Value::Float(x)
505 } else if text.eq_ignore_ascii_case("true") || text.eq_ignore_ascii_case("false") {
506 Value::Bool(text.eq_ignore_ascii_case("true"))
507 } else {
508 Value::String(text.to_string())
509 })
510 }
511
512 pub(crate) fn status_allowed(&self) -> Option<Vec<RowStatus>> {
514 let names: Vec<String> = self.status_filter.split(';').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect();
515 if names.is_empty() {
516 return None;
517 }
518 Some(
519 names
520 .iter()
521 .filter_map(|n| match n.as_str() {
522 "unmodified" => Some(RowStatus::Unmodified),
523 "modified" => Some(RowStatus::Modified),
524 "inserted" => Some(RowStatus::Inserted),
525 _ => None,
526 })
527 .collect(),
528 )
529 }
530}
531
532impl Component for ClientDataSet {
533 fn class_name(&self) -> &'static str {
534 "ClientDataSet"
535 }
536
537 fn props(&self) -> &'static [aylis_core::PropInfo] {
538 use aylis_core::{PropInfo, PropKind};
539 const PROPS: &[PropInfo] = &[
540 PropInfo::new("key_fields", PropKind::String, "Data"),
541 PropInfo::new("apply_mode", PropKind::Enum(ApplyMode::NAMES), "Data"),
542 PropInfo::new("read_only", PropKind::Bool, "Data"),
543 PropInfo::new("active", PropKind::Bool, "Data"),
544 PropInfo::new("filter", PropKind::String, "Data"),
545 PropInfo::new("filtered", PropKind::Bool, "Data"),
546 PropInfo::new("index_field_names", PropKind::String, "Data"),
547 PropInfo::new("indexes", PropKind::String, "Data"),
548 PropInfo::new("index_name", PropKind::String, "Data"),
549 PropInfo::new("params", PropKind::String, "Data"),
550 PropInfo::new("status_filter", PropKind::String, "Data"),
551 PropInfo::new("master_source", PropKind::Component, "Data"),
552 PropInfo::new("master_fields", PropKind::String, "Data"),
553 PropInfo::new("apply_separately", PropKind::Bool, "Data"),
554 PropInfo::new("record_total", PropKind::Int, "Data"),
555 PropInfo::new("max_records", PropKind::Int, "Data"),
556 PropInfo::new("partial_notice", PropKind::String, "Data").read_only().runtime(),
557 PropInfo::new("on_master_change", PropKind::Event, "Events"),
558 PropInfo::new("after_scroll", PropKind::Event, "Events"),
559 PropInfo::new("before_post", PropKind::Event, "Events"),
560 PropInfo::new("after_post", PropKind::Event, "Events"),
561 PropInfo::new("before_delete", PropKind::Event, "Events"),
562 PropInfo::new("on_state_change", PropKind::Event, "Events"),
563 PropInfo::new("on_apply_updates", PropKind::Event, "Events"),
564 PropInfo::new("on_reconcile_error", PropKind::Event, "Events"),
565 PropInfo::new("on_error", PropKind::Event, "Events"),
566 PropInfo::new("on_fetch", PropKind::Event, "Events"),
567 PropInfo::new("on_server_query", PropKind::Event, "Events"),
568 ];
569 PROPS
570 }
571
572 fn get_prop(&self, name: &str) -> Option<aylis_core::PropValue> {
573 use aylis_core::PropValue;
574 Some(match name {
575 "key_fields" => self.key_fields.clone().into(),
576 "apply_mode" => PropValue::enum_value(self.apply_mode),
577 "read_only" => self.read_only.into(),
578 "active" => self.active_prop().into(),
579 "filter" => self.filter.clone().into(),
580 "filtered" => self.filtered.into(),
581 "index_field_names" => self.index_field_names.clone().into(),
582 "indexes" => self.indexes.clone().into(),
583 "index_name" => self.index_name.clone().into(),
584 "params" => self.params.clone().into(),
585 "status_filter" => self.status_filter.clone().into(),
586 "master_source" => PropValue::Component(self.master_source),
587 "master_fields" => self.master_fields.clone().into(),
588 "apply_separately" => self.apply_separately.into(),
589 "record_total" => self.record_total.into(),
590 "max_records" => self.max_records.into(),
591 "partial_notice" => self.partial_notice.clone().into(),
592 _ => return None,
593 })
594 }
595
596 fn set_prop(&mut self, name: &str, value: aylis_core::PropValue) -> aylis_core::Result<()> {
597 match name {
598 "key_fields" => self.key_fields = value.to_str()?.to_string(),
599 "apply_mode" => self.apply_mode = value.to_enum()?,
600 "read_only" => self.read_only = value.to_bool()?,
601 "active" => self.wants_open = value.to_bool()?,
603 "filter" => self.filter = value.to_str()?.to_string(),
604 "filtered" => self.filtered = value.to_bool()?,
605 "index_field_names" => {
606 self.index_field_names = value.to_str()?.to_string();
607 self.index_name.clear();
608 }
609 "indexes" => self.indexes = value.to_str()?.to_string(),
610 "index_name" => self.index_name = value.to_str()?.to_string(),
611 "params" => self.params = value.to_str()?.to_string(),
612 "status_filter" => self.status_filter = value.to_str()?.to_string(),
613 "master_source" => self.master_source = value.to_component()?,
614 "master_fields" => self.master_fields = value.to_str()?.to_string(),
615 "apply_separately" => self.apply_separately = value.to_bool()?,
616 "record_total" => self.record_total = value.to_i64()?.max(0),
617 "max_records" => self.max_records = value.to_i64()?.max(0),
618 _ => return Err(aylis_core::Error::UnknownProperty(name.to_string())),
619 }
620 if REFILTER_PROPS.contains(&name) {
621 self.needs_refilter = true;
622 }
623 Ok(())
624 }
625
626 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
629 if name == "record_total" && self.is_active() {
631 let id = ctx.id;
632 ctx.ui.poster().post(move |ui| crate::handle::data_set(ui, id).notify(DataEvent::DataSetChanged));
633 }
634 if self.needs_refilter && self.is_active() && REFILTER_PROPS.contains(&name) {
635 let id = ctx.id;
636 ctx.ui.poster().post(move |ui| {
637 let _ = crate::handle::data_set(ui, id).refilter();
638 });
639 }
640 }
641
642 fn notification(&mut self, freed: ComponentId) {
643 if self.master_source == Some(freed) {
644 self.master_source = None;
645 }
646 }
647}
648
649const REFILTER_PROPS: &[&str] = &["filter", "filtered", "index_field_names", "indexes", "index_name", "params", "status_filter", "master_source", "master_fields"];
653
654pub struct DataSource {
656 pub data_set: Option<ComponentId>,
657 pub auto_edit: bool,
659 pub enabled: bool,
661}
662
663impl Default for DataSource {
664 fn default() -> Self {
665 Self { data_set: None, auto_edit: true, enabled: true }
666 }
667}
668
669impl DataSource {
670 pub fn new(data_set: ComponentId) -> Self {
671 Self { data_set: Some(data_set), ..Default::default() }
672 }
673}
674
675impl Component for DataSource {
676 fn class_name(&self) -> &'static str {
677 "DataSource"
678 }
679
680 properties! {
681 data_set: Option<ComponentId> => "Data",
682 auto_edit: bool => "Data",
683 enabled: bool => "Data";
684 events: on_data_change, on_state_change
685 }
686
687 fn notification(&mut self, freed: ComponentId) {
688 if self.data_set == Some(freed) {
689 self.data_set = None;
690 }
691 }
692}
693
694#[derive(Clone, Copy, Debug, PartialEq, Eq)]
696pub(crate) enum Asking {
697 Post,
698 Delete,
699}