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