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,
309 pub read_only: bool,
311 pub filter: String,
314 pub filtered: bool,
317 pub index_field_names: String,
320 pub indexes: String,
324 pub index_name: String,
327 pub params: String,
333 pub status_filter: String,
336 pub master_source: Option<ComponentId>,
338 pub master_fields: String,
342 pub apply_separately: bool,
345 pub(crate) param_values: Vec<(String, Value)>,
347 pub(crate) hidden: Vec<Row>,
349 pub(crate) needs_refilter: bool,
350 pub(crate) wants_open: bool,
353 pub(crate) columns: Vec<Column>,
354 pub(crate) column_index: std::collections::HashMap<String, usize>,
357 pub(crate) rows: Vec<Row>,
358 pub(crate) store: ColumnStore,
360 pub(crate) deleted: Vec<Row>,
361 pub(crate) cursor: usize,
362 pub(crate) bof: bool,
363 pub(crate) eof: bool,
364 pub(crate) state: DataSetState,
365 pub(crate) buffer: Option<Vec<Value>>,
366 pub(crate) insert_at: usize,
367 pub(crate) next_temp_key: i64,
368 pub(crate) disabled: u32,
369 pub(crate) pending_notify: bool,
370 pub(crate) pending_error: Option<String>,
371 pub(crate) field_errors: Vec<(String, String)>,
373 pub(crate) awaiting_text: Vec<String>,
376 pub(crate) post_deferred: bool,
378 pub(crate) asking: Option<Asking>,
381 pub(crate) answered: Option<Asking>,
382 pub(crate) applying: bool,
385 pub(crate) apply_errors: usize,
386 pub record_total: i64,
389 pub max_records: i64,
392 pub(crate) has_more: bool,
394 pub(crate) fetching: bool,
395 pub(crate) partial_notice: String,
398 pub(crate) querying: bool,
401 pub(crate) hooks: Hooks,
402}
403
404impl ClientDataSet {
405 pub fn new() -> Self {
406 Self::default()
407 }
408
409 pub fn partial_notice(&self) -> &str {
412 &self.partial_notice
413 }
414
415 pub fn with_key(mut self, key_fields: &str) -> Self {
416 self.key_fields = key_fields.to_string();
417 self
418 }
419
420 pub fn with_apply_mode(mut self, mode: ApplyMode) -> Self {
421 self.apply_mode = mode;
422 self
423 }
424
425 pub fn state(&self) -> DataSetState {
426 self.state
427 }
428
429 pub fn is_active(&self) -> bool {
430 self.state != DataSetState::Inactive
431 }
432
433 pub fn rows(&self) -> &[Row] {
434 &self.rows
435 }
436
437 pub fn deleted_rows(&self) -> &[Row] {
438 &self.deleted
439 }
440
441 pub(crate) fn column(&self, name: &str) -> Option<usize> {
442 if let Some(&i) = self.column_index.get(name) {
443 return Some(i);
444 }
445 if name.bytes().any(|b| b.is_ascii_uppercase()) {
446 if let Some(&i) = self.column_index.get(&name.to_ascii_lowercase()) {
447 return Some(i);
448 }
449 }
450 self.columns.iter().position(|c| c.name.eq_ignore_ascii_case(name))
452 }
453
454 pub(crate) fn set_columns(&mut self, columns: Vec<Column>) {
456 self.column_index = columns.iter().enumerate().rev().map(|(i, c)| (c.name.to_ascii_lowercase(), i)).collect();
457 self.columns = columns;
458 }
459
460 pub(crate) fn current(&self) -> Option<Src<'_>> {
462 match &self.buffer {
463 Some(b) => Some(Src::Slice(b)),
464 None => self.rows.get(self.cursor).map(|r| src(&self.store, r)),
465 }
466 }
467
468 pub fn row_values(&self, row: &Row) -> Vec<Value> {
471 match &row.data {
472 RowData::Stored(i) => self.store.row(*i),
473 RowData::Owned(v) => v.as_ref().clone(),
474 }
475 }
476
477 pub fn storage_bytes(&self) -> usize {
479 self.store.approx_bytes()
480 }
481
482 fn active_prop(&self) -> bool {
483 self.is_active() || self.wants_open
484 }
485
486 pub fn effective_index(&self) -> Result<String, String> {
488 if self.index_name.trim().is_empty() {
489 return Ok(self.index_field_names.clone());
490 }
491 crate::records::index_defs(&self.indexes)
492 .into_iter()
493 .find(|(n, _)| n.eq_ignore_ascii_case(self.index_name.trim()))
494 .map(|(_, fields)| fields)
495 .ok_or_else(|| format!("índice '{}' não existe em indexes", self.index_name.trim()))
496 }
497
498 pub fn index_names(&self) -> Vec<String> {
500 crate::records::index_defs(&self.indexes).into_iter().map(|(n, _)| n).collect()
501 }
502
503 pub fn param(&self, name: &str) -> Option<Value> {
506 if let Some((_, v)) = self.param_values.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)) {
507 return Some(v.clone());
508 }
509 let (_, text) = crate::records::filter_params(&self.params).into_iter().find(|(n, _)| n.eq_ignore_ascii_case(name))?;
510 let text = text.trim();
511 Some(if let Ok(i) = text.parse::<i64>() {
512 Value::Int(i)
513 } else if let Ok(x) = text.parse::<f64>() {
514 Value::Float(x)
515 } else if text.eq_ignore_ascii_case("true") || text.eq_ignore_ascii_case("false") {
516 Value::Bool(text.eq_ignore_ascii_case("true"))
517 } else {
518 Value::String(text.to_string())
519 })
520 }
521
522 pub(crate) fn status_allowed(&self) -> Option<Vec<RowStatus>> {
524 let names: Vec<String> = self.status_filter.split(';').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect();
525 if names.is_empty() {
526 return None;
527 }
528 Some(
529 names
530 .iter()
531 .filter_map(|n| match n.as_str() {
532 "unmodified" => Some(RowStatus::Unmodified),
533 "modified" => Some(RowStatus::Modified),
534 "inserted" => Some(RowStatus::Inserted),
535 _ => None,
536 })
537 .collect(),
538 )
539 }
540}
541
542impl Component for ClientDataSet {
543 fn class_name(&self) -> &'static str {
544 "ClientDataSet"
545 }
546
547 fn props(&self) -> &'static [aylis_core::PropInfo] {
548 use aylis_core::{EventArg, PropInfo, PropKind};
549 const PROPS: &[PropInfo] = &[
550 PropInfo::new("key_fields", PropKind::String, "Data"),
551 PropInfo::new("apply_mode", PropKind::Enum(ApplyMode::NAMES), "Data").rust_type("ApplyMode"),
552 PropInfo::new("read_only", PropKind::Bool, "Data"),
553 PropInfo::new("active", PropKind::Bool, "Data"),
554 PropInfo::new("filter", PropKind::String, "Data"),
555 PropInfo::new("filtered", PropKind::Bool, "Data"),
556 PropInfo::new("index_field_names", PropKind::String, "Data"),
557 PropInfo::new("indexes", PropKind::RecordList(&crate::INDEX_DEF_RECORD), "Data"),
558 PropInfo::new("index_name", PropKind::String, "Data"),
559 PropInfo::new("params", PropKind::RecordList(&crate::FILTER_PARAM_RECORD), "Data"),
560 PropInfo::new("status_filter", PropKind::String, "Data"),
561 PropInfo::new("master_source", PropKind::Component, "Data"),
562 PropInfo::new("master_fields", PropKind::RecordList(&crate::MASTER_FIELD_RECORD), "Data"),
563 PropInfo::new("apply_separately", PropKind::Bool, "Data"),
564 PropInfo::new("record_total", PropKind::Int, "Data"),
565 PropInfo::new("max_records", PropKind::Int, "Data"),
566 PropInfo::new("partial_notice", PropKind::String, "Data").read_only().runtime(),
567 PropInfo::new("on_master_change", PropKind::Event, "Events")
568 .event_arg(EventArg::Value(PropKind::Record(&crate::events::MASTER_CHANGE_RECORD)))
569 .rust_type("MasterChange"),
570 PropInfo::new("after_scroll", PropKind::Event, "Events").event_arg(EventArg::None),
571 PropInfo::new("before_post", PropKind::Event, "Events"),
572 PropInfo::new("after_post", PropKind::Event, "Events").event_arg(EventArg::None),
573 PropInfo::new("before_delete", PropKind::Event, "Events"),
574 PropInfo::new("on_state_change", PropKind::Event, "Events").event_arg(EventArg::None),
575 PropInfo::new("on_apply_updates", PropKind::Event, "Events"),
576 PropInfo::new("on_reconcile_error", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::String)),
577 PropInfo::new("on_error", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::String)),
578 PropInfo::new("on_fetch", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::Int)),
579 PropInfo::new("on_server_query", PropKind::Event, "Events")
580 .event_arg(EventArg::Value(PropKind::Record(&crate::events::SERVER_QUERY_RECORD)))
581 .rust_type("ServerQuery"),
582 ];
583 PROPS
584 }
585
586 fn get_prop(&self, name: &str) -> Option<aylis_core::PropValue> {
587 use aylis_core::PropValue;
588 Some(match name {
589 "key_fields" => self.key_fields.clone().into(),
590 "apply_mode" => PropValue::enum_value(self.apply_mode),
591 "read_only" => self.read_only.into(),
592 "active" => self.active_prop().into(),
593 "filter" => self.filter.clone().into(),
594 "filtered" => self.filtered.into(),
595 "index_field_names" => self.index_field_names.clone().into(),
596 "indexes" => self.indexes.clone().into(),
597 "index_name" => self.index_name.clone().into(),
598 "params" => self.params.clone().into(),
599 "status_filter" => self.status_filter.clone().into(),
600 "master_source" => PropValue::Component(self.master_source),
601 "master_fields" => self.master_fields.clone().into(),
602 "apply_separately" => self.apply_separately.into(),
603 "record_total" => self.record_total.into(),
604 "max_records" => self.max_records.into(),
605 "partial_notice" => self.partial_notice.clone().into(),
606 _ => return None,
607 })
608 }
609
610 fn set_prop(&mut self, name: &str, value: aylis_core::PropValue) -> aylis_core::Result<()> {
611 match name {
612 "key_fields" => self.key_fields = value.to_str()?.to_string(),
613 "apply_mode" => self.apply_mode = value.to_enum()?,
614 "read_only" => self.read_only = value.to_bool()?,
615 "active" => self.wants_open = value.to_bool()?,
617 "filter" => self.filter = value.to_str()?.to_string(),
618 "filtered" => self.filtered = value.to_bool()?,
619 "index_field_names" => {
620 self.index_field_names = value.to_str()?.to_string();
621 self.index_name.clear();
622 }
623 "indexes" => self.indexes = value.to_str()?.to_string(),
624 "index_name" => self.index_name = value.to_str()?.to_string(),
625 "params" => self.params = value.to_str()?.to_string(),
626 "status_filter" => self.status_filter = value.to_str()?.to_string(),
627 "master_source" => self.master_source = value.to_component()?,
628 "master_fields" => self.master_fields = value.to_str()?.to_string(),
629 "apply_separately" => self.apply_separately = value.to_bool()?,
630 "record_total" => self.record_total = value.to_i64()?.max(0),
631 "max_records" => self.max_records = value.to_i64()?.max(0),
632 _ => return Err(aylis_core::Error::UnknownProperty(name.to_string())),
633 }
634 if REFILTER_PROPS.contains(&name) {
635 self.needs_refilter = true;
636 }
637 Ok(())
638 }
639
640 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
643 if name == "record_total" && self.is_active() {
645 let id = ctx.id;
646 ctx.ui.poster().post(move |ui| crate::handle::data_set(ui, id).notify(DataEvent::DataSetChanged));
647 }
648 if self.needs_refilter && self.is_active() && REFILTER_PROPS.contains(&name) {
649 let id = ctx.id;
650 ctx.ui.poster().post(move |ui| {
651 let _ = crate::handle::data_set(ui, id).refilter();
652 });
653 }
654 }
655
656 fn notification(&mut self, freed: ComponentId) {
657 if self.master_source == Some(freed) {
658 self.master_source = None;
659 }
660 }
661}
662
663const REFILTER_PROPS: &[&str] = &["filter", "filtered", "index_field_names", "indexes", "index_name", "params", "status_filter", "master_source", "master_fields"];
667
668pub struct DataSource {
670 pub data_set: Option<ComponentId>,
672 pub auto_edit: bool,
674 pub enabled: bool,
676}
677
678impl Default for DataSource {
679 fn default() -> Self {
680 Self { data_set: None, auto_edit: true, enabled: true }
681 }
682}
683
684impl DataSource {
685 pub fn new(data_set: ComponentId) -> Self {
686 Self { data_set: Some(data_set), ..Default::default() }
687 }
688}
689
690impl Component for DataSource {
691 fn class_name(&self) -> &'static str {
692 "DataSource"
693 }
694
695 properties! {
696 data_set: Option<ComponentId> => "Data",
697 auto_edit: bool => "Data",
698 enabled: bool => "Data";
699 events: on_data_change: (), on_state_change: ()
700 }
701
702 fn notification(&mut self, freed: ComponentId) {
703 if self.data_set == Some(freed) {
704 self.data_set = None;
705 }
706 }
707}
708
709#[derive(Clone, Copy, Debug, PartialEq, Eq)]
711pub(crate) enum Asking {
712 Post,
713 Delete,
714}