1pub mod inspect;
127pub mod mcp;
128pub mod script;
129
130use aylis_core::platform::LocaleInfo;
131use aylis_core::{ComponentId, EventArgs, Key, ModalResult, PointerButton, PropEnum, PropValue, Theme, Ui};
132use aylis_data::json::{json_to_value, value_to_json};
133use aylis_data::{DataSet, data_set};
134use serde_json::{Map, Value, json};
135
136thread_local! {
137 static CURRENT_ID: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
140 static PROFILE_MARKS: std::cell::RefCell<Vec<(String, f64)>> = const { std::cell::RefCell::new(Vec::new()) };
143}
144
145pub fn register_all(ui: &mut Ui) {
147 aylis_controls::register(ui);
148 aylis_data::register(ui);
149 aylis_dbcontrols::register(ui);
150 aylis_providers::register(ui);
151 aylis_media::register(ui);
152 aylis_vector::register(ui);
153 aylis_markdown::register(ui);
154 aylis_webview::register(ui);
155 mcp::register(ui);
156}
157
158pub const PROTOCOL_VERSION: u64 = 1;
162
163pub const CAPABILITIES: &[&str] = &["wake", "exception", "deflate", "ask"];
165
166pub const COMPRESS_ABOVE: usize = 1024;
168
169pub fn compress(text: &str) -> Vec<u8> {
173 miniz_oxide::deflate::compress_to_vec(text.as_bytes(), 6)
174}
175
176pub fn decompress(bytes: &[u8]) -> Option<String> {
178 let raw = miniz_oxide::inflate::decompress_to_vec(bytes).ok()?;
179 String::from_utf8(raw).ok()
180}
181
182pub fn announces_deflate(line: &str) -> bool {
184 line.contains("\"capabilities\"")
185 && serde_json::from_str::<Value>(line).ok().is_some_and(|m| {
186 m["result"]["capabilities"].as_array().is_some_and(|c| c.iter().any(|v| v == "deflate"))
187 })
188}
189
190#[derive(Default)]
194pub struct Handshake {
195 greeted: bool,
196}
197
198impl Handshake {
199 pub fn check(&mut self, message: &Value) -> Option<Value> {
202 if message.get("cmd").and_then(Value::as_str) == Some("hello") {
203 self.greeted = true;
204 return None;
205 }
206 if self.greeted {
207 return None;
208 }
209 let error = "o backend não se apresentou: a primeira mensagem tem de ser {\"cmd\": \"hello\", \"protocol\": 1} (atualize o cliente do aylis)";
210 Some(match message.get("id") {
211 Some(id) => json!({ "id": id, "error": error }),
212 None => json!({ "event": "error", "cmd": message.get("cmd").cloned().unwrap_or(Value::Null), "message": error }),
213 })
214 }
215}
216
217fn hello(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
221 let theirs = obj.get("protocol").and_then(Value::as_u64).ok_or("hello: falta \"protocol\" (a versão do protocolo do cliente)")?;
222 let done = obj.get("features").and_then(Value::as_array).is_some_and(|f| f.iter().any(|v| v == "done"));
225 ui.extension::<Remote>().busy.tracking = done;
226 if theirs == PROTOCOL_VERSION {
227 return Ok(json!({ "protocol": PROTOCOL_VERSION, "capabilities": CAPABILITIES }));
228 }
229 let update_url = obj.get("update_url").and_then(Value::as_str).unwrap_or_default();
230 let (user, backend) = if theirs > PROTOCOL_VERSION {
231 let mut text = aylis_core::messages::t("Há uma versão nova do aplicativo. Atualize para continuar.").to_string();
232 if !update_url.is_empty() {
233 text = format!("{text}\n{update_url}");
234 }
235 (text, format!("a tela é do protocolo {PROTOCOL_VERSION} e o backend do {theirs}: atualize o aplicativo (a tela)"))
236 } else {
237 (
238 aylis_core::messages::t("O servidor do aplicativo é de uma versão anterior. Tente de novo mais tarde.").to_string(),
239 format!("a tela é do protocolo {PROTOCOL_VERSION} e o backend do {theirs}: atualize o backend (o cliente do aylis)"),
240 )
241 };
242 ui.raise_exception(aylis_core::Exception { message: user, path: String::new(), event: "hello".into() });
243 Err(backend)
244}
245
246pub fn handle_message(ui: &mut Ui, message: &Value) -> Option<Value> {
249 if message.get("cmd").and_then(Value::as_str) == Some("wake") {
251 return Some(json!({ "event": "__post" }));
252 }
253 let id = message.get("id").cloned();
254 CURRENT_ID.with(|c| *c.borrow_mut() = id.clone());
255 let result = execute(ui, message);
256 let deferred = id.is_some() && CURRENT_ID.with(|c| c.borrow_mut().take()).is_none();
258 if deferred {
259 return result.err().map(|error| json!({ "event": "error", "cmd": message.get("cmd").cloned().unwrap_or(Value::Null), "message": error }));
260 }
261 match (id, result) {
262 (Some(id), Ok(result)) => Some(json!({ "id": id, "result": result })),
263 (Some(id), Err(error)) => Some(json!({ "id": id, "error": error })),
264 (None, Ok(_)) => None,
265 (None, Err(error)) => {
266 let cmd = message.get("cmd").cloned().unwrap_or(Value::Null);
267 Some(json!({ "event": "error", "cmd": cmd, "message": error }))
268 }
269 }
270}
271
272pub fn execute(ui: &mut Ui, command: &Value) -> Result<Value, String> {
274 let obj = command.as_object().ok_or("o comando deve ser um objeto JSON")?;
275 let cmd = obj.get("cmd").and_then(Value::as_str).ok_or("falta \"cmd\"")?;
276 match cmd {
277 "load" => {
278 let layout = obj.get("layout").ok_or("falta \"layout\"")?;
279 let document = if layout.get("root").is_some() { layout.clone() } else { json!({ "root": layout }) };
280 let parent = optional_target(ui, obj.get("parent"))?;
281 let id = aylis_json::load_value(ui, &document, parent).map_err(|e| e.to_string())?;
282 aylis_data::open_active(ui);
283 Ok(json!({ "id": id.to_u64(), "name": ui.name(id) }))
284 }
285 "create" => {
286 let class = string(obj, "class")?;
287 let parent = optional_target(ui, obj.get("parent"))?;
288 let id = ui.create(class, parent).map_err(|e| e.to_string())?;
289 let setup = (|| {
290 if let Some(name) = obj.get("name").and_then(Value::as_str) {
291 ui.set_name(id, name).map_err(|e| e.to_string())?;
292 }
293 if let Some(props) = obj.get("props") {
294 let props = props.as_object().ok_or("\"props\" deve ser um objeto")?;
295 ui.without_change_events(|ui| aylis_json::set_props(ui, id, props))?;
297 }
298 Ok::<_, String>(())
299 })();
300 if let Err(e) = setup {
301 ui.free(id);
302 return Err(e);
303 }
304 aylis_data::open_active(ui);
305 Ok(json!({ "id": id.to_u64() }))
306 }
307 "set" => {
308 let id = target(ui, obj)?;
309 if let Some(name) = obj.get("prop").and_then(Value::as_str) {
311 let value = obj.get("value").ok_or("falta \"value\" (com \"prop\")")?;
312 let mut one = Map::new();
313 one.insert(name.to_string(), value.clone());
314 aylis_json::set_props(ui, id, &one)?;
315 return Ok(Value::Null);
316 }
317 let props = obj.get("props").and_then(Value::as_object).ok_or("informe \"prop\" e \"value\", ou \"props\" (objeto)")?;
318 aylis_json::set_props(ui, id, props)?;
319 Ok(Value::Null)
320 }
321 "get" => {
322 let id = target(ui, obj)?;
323 if let Some(name) = obj.get("prop").and_then(Value::as_str) {
324 if obj.get("ref").and_then(Value::as_bool) == Some(true) {
327 let value = ui.get_prop(id, name).map_err(|e| e.to_string())?;
328 return Ok(match value.to_component() {
329 Ok(Some(c)) => json!({ "id": c.to_u64(), "name": ui.name(c).unwrap_or_default(), "class": ui.class_name(c).unwrap_or_default() }),
330 _ => Value::Null,
331 });
332 }
333 return get(ui, id, name);
334 }
335 let names = obj.get("props").and_then(Value::as_array).ok_or("informe \"prop\" ou \"props\"")?;
336 let mut out = Map::new();
337 for name in names {
338 let name = name.as_str().ok_or("\"props\" deve ser uma lista de nomes")?;
339 out.insert(name.to_string(), get(ui, id, name)?);
340 }
341 Ok(Value::Object(out))
342 }
343 "free" => {
344 let id = target(ui, obj)?;
345 ui.free(id);
346 Ok(Value::Null)
347 }
348 "invoke" => {
350 let id = target(ui, obj)?;
351 let method = string(obj, "method")?;
352 let args: Vec<PropValue> = obj.get("args").and_then(Value::as_array).map(|a| a.iter().map(json_arg).collect()).unwrap_or_default();
353 let result = ui.invoke(id, method, &args)?;
354 if obj.get("ref").and_then(Value::as_bool) == Some(true) {
356 return Ok(match result.to_component() {
357 Ok(Some(c)) => json!({ "id": c.to_u64(), "name": ui.name(c).unwrap_or_default(), "class": ui.class_name(c).unwrap_or_default() }),
358 _ => Value::Null,
359 });
360 }
361 Ok(aylis_json::prop_to_json(ui, &result))
362 }
363 "click" => {
364 let id = target(ui, obj)?;
365 if !["modifiers", "x", "y", "button", "double"].iter().any(|k| obj.contains_key(*k)) {
367 ui.click(id);
368 return Ok(Value::Null);
369 }
370 let (root, at) = point_in(ui, id, obj.get("x"), obj.get("y"))?;
371 let mut event = aylis_core::PointerEvent { position: at, button: button(obj)?, modifiers: modifiers(obj)?, click_count: 1, ..Default::default() };
372 ui.pointer_move(root, event);
373 ui.pointer_down(root, event);
374 ui.pointer_up(root, event);
375 if obj.get("double").and_then(Value::as_bool) == Some(true) {
376 event.click_count = 2;
377 ui.pointer_down(root, event);
378 ui.pointer_up(root, event);
379 }
380 ui.process_events();
381 Ok(Value::Null)
382 }
383 "drag" => {
388 let from = resolve(ui, obj.get("from").ok_or("falta \"from\"")?)?;
389 let (root, start) = point_in(ui, from, obj.get("from_x"), obj.get("from_y"))?;
390 let steps = obj.get("steps").and_then(Value::as_u64).unwrap_or(10).clamp(1, 200) as usize;
391 let event = aylis_core::PointerEvent { position: start, button: button(obj)?, modifiers: modifiers(obj)?, click_count: 1, ..Default::default() };
392 let Some(to) = obj.get("to") else {
395 let screen = |k: &str| obj.get(k).and_then(Value::as_i64).map(|v| v as i32).ok_or(format!("drag sem \"to\": falta \"{k}\""));
396 let (x, y) = (screen("screen_x")?, screen("screen_y")?);
397 start_drag_between_forms(ui, root, start, event)?;
398 ui.drag_over_form(root, None, aylis_core::PointF::default());
399 ui.set_screen_pointer(Some(aylis_core::ScreenPointer { x, y, scale: 1.0 }));
400 ui.pointer_up(root, aylis_core::PointerEvent { position: aylis_core::PointF::new(-1.0e6, -1.0e6), ..event });
401 ui.process_events();
402 return Ok(Value::Null);
403 };
404 let to = resolve(ui, to)?;
405 let (end_root, end) = point_in(ui, to, obj.get("to_x"), obj.get("to_y"))?;
406 if end_root != root {
409 start_drag_between_forms(ui, root, start, event)?;
410 for _ in 0..steps.min(3) {
411 ui.drag_over_form(root, Some(end_root), end);
412 ui.process_events();
413 }
414 ui.pointer_up(root, aylis_core::PointerEvent { position: aylis_core::PointF::new(-1.0e6, -1.0e6), ..event });
415 ui.process_events();
416 return Ok(Value::Null);
417 }
418 ui.pointer_move(root, event);
419 ui.pointer_down(root, event);
420 for i in 1..=steps {
421 let t = i as f32 / steps as f32;
422 let at = aylis_core::PointF::new(start.x + (end.x - start.x) * t, start.y + (end.y - start.y) * t);
423 ui.pointer_move(root, aylis_core::PointerEvent { position: at, ..event });
424 ui.process_events();
425 }
426 ui.pointer_up(root, aylis_core::PointerEvent { position: end, ..event });
427 ui.process_events();
428 Ok(Value::Null)
429 }
430 "drag_window" => {
433 let form = resolve(ui, obj.get("form").ok_or("falta \"form\"")?)?;
434 let form = ui.root_of(form);
435 let to = resolve(ui, obj.get("to").ok_or("falta \"to\"")?)?;
436 let (end_root, end) = point_in(ui, to, obj.get("to_x"), obj.get("to_y"))?;
437 if end_root == form {
438 return Err("drag_window: \"to\" está no próprio form".into());
439 }
440 ui.window_drag_over(form, Some((end_root, end)));
441 let received = ui.window_drag_end(form);
442 ui.process_events();
443 Ok(json!({ "received": received }))
444 }
445 "items" => {
447 let id = target(ui, obj)?;
448 let items: Vec<Value> = ui
449 .access_items(id)
450 .into_iter()
451 .map(|it| {
452 serde_json::json!({
453 "role": format!("{:?}", it.role).to_lowercase(),
454 "name": it.name,
455 "selected": it.selected,
456 "checked": it.checked,
457 "disabled": it.disabled,
458 "parent": it.parent,
459 "row": it.row,
460 "column": it.column,
461 "level": it.level,
462 "expanded": it.expanded,
463 })
464 })
465 .collect();
466 Ok(Value::Array(items))
467 }
468 "click_item" => {
471 use aylis_core::automation::ItemAction;
472 let id = target(ui, obj)?;
473 let action = match obj.get("action").and_then(Value::as_str).unwrap_or("click") {
474 "select" => ItemAction::Select,
475 "expand" => ItemAction::Expand,
476 "collapse" => ItemAction::Collapse,
477 _ => ItemAction::Click,
478 };
479 let named = obj.get("item").and_then(Value::as_str).and_then(|name| ui.access_items(id).iter().position(|i| i.name.trim().eq_ignore_ascii_case(name.trim())));
480 let done = match (named, obj.get("index").and_then(Value::as_u64)) {
481 (Some(i), _) => ui.access_action(id, i, action),
482 (None, Some(i)) => ui.access_action(id, i as usize, action),
483 _ => return Err("click_item: informe \"item\" (o texto) ou \"index\"".into()),
484 };
485 if done { Ok(Value::Null) } else { Err("item não encontrado ou sem ação".into()) }
486 }
487 "focus" => {
488 let id = target(ui, obj)?;
489 Ok(Value::Bool(ui.set_focus(id)))
490 }
491 "focused" => {
493 let form = target(ui, obj)?;
494 let root = ui.root_of(form);
495 Ok(ui.focused(root).and_then(|f| ui.name(f).map(|n| Value::String(n.to_string()))).unwrap_or(Value::Null))
496 }
497 "key" => {
501 let form = target(ui, obj)?;
502 let root = ui.root_of(form);
503 let (mut modifiers, key) = aylis_core::parse_shortcut(string(obj, "key")?).ok_or("tecla inválida (ex.: \"Enter\", \"Shift+Tab\", \"Ctrl+A\", \"Alt+S\")")?;
504 let extra = self::modifiers(obj)?;
505 modifiers.shift |= extra.shift;
506 modifiers.ctrl |= extra.ctrl;
507 modifiers.alt |= extra.alt;
508 modifiers.meta |= extra.meta;
509 let event = aylis_core::KeyEvent { key, modifiers, repeat: false };
510 ui.key_down(root, event);
511 ui.key_up(root, event);
512 Ok(Value::Null)
513 }
514 "type" => {
516 let form = target(ui, obj)?;
517 let root = ui.root_of(form);
518 ui.text_input(root, string(obj, "text")?);
519 Ok(Value::Null)
520 }
521 "focus_next" | "focus_prev" => {
523 let form = target(ui, obj)?;
524 let root = ui.root_of(form);
525 Ok(Value::Bool(ui.focus_next(root, cmd == "focus_next")))
526 }
527 "find" => {
528 let name = string(obj, "name")?;
529 Ok(ui.find(name).map_or(Value::Null, |id| Value::from(id.to_u64())))
530 }
531 "save" => {
532 let id = target(ui, obj)?;
533 aylis_json::save_value(ui, id).map_err(|e| e.to_string())
534 }
535 "theme" => {
536 let theme = match (obj.get("theme"), obj.get("name").and_then(Value::as_str)) {
537 (Some(theme), _) => aylis_json::theme_from_value(theme).map_err(|e| e.to_string())?,
538 (None, Some("dark")) => Theme::dark(),
539 (None, Some("light")) => Theme::light(),
540 _ => return Err("informe \"theme\" (JSON) ou \"name\": \"light\"/\"dark\"".into()),
541 };
542 ui.set_theme(theme);
543 Ok(Value::Null)
544 }
545 "locale" => {
546 let locale = match string(obj, "locale")? {
547 "pt-BR" | "pt_BR" | "pt" => LocaleInfo::pt_br(),
548 "en-US" | "en_US" | "en" => LocaleInfo::en_us(),
549 other => return Err(format!("idioma '{other}' não suportado (use pt-BR ou en-US)")),
550 };
551 ui.services_mut().locale = Some(Box::new(locale));
552 Ok(Value::Null)
553 }
554 "data" => data_command(ui, obj),
555 "batch" => {
556 let commands = obj.get("commands").and_then(Value::as_array).ok_or("falta \"commands\" (lista)")?;
557 Ok(Value::Array(
558 commands
559 .iter()
560 .map(|c| execute(ui, c).unwrap_or_else(|e| json!({ "error": e })))
561 .collect(),
562 ))
563 }
564 "create_form" => {
565 let name = string(obj, "name")?;
567 let fresh = obj.get("new").and_then(Value::as_bool).unwrap_or(false);
568 let id = if fresh { ui.create_form_instance(name) } else { ui.create_form(name) }.map_err(|e| e.to_string())?;
569 aylis_data::open_active(ui);
570 Ok(json!({ "id": id.to_u64(), "name": ui.name(id) }))
571 }
572 "show" => {
573 let id = target(ui, obj)?;
574 ui.show(id).map_err(|e| e.to_string())?;
575 Ok(Value::Null)
576 }
577 "show_modal" => {
578 let id = target(ui, obj)?;
579 let handler = obj.get("handler").and_then(Value::as_str).map(str::to_string);
580 let reply = if obj.get("wait").and_then(Value::as_bool) == Some(true) { defer_reply(ui) } else { None };
582 let waiting = ui.backend_busy();
584 if waiting {
585 ui.backend_waiting_user(true);
586 }
587 ui.show_modal(id, move |ui, result| {
588 if waiting {
589 ui.backend_waiting_user(false);
590 }
591 if let Some(reply) = reply {
592 send_reply(ui, reply, Ok(json!(result.name())));
593 }
594 if let Some(handler) = handler {
595 let args = EventArgs::Value(PropValue::Enum(result.name().to_string()));
596 ui.call_handler(id, "on_modal_result", &handler, &args);
597 }
598 })
599 .map_err(|e| e.to_string())?;
600 Ok(Value::Null)
601 }
602 "components" => {
606 let form = target(ui, obj)?;
607 let mut out = Vec::new();
608 let mut stack = ui.children(form).to_vec();
609 while let Some(id) = stack.pop() {
610 if ui.form_of(id) != form {
611 continue;
612 }
613 if let Some(name) = ui.name(id).filter(|n| !n.is_empty()) {
614 out.push(json!({ "name": name, "id": id.to_u64(), "class": ui.class_name(id).unwrap_or_default() }));
615 }
616 stack.extend(ui.children(id).iter().copied());
617 }
618 Ok(Value::Array(out))
619 }
620 "close" => match obj.get("target") {
621 Some(t) => {
622 let id = resolve(ui, t)?;
623 Ok(Value::Bool(ui.close(id)))
624 }
625 None => {
626 ui.request_close();
627 Ok(Value::Null)
628 }
629 },
630 "media" => media(ui, obj),
631 "tree" => {
632 let root = optional_target(ui, obj.get("target"))?;
633 let depth = obj.get("depth").and_then(Value::as_u64).map_or(usize::MAX, |d| d as usize);
635 let visible_only = obj.get("visible_only").and_then(Value::as_bool).unwrap_or(false);
636 Ok(inspect::tree_with(ui, root, depth, visible_only))
637 }
638 "props" => {
639 let id = target(ui, obj)?;
640 Ok(inspect::props(ui, id))
641 }
642 "rect" => {
644 let id = target(ui, obj)?;
645 ui.layout();
646 let abs = ui.absolute_rect(id).ok_or("componente sem posição")?;
647 let own = ui.bounds(id).ok_or("componente sem posição")?;
648 Ok(serde_json::json!({ "x": abs.x, "y": abs.y, "width": abs.width, "height": abs.height, "in_parent": [own.x, own.y, own.width, own.height] }))
649 }
650 "highlight" => {
651 let id = target(ui, obj)?;
652 inspect::highlight(ui, id)?;
653 Ok(Value::Null)
654 }
655 "tr" => Ok(Value::String(ui.tr(string(obj, "text")?))),
656 "set_language" => {
657 aylis_project::i18n::set_language(ui, string(obj, "language")?);
658 Ok(Value::Null)
659 }
660 "toast" => {
661 aylis_controls::toast(ui, string(obj, "text")?);
662 Ok(Value::Null)
663 }
664 "profile_begin" => {
667 let name = string(obj, "name")?.to_string();
668 PROFILE_MARKS.with(|m| m.borrow_mut().push((name, aylis_core::profile::now())));
669 Ok(Value::Null)
670 }
671 "profile_end" => {
672 if let Some((name, start)) = PROFILE_MARKS.with(|m| m.borrow_mut().pop()) {
673 aylis_core::profile::record(aylis_core::profile::Lane::Mark, &name, start, (aylis_core::profile::now() - start).max(0.0));
674 }
675 Ok(Value::Null)
676 }
677 "message_dlg" => {
678 use aylis_controls::DlgKind;
679 let text = string(obj, "text")?.to_string();
680 let kind = match obj.get("kind").and_then(Value::as_str).unwrap_or("information") {
681 "warning" => DlgKind::Warning,
682 "error" => DlgKind::Error,
683 "confirmation" => DlgKind::Confirmation,
684 _ => DlgKind::Information,
685 };
686 let buttons: Vec<ModalResult> = obj
687 .get("buttons")
688 .and_then(Value::as_array)
689 .map(|a| a.iter().filter_map(|b| b.as_str().and_then(ModalResult::from_name)).collect())
690 .unwrap_or_default();
691 let handler = obj.get("handler").and_then(Value::as_str).map(str::to_string);
692 let reply = if obj.get("wait").and_then(Value::as_bool) == Some(true) { defer_reply(ui) } else { None };
693 let waiting = ui.backend_busy();
694 if waiting {
695 ui.backend_waiting_user(true);
696 }
697 let form = aylis_controls::message_dlg(ui, &text, kind, &buttons, move |ui, result| {
698 if waiting {
699 ui.backend_waiting_user(false);
700 }
701 if let Some(reply) = reply {
702 send_reply(ui, reply, Ok(json!(result.name())));
703 }
704 if let (Some(handler), Some(main)) = (handler, ui.main_form()) {
705 let args = EventArgs::Value(PropValue::Enum(result.name().to_string()));
706 ui.call_handler(main, "on_modal_result", &handler, &args);
707 }
708 });
709 Ok(json!(ui.path_of(form)))
710 }
711 "execute" => {
712 let id = target(ui, obj)?;
713 aylis_controls::OpenDialog::execute(ui, id);
714 Ok(Value::Null)
715 }
716 "hello" => hello(ui, obj),
717 "exception" => {
720 let message = string(obj, "message")?.to_string();
721 let path = obj.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
722 let event = obj.get("handler").and_then(Value::as_str).unwrap_or_default().to_string();
723 ui.raise_exception(aylis_core::Exception { message, path, event });
724 Ok(Value::Null)
725 }
726 "done" => {
730 let seq = obj.get("seq").and_then(Value::as_u64).ok_or("falta 'seq'")?;
731 backend_done(ui, seq);
732 Ok(Value::Null)
733 }
734 "answer" => {
735 let token = obj.get("ask").and_then(Value::as_u64).ok_or("falta 'ask' (o número da pergunta)")?;
736 let answer = match obj.get("error").and_then(Value::as_str) {
737 Some(message) => aylis_core::Answer::Refused(message.to_string()),
738 None => {
739 let values = obj.get("values").and_then(Value::as_object).map(|m| m.iter().map(|(k, v)| (k.clone(), answer_value(v))).collect()).unwrap_or_default();
740 aylis_core::Answer::Accepted(values)
741 }
742 };
743 ui.answer(token, answer);
744 flush_waiting_data(ui);
745 Ok(Value::Null)
746 }
747 "modal_result" => {
748 let id = target(ui, obj)?;
749 let name = string(obj, "result")?;
750 let result = ModalResult::from_name(name).ok_or_else(|| format!("resultado '{name}' inválido (use {})", ModalResult::NAMES.join(", ")))?;
751 ui.set_modal_result(id, result);
752 Ok(Value::Null)
753 }
754 other => Err(format!("comando desconhecido '{other}'")),
755 }
756}
757
758fn media(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
760 use aylis_media::{MediaPlayer, VideoPlayer};
761 let id = target(ui, obj)?;
762 let op = string(obj, "op")?;
763 let video = ui.get::<VideoPlayer>(id).is_some();
764 if !video && ui.get::<MediaPlayer>(id).is_none() {
765 return Err("o alvo não é um MediaPlayer nem um VideoPlayer".into());
766 }
767 let seconds = obj.get("seconds").and_then(Value::as_f64).unwrap_or(0.0);
768 Ok(match (op, video) {
769 ("play", true) => VideoPlayer::play(ui, id).map(|_| Value::Null)?,
770 ("play", false) => MediaPlayer::play(ui, id).map(|_| Value::Null)?,
771 ("pause", true) => {
772 VideoPlayer::pause(ui, id);
773 Value::Null
774 }
775 ("pause", false) => {
776 MediaPlayer::pause(ui, id);
777 Value::Null
778 }
779 ("stop", true) => {
780 VideoPlayer::stop(ui, id);
781 Value::Null
782 }
783 ("stop", false) => {
784 MediaPlayer::stop(ui, id);
785 Value::Null
786 }
787 ("seek", true) => {
788 VideoPlayer::seek(ui, id, seconds);
789 Value::Null
790 }
791 ("seek", false) => {
792 MediaPlayer::seek(ui, id, seconds);
793 Value::Null
794 }
795 ("position", true) => json!(VideoPlayer::position(ui, id)),
796 ("position", false) => json!(MediaPlayer::position(ui, id)),
797 ("duration", true) => json!(VideoPlayer::duration(ui, id)),
798 ("duration", false) => json!(MediaPlayer::duration(ui, id)),
799 ("playing", true) => json!(VideoPlayer::is_playing(ui, id)),
800 ("playing", false) => json!(MediaPlayer::is_playing(ui, id)),
801 (other, _) => return Err(format!("operação de mídia desconhecida '{other}'")),
802 })
803}
804
805fn string<'a>(obj: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
806 obj.get(key).and_then(Value::as_str).ok_or_else(|| format!("falta \"{key}\" (texto)"))
807}
808
809pub fn resolve(ui: &Ui, value: &Value) -> Result<ComponentId, String> {
811 match value {
812 Value::String(name) if !name.is_empty() && !name.contains('.') => {
815 let found = named_everywhere(ui, name);
816 match found.as_slice() {
817 [one] => Ok(*one),
818 [] => ui.find_path(name).ok_or_else(|| format!("componente '{name}' não encontrado")),
819 many => Err(format!(
820 "o nome '{name}' está em {} lugares; use o caminho ou o id: {}",
821 many.len(),
822 many.iter().map(|&id| format!("{} (id {})", ui.path_of(id), id.to_u64())).collect::<Vec<_>>().join(", ")
823 )),
824 }
825 }
826 Value::String(name) => ui.find_path(name).ok_or_else(|| format!("componente '{name}' não encontrado")),
827 Value::Number(n) => {
828 let id = ComponentId::from_u64(n.as_u64().ok_or("id inválido")?);
829 if ui.contains(id) { Ok(id) } else { Err(format!("componente {n} não existe (ou foi liberado)")) }
830 }
831 other => Err(format!("alvo inválido: {other} (use o nome ou o id)")),
832 }
833}
834
835fn named_everywhere(ui: &Ui, name: &str) -> Vec<ComponentId> {
837 let mut found = Vec::new();
838 let mut stack: Vec<ComponentId> = ui.roots().to_vec();
839 while let Some(id) = stack.pop() {
840 if ui.name(id).is_some_and(|n| n.eq_ignore_ascii_case(name)) {
841 found.push(id);
842 }
843 stack.extend(ui.children(id).iter().copied());
844 }
845 found
846}
847
848fn start_drag_between_forms(ui: &mut Ui, root: ComponentId, start: aylis_core::PointF, event: aylis_core::PointerEvent) -> Result<(), String> {
853 ui.pointer_move(root, event);
854 ui.pointer_down(root, event);
855 for i in 1..=6 {
857 let at = aylis_core::PointF::new(start.x + 6.0 * i as f32, start.y + 12.0 * i as f32);
858 ui.pointer_move(root, aylis_core::PointerEvent { position: at, ..event });
859 ui.process_events();
860 }
861 if !ui.dragging(root) {
862 ui.pointer_up(root, event);
863 return Err("drag: o arrasto não começou (o componente em \"from\" não arrasta)".into());
864 }
865 Ok(())
866}
867
868fn point_in(ui: &mut Ui, id: ComponentId, x: Option<&Value>, y: Option<&Value>) -> Result<(ComponentId, aylis_core::PointF), String> {
869 ui.update_layout();
870 let rect = ui.absolute_rect(id).ok_or("o componente não está numa tela")?;
871 let coord = |v: Option<&Value>, size: f32, name: &str| -> Result<f32, String> {
872 match v {
873 None | Some(Value::Null) => Ok(size / 2.0),
874 Some(v) => v.as_f64().map(|n| n as f32).ok_or(format!("\"{name}\" tem de ser um número")),
875 }
876 };
877 let at = aylis_core::PointF::new(rect.x + coord(x, rect.width, "x")?, rect.y + coord(y, rect.height, "y")?);
878 Ok((ui.root_of(id), at))
879}
880
881fn modifiers(obj: &Map<String, Value>) -> Result<aylis_core::Modifiers, String> {
884 let names: Vec<String> = match obj.get("modifiers") {
885 None | Some(Value::Null) => return Ok(aylis_core::Modifiers::default()),
886 Some(Value::String(s)) => s.split('+').map(|p| p.trim().to_lowercase()).filter(|p| !p.is_empty()).collect(),
887 Some(Value::Array(a)) => a.iter().map(|v| v.as_str().map(|s| s.trim().to_lowercase()).ok_or("\"modifiers\": uma lista de nomes")).collect::<Result<_, _>>()?,
888 Some(_) => return Err("\"modifiers\": \"Ctrl+Shift\" ou [\"ctrl\", \"shift\"]".into()),
889 };
890 let mut m = aylis_core::Modifiers::default();
891 for name in names {
892 match name.as_str() {
893 "ctrl" | "control" => m.ctrl = true,
894 "shift" => m.shift = true,
895 "alt" => m.alt = true,
896 "meta" | "cmd" | "win" => m.meta = true,
897 other => return Err(format!("tecla modificadora desconhecida: {other} (use ctrl, shift, alt, meta)")),
898 }
899 }
900 Ok(m)
901}
902
903fn button(obj: &Map<String, Value>) -> Result<PointerButton, String> {
905 match obj.get("button").and_then(Value::as_str).unwrap_or("left") {
906 "left" | "primary" => Ok(PointerButton::Primary),
907 "right" | "secondary" => Ok(PointerButton::Secondary),
908 "middle" => Ok(PointerButton::Middle),
909 other => Err(format!("botão desconhecido: {other} (use left, right, middle)")),
910 }
911}
912
913fn target(ui: &Ui, obj: &Map<String, Value>) -> Result<ComponentId, String> {
914 resolve(ui, obj.get("target").ok_or("falta \"target\"")?)
915}
916
917fn optional_target(ui: &Ui, value: Option<&Value>) -> Result<Option<ComponentId>, String> {
918 match value {
919 None | Some(Value::Null) => Ok(None),
920 Some(v) => resolve(ui, v).map(Some),
921 }
922}
923
924fn json_arg(v: &Value) -> PropValue {
926 match v {
927 Value::Bool(b) => PropValue::Bool(*b),
928 Value::Number(n) => n.as_i64().map(PropValue::Int).unwrap_or_else(|| PropValue::Float(n.as_f64().unwrap_or(0.0))),
929 Value::String(s) => PropValue::String(s.clone()),
930 Value::Null => PropValue::Null,
931 other => PropValue::String(other.to_string()),
932 }
933}
934
935fn get(ui: &Ui, id: ComponentId, name: &str) -> Result<Value, String> {
936 let value = ui.get_prop(id, name).map_err(|e| e.to_string())?;
937 Ok(aylis_json::prop_to_json(ui, &value))
938}
939
940fn json_key(json: &Value) -> aylis_data::Value {
944 match json {
945 Value::Null => aylis_data::Value::Null,
946 Value::Bool(b) => aylis_data::Value::Bool(*b),
947 Value::Number(n) => n.as_i64().map(aylis_data::Value::Int).unwrap_or_else(|| aylis_data::Value::Float(n.as_f64().unwrap_or(0.0))),
948 Value::String(s) => aylis_data::Value::String(s.clone()),
949 other => aylis_data::Value::String(other.to_string()),
950 }
951}
952
953fn data(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
954 let id = target(ui, obj)?;
955 if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
956 return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
957 }
958 let op = string(obj, "op")?;
959 let mut ds = data_set(ui, id);
960 let ok = |r: aylis_data::DataResult| r.map(|_| Value::Null).map_err(|e| e.message);
961 match op {
962 "load" => ok(ds.load_json(obj.get("rows").ok_or("falta \"rows\"")?)),
963 "load_columns" => ok(ds.load_columns(obj.get("fields").ok_or("falta \"fields\"")?, obj.get("columns").ok_or("falta \"columns\"")?)),
965 "append" => {
966 let more = obj.get("has_more").and_then(Value::as_bool).unwrap_or(false);
967 ok(ds.append_json(obj.get("rows").ok_or("falta \"rows\"")?, more))
968 }
969 "reconcile" => {
971 let results = obj.get("results").ok_or("falta \"results\"")?;
972 let results = ds.parse_results(&json!({ "results": results }).to_string()).map_err(|e| e.message)?;
973 let rejected: Vec<&str> = results.iter().filter_map(|r| r.error.as_deref()).collect();
974 let rejected = json!({ "rejected": rejected });
975 let _ = ds.reconcile(&results);
976 Ok(rejected)
977 }
978 "first" => ok(ds.first()),
979 "prior" => ok(ds.prior()),
980 "next" => ok(ds.next()),
981 "last" => ok(ds.last()),
982 "move_to" => ok(ds.move_to(obj.get("index").and_then(Value::as_u64).ok_or("falta \"index\"")? as usize)),
983 "edit" => ok(ds.edit()),
984 "insert" => ok(ds.insert()),
985 "append_record" => ok(ds.append()),
986 "post" => {
988 ok(ds.post())?;
989 if ds.is_asking() || ds.awaiting_text() {
990 if let Some(reply) = defer_reply(ds.ui()) {
991 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "post".into(), replay: None });
992 }
993 }
994 Ok(Value::Null)
995 }
996 "cancel" => ok(ds.cancel()),
997 "delete" => {
998 ok(ds.delete())?;
999 if ds.is_asking() {
1000 if let Some(reply) = defer_reply(ds.ui()) {
1001 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "delete".into(), replay: None });
1002 }
1003 }
1004 Ok(Value::Null)
1005 }
1006 "apply" => {
1009 let result = ds.apply_updates();
1010 if ds.is_applying() {
1011 if let Some(reply) = defer_reply(ds.ui()) {
1012 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "apply".into(), replay: None });
1013 }
1014 return Ok(Value::Null);
1015 }
1016 match result {
1017 Err(e) if ds.apply_errors() == 0 => Err(e.message),
1018 _ => Ok(json!(ds.apply_errors())),
1019 }
1020 }
1021 "cancel_updates" => ok(ds.cancel_updates()),
1022 "refresh" => {
1023 ds.refresh_links();
1024 Ok(Value::Null)
1025 }
1026 "set_has_more" => ok(ds.set_has_more(obj.get("value").and_then(Value::as_bool).unwrap_or(false))),
1027 "set_value" => {
1028 let field = string(obj, "field")?;
1029 let json = obj.get("value").cloned().unwrap_or(Value::Null);
1030 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
1031 ok(ds.set_value(field, value))
1032 }
1033 "set_text" => {
1034 let field = string(obj, "field")?;
1035 ok(ds.set_text(field, string(obj, "text")?))
1036 }
1037 "set_values" => {
1040 let values = obj.get("values").and_then(Value::as_object).ok_or("falta \"values\" (objeto)")?;
1041 if !ds.state().is_editing() {
1042 ds.edit().map_err(|e| e.message)?;
1043 }
1044 for (field, json) in values {
1045 let value = json_to_value(json, ds.view().field(field).map_err(|e| e.message)?)?;
1046 ds.set_value(field, value).map_err(|e| format!("{field}: {}", e.message))?;
1047 }
1048 Ok(Value::Null)
1049 }
1050 "locate" => {
1051 let field = string(obj, "field")?;
1052 let json = obj.get("value").cloned().unwrap_or(Value::Null);
1053 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
1054 ds.locate(field, value).map(Value::Bool).map_err(|e| e.message)
1055 }
1056 "set_filter" => ok(ds.set_filter(obj.get("filter").and_then(Value::as_str).unwrap_or_default())),
1057 "set_index" => ok(ds.set_index(obj.get("index").and_then(Value::as_str).unwrap_or_default())),
1058 "set_index_name" => ok(ds.set_index_name(obj.get("name").and_then(Value::as_str).unwrap_or_default())),
1059 "set_param" => {
1061 let name = string(obj, "name")?;
1062 ok(ds.set_param(name, json_key(obj.get("value").unwrap_or(&Value::Null))))
1063 }
1064 "revert_record" => ok(ds.revert_record()),
1065 "field_texts" => {
1067 let field = string(obj, "field")?;
1068 let pairs = obj.get("texts").and_then(Value::as_array).ok_or("falta \"texts\" (lista de [valor, texto])")?;
1069 let texts = pairs
1070 .iter()
1071 .filter_map(|p| {
1072 let p = p.as_array()?;
1073 Some((json_key(p.first()?), p.get(1)?.as_str().unwrap_or_default().to_string()))
1074 })
1075 .collect();
1076 ok(ds.set_field_texts(field, texts))
1077 }
1078 "field_error" => {
1081 let field = string(obj, "field")?;
1082 let message = obj.get("message").and_then(Value::as_str).map(str::to_string);
1083 ok(ds.set_field_error(field, message))
1084 }
1085 "lookup" => {
1086 let key_fields = string(obj, "key_fields")?;
1087 let result = string(obj, "result_field")?;
1088 let keys: Vec<aylis_data::Value> = match obj.get("keys") {
1089 Some(Value::Array(list)) => list.iter().map(json_key).collect(),
1090 Some(k) => vec![json_key(k)],
1091 None => return Err("falta \"keys\"".into()),
1092 };
1093 Ok(ds.view().lookup(key_fields, &keys, result).map(|v| value_to_json(&v)).unwrap_or(Value::Null))
1094 }
1095 "value" => ds.value(string(obj, "field")?).map(|v| value_to_json(&v)).map_err(|e| e.message),
1096 "text" => ds.text(string(obj, "field")?).map(Value::String).map_err(|e| e.message),
1097 "record" => record(&ds),
1098 "info" => {
1099 let v = ds.view();
1100 Ok(json!({
1101 "state": format!("{:?}", v.state()).to_lowercase(),
1102 "rec_no": v.rec_no(),
1103 "count": v.record_count(),
1104 "changes": v.change_count(),
1105 "has_more": v.has_more(),
1106 "bof": v.bof(),
1107 "eof": v.eof(),
1108 "status": v.update_status().map(|s| format!("{s:?}").to_lowercase()),
1110 }))
1111 }
1112 "delta" => {
1113 let changes = ds.delta_with_details().map_err(|e| e.message)?;
1114 let name = ds.ui().name(id).unwrap_or_default().to_string();
1115 serde_json::from_str(&aylis_data::json::delta_to_json(&name, &changes)).map_err(|e| e.to_string())
1116 }
1117 other => Err(format!("operação de dados desconhecida '{other}'")),
1118 }
1119}
1120
1121fn answer_value(v: &Value) -> PropValue {
1123 match v {
1124 Value::Bool(b) => PropValue::Bool(*b),
1125 Value::Number(n) if n.is_i64() => PropValue::Int(n.as_i64().unwrap_or_default()),
1126 Value::Number(n) => PropValue::Float(n.as_f64().unwrap_or_default()),
1127 Value::String(s) => PropValue::String(s.clone()),
1128 Value::Null => PropValue::Null,
1129 other => PropValue::String(other.to_string()),
1130 }
1131}
1132
1133fn record(ds: &DataSet<'_>) -> Result<Value, String> {
1134 let v = ds.view();
1135 let mut out = Map::new();
1136 for name in v.field_names() {
1137 out.insert(name.clone(), value_to_json(&v.value(&name).map_err(|e| e.message)?));
1138 }
1139 Ok(Value::Object(out))
1140}
1141
1142pub fn event_to_json(ui: &Ui, sender: ComponentId, event: &str, handler: &str, args: &EventArgs) -> Value {
1146 let mut message = json!({
1147 "event": event,
1148 "handler": handler,
1149 "form": ui.form_class(ui.form_of(sender)).or_else(|| ui.name(ui.form_of(sender))).unwrap_or_default(),
1152 "form_id": ui.form_of(sender).to_u64(),
1154 "sender": {
1155 "id": sender.to_u64(),
1156 "name": ui.name(sender).unwrap_or_default(),
1157 "path": ui.path_of(sender),
1158 "class": ui.class_name(sender).unwrap_or_default(),
1159 },
1160 "args": args_to_json(ui, args),
1161 });
1162 if event == "on_click"
1165 && let Some(p) = ui.click_pointer()
1166 {
1167 message["pointer"] = pointer_to_json(&p);
1168 }
1169 let info = ui.component(sender).map(|c| c.event_info(event)).unwrap_or_default();
1172 if !info.is_empty() {
1173 message["info"] = Value::Object(info.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect());
1174 }
1175 message
1176}
1177
1178fn button_name(button: PointerButton) -> &'static str {
1179 match button {
1180 PointerButton::Primary => "primary",
1181 PointerButton::Secondary => "secondary",
1182 PointerButton::Middle => "middle",
1183 PointerButton::Back => "back",
1184 PointerButton::Forward => "forward",
1185 }
1186}
1187
1188fn pointer_to_json(p: &aylis_core::ClickPointer) -> Value {
1190 let m = p.modifiers;
1191 let modifiers: Vec<&str> =
1192 [(m.ctrl, "ctrl"), (m.shift, "shift"), (m.alt, "alt"), (m.meta, "meta")].into_iter().filter(|(on, _)| *on).map(|(_, n)| n).collect();
1193 json!({
1194 "x": p.position.x,
1195 "y": p.position.y,
1196 "form_x": p.form_position.x,
1197 "form_y": p.form_position.y,
1198 "button": button_name(p.button),
1199 "modifiers": modifiers,
1200 "kind": match p.kind {
1201 aylis_core::PointerKind::Mouse => "mouse",
1202 aylis_core::PointerKind::Touch => "touch",
1203 aylis_core::PointerKind::Pen => "pen",
1204 },
1205 "clicks": p.click_count,
1206 })
1207}
1208
1209fn args_to_json(ui: &Ui, args: &EventArgs) -> Value {
1210 match args {
1211 EventArgs::None => Value::Null,
1212 EventArgs::Pointer(p) => json!({
1213 "x": p.position.x,
1214 "y": p.position.y,
1215 "button": button_name(p.button),
1216 "clicks": p.click_count,
1217 }),
1218 EventArgs::Wheel(w) => json!({ "x": w.position.x, "y": w.position.y, "dx": w.delta.x, "dy": w.delta.y }),
1219 EventArgs::Gesture(g) => json!({
1220 "phase": match g.phase { aylis_core::GesturePhase::Begin => "begin", aylis_core::GesturePhase::Update => "update", aylis_core::GesturePhase::End => "end" },
1221 "x": g.center.x, "y": g.center.y, "scale": g.scale, "delta_scale": g.delta_scale,
1222 "rotation": g.rotation, "delta_rotation": g.delta_rotation, "pan_x": g.pan.x, "pan_y": g.pan.y,
1223 }),
1224 EventArgs::Swipe(s) => json!({
1225 "direction": s.direction.name(), "x": s.start.x, "y": s.start.y,
1226 "dx": s.distance.x, "dy": s.distance.y, "vx": s.velocity.x, "vy": s.velocity.y,
1227 }),
1228 EventArgs::Key(k) => json!({
1229 "key": key_name(k.key),
1230 "ctrl": k.modifiers.ctrl,
1231 "shift": k.modifiers.shift,
1232 "alt": k.modifiers.alt,
1233 }),
1234 EventArgs::Text(text) => match serde_json::from_str::<Value>(text) {
1236 Ok(v @ (Value::Object(_) | Value::Array(_))) => v,
1237 _ => Value::String(text.clone()),
1238 },
1239 EventArgs::Value(PropValue::Component(c)) => c.map_or(Value::Null, |id| Value::from(id.to_u64())),
1240 EventArgs::Value(v) => aylis_json::prop_to_json(ui, v),
1241 EventArgs::Intercept(i) => {
1244 let sender = i.sender.map_or(Value::Null, |id| {
1245 json!({
1246 "id": id.to_u64(),
1247 "name": ui.name(id).unwrap_or_default(),
1248 "path": ui.path_of(id),
1249 "class": ui.class_name(id).unwrap_or_default(),
1250 })
1251 });
1252 json!({
1253 "form": i.form.and_then(|f| ui.name(f)).unwrap_or_default(),
1254 "form_id": i.form.map_or(Value::Null, |f| Value::from(f.to_u64())),
1255 "sender": sender,
1256 "event": i.event,
1257 "handler": i.handler,
1258 "args": args_to_json(ui, &i.args),
1259 })
1260 }
1261 }
1262}
1263
1264fn key_name(key: Key) -> String {
1265 match key {
1266 Key::Char(c) => c.to_string(),
1267 Key::F(n) => format!("f{n}"),
1268 other => format!("{other:?}").to_lowercase(),
1269 }
1270}
1271
1272pub fn forward_events(ui: &mut Ui, send: impl Fn(&mut Ui, Value) + 'static) {
1275 let send: std::rc::Rc<dyn Fn(&mut Ui, Value)> = std::rc::Rc::new(send);
1276 ui.extension::<Remote>().sink = Some(send.clone());
1278 ui.on_forms_freed(|ui, forms| {
1280 let ids: Vec<Value> = forms.iter().map(|f| Value::from(f.to_u64())).collect();
1281 send_event(ui, None, json!({ "event": "__freed", "forms": ids }));
1282 });
1283 ui.set_event_sink(move |ui, sender, event, handler, args| {
1284 let mut json = event_to_json(ui, sender, event, handler, args);
1285 if ui.asking() {
1288 json["ask"] = Value::from(ui.defer_question());
1289 }
1290 let key = (sender.to_u64(), event.to_string());
1292 let joined = {
1293 let coalesce = coalesces(ui, sender, event);
1294 let b = &mut ui.extension::<Remote>().busy;
1295 if b.tracking && json.get("ask").is_none() && b.running.values().any(|k| *k == key) && coalesce {
1296 b.latest.insert(key.clone(), json.clone());
1297 true
1298 } else {
1299 false
1300 }
1301 };
1302 if !joined {
1303 send_event(ui, Some(sender), json);
1304 }
1305 });
1306}
1307
1308fn defer_reply(ui: &Ui) -> Option<Value> {
1311 if ui.extension_ref::<Remote>().is_none_or(|r| r.sink.is_none()) {
1312 return None;
1313 }
1314 CURRENT_ID.with(|c| c.borrow_mut().take())
1315}
1316
1317fn send_reply(ui: &mut Ui, id: Value, result: Result<Value, String>) {
1319 let message = match result {
1320 Ok(result) => json!({ "id": id, "result": result }),
1321 Err(error) => json!({ "id": id, "error": error }),
1322 };
1323 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1324 sink(ui, message);
1325 }
1326}
1327
1328fn flush_waiting_data(ui: &mut Ui) {
1331 let waiting = std::mem::take(&mut ui.extension::<Remote>().waiting);
1332 let mut still = Vec::new();
1333 for w in waiting {
1334 let ds = data_set(ui, w.ds);
1335 if ds.is_asking() || ds.awaiting_text() {
1336 still.push(w);
1337 continue;
1338 }
1339 let editing = ds.state().is_editing();
1340 let result = match w.replay {
1341 Some(_) if editing => Err("a gravação foi recusada".to_string()),
1343 Some(command) => {
1344 let had_id = w.reply.is_some();
1346 CURRENT_ID.with(|c| *c.borrow_mut() = w.reply.clone());
1347 let result = data_command(ui, &command);
1348 if had_id && CURRENT_ID.with(|c| c.borrow_mut().take()).is_none() {
1349 continue;
1350 }
1351 result
1352 }
1353 None if w.op == "post" && editing => Err("a gravação foi recusada".to_string()),
1354 None if w.op == "apply" => match ds.apply_errors() {
1355 usize::MAX => Err("a gravação foi recusada".to_string()),
1356 n => Ok(json!(n)),
1357 },
1358 None => Ok(Value::Null),
1359 };
1360 match (w.reply, result) {
1361 (Some(reply), result) => send_reply(ui, reply, result),
1362 (None, Err(error)) => {
1364 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1365 sink(ui, json!({ "event": "error", "cmd": "data", "message": error }));
1366 }
1367 }
1368 (None, Ok(_)) => {}
1369 }
1370 }
1371 ui.extension::<Remote>().waiting.extend(still);
1372}
1373
1374struct Waiting {
1376 reply: Option<Value>,
1378 ds: ComponentId,
1379 op: String,
1380 replay: Option<Map<String, Value>>,
1382}
1383
1384fn data_command(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
1387 match data(ui, obj) {
1388 Err(error) if error == aylis_data::DataError::waiting().message => {
1389 let ds = target(ui, obj)?;
1390 let reply = defer_reply(ui);
1391 let op = string(obj, "op")?.to_string();
1392 ui.extension::<Remote>().waiting.push(Waiting { reply, ds, op, replay: Some(obj.clone()) });
1393 Ok(Value::Null)
1394 }
1395 other => other,
1396 }
1397}
1398
1399#[derive(Default)]
1401struct BusyTrack {
1402 tracking: bool,
1405 next: u64,
1406 running: std::collections::HashMap<u64, (u64, String)>,
1408 latest: std::collections::HashMap<(u64, String), Value>,
1410}
1411
1412pub fn coalesces(ui: &Ui, sender: ComponentId, event: &str) -> bool {
1416 aylis_core::question::COALESCED_EVENTS.contains(&event)
1417 || (event == "on_change" && matches!(ui.class_name(sender), Some("TrackBar" | "Slider" | "RangeSlider" | "ScrollBar" | "Knob" | "Gauge")))
1418}
1419
1420fn backend_done(ui: &mut Ui, seq: u64) {
1422 let next = {
1423 let b = &mut ui.extension::<Remote>().busy;
1424 b.running.remove(&seq).and_then(|key| b.latest.remove(&key))
1425 };
1426 ui.backend_done(seq);
1427 if let Some(json) = next {
1428 let sender = json["sender"]["id"].as_u64().map(ComponentId::from_u64);
1429 send_event(ui, sender, json);
1430 }
1431}
1432
1433fn send_event(ui: &mut Ui, sender: Option<ComponentId>, mut json: Value) {
1435 if ui.extension::<Remote>().busy.tracking {
1436 let seq = {
1437 let b = &mut ui.extension::<Remote>().busy;
1438 b.next += 1;
1439 b.next
1440 };
1441 json["seq"] = Value::from(seq);
1442 if let Some(sender) = sender {
1443 ui.backend_event_sent(seq, sender);
1444 let event = json["event"].as_str().unwrap_or_default().to_string();
1445 if coalesces(ui, sender, &event) {
1446 ui.extension::<Remote>().busy.running.insert(seq, (sender.to_u64(), event));
1447 }
1448 }
1449 }
1450 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1451 sink(ui, json);
1452 }
1453}
1454
1455#[derive(Default)]
1458struct Remote {
1459 sink: Option<std::rc::Rc<dyn Fn(&mut Ui, Value)>>,
1461 busy: BusyTrack,
1462 waiting: Vec<Waiting>,
1464}