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 if matches!(ui.class_name(id), Some("MediaPlayer" | "VideoPlayer")) && MEDIA_OPS.contains(&method) {
355 let mut media_cmd = obj.clone();
356 media_cmd.insert("op".into(), json!(method));
357 if let Some(seconds) = obj.get("args").and_then(Value::as_array).and_then(|a| a.first()).cloned() {
358 media_cmd.insert("seconds".into(), seconds);
359 }
360 return media(ui, &media_cmd);
361 }
362 let args: Vec<PropValue> = obj.get("args").and_then(Value::as_array).map(|a| a.iter().map(json_arg).collect()).unwrap_or_default();
363 let result = ui.invoke(id, method, &args)?;
364 if obj.get("ref").and_then(Value::as_bool) == Some(true) {
366 return Ok(match result.to_component() {
367 Ok(Some(c)) => json!({ "id": c.to_u64(), "name": ui.name(c).unwrap_or_default(), "class": ui.class_name(c).unwrap_or_default() }),
368 _ => Value::Null,
369 });
370 }
371 Ok(aylis_json::prop_to_json(ui, &result))
372 }
373 "click" => {
374 let id = target(ui, obj)?;
375 if !["modifiers", "x", "y", "button", "double"].iter().any(|k| obj.contains_key(*k)) {
377 ui.click(id);
378 return Ok(Value::Null);
379 }
380 let (root, at) = point_in(ui, id, obj.get("x"), obj.get("y"))?;
381 let mut event = aylis_core::PointerEvent { position: at, button: button(obj)?, modifiers: modifiers(obj)?, click_count: 1, ..Default::default() };
382 ui.pointer_move(root, event);
383 ui.pointer_down(root, event);
384 ui.pointer_up(root, event);
385 if obj.get("double").and_then(Value::as_bool) == Some(true) {
386 event.click_count = 2;
387 ui.pointer_down(root, event);
388 ui.pointer_up(root, event);
389 }
390 ui.process_events();
391 Ok(Value::Null)
392 }
393 "drag" => {
398 let from = resolve(ui, obj.get("from").ok_or("falta \"from\"")?)?;
399 let (root, start) = point_in(ui, from, obj.get("from_x"), obj.get("from_y"))?;
400 let steps = obj.get("steps").and_then(Value::as_u64).unwrap_or(10).clamp(1, 200) as usize;
401 let event = aylis_core::PointerEvent { position: start, button: button(obj)?, modifiers: modifiers(obj)?, click_count: 1, ..Default::default() };
402 let Some(to) = obj.get("to") else {
405 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}\""));
406 let (x, y) = (screen("screen_x")?, screen("screen_y")?);
407 start_drag_between_forms(ui, root, start, event)?;
408 ui.drag_over_form(root, None, aylis_core::PointF::default());
409 ui.set_screen_pointer(Some(aylis_core::ScreenPointer { x, y, scale: 1.0 }));
410 ui.pointer_up(root, aylis_core::PointerEvent { position: aylis_core::PointF::new(-1.0e6, -1.0e6), ..event });
411 ui.process_events();
412 return Ok(Value::Null);
413 };
414 let to = resolve(ui, to)?;
415 let (end_root, end) = point_in(ui, to, obj.get("to_x"), obj.get("to_y"))?;
416 if end_root != root {
419 start_drag_between_forms(ui, root, start, event)?;
420 for _ in 0..steps.min(3) {
421 ui.drag_over_form(root, Some(end_root), end);
422 ui.process_events();
423 }
424 ui.pointer_up(root, aylis_core::PointerEvent { position: aylis_core::PointF::new(-1.0e6, -1.0e6), ..event });
425 ui.process_events();
426 return Ok(Value::Null);
427 }
428 ui.pointer_move(root, event);
429 ui.pointer_down(root, event);
430 for i in 1..=steps {
431 let t = i as f32 / steps as f32;
432 let at = aylis_core::PointF::new(start.x + (end.x - start.x) * t, start.y + (end.y - start.y) * t);
433 ui.pointer_move(root, aylis_core::PointerEvent { position: at, ..event });
434 ui.process_events();
435 }
436 ui.pointer_up(root, aylis_core::PointerEvent { position: end, ..event });
437 ui.process_events();
438 Ok(Value::Null)
439 }
440 "drag_window" => {
443 let form = resolve(ui, obj.get("form").ok_or("falta \"form\"")?)?;
444 let form = ui.root_of(form);
445 let to = resolve(ui, obj.get("to").ok_or("falta \"to\"")?)?;
446 let (end_root, end) = point_in(ui, to, obj.get("to_x"), obj.get("to_y"))?;
447 if end_root == form {
448 return Err("drag_window: \"to\" está no próprio form".into());
449 }
450 ui.window_drag_over(form, Some((end_root, end)));
451 let received = ui.window_drag_end(form);
452 ui.process_events();
453 Ok(json!({ "received": received }))
454 }
455 "items" => {
457 let id = target(ui, obj)?;
458 let items: Vec<Value> = ui
459 .access_items(id)
460 .into_iter()
461 .map(|it| {
462 serde_json::json!({
463 "role": format!("{:?}", it.role).to_lowercase(),
464 "name": it.name,
465 "selected": it.selected,
466 "checked": it.checked,
467 "disabled": it.disabled,
468 "parent": it.parent,
469 "row": it.row,
470 "column": it.column,
471 "level": it.level,
472 "expanded": it.expanded,
473 })
474 })
475 .collect();
476 Ok(Value::Array(items))
477 }
478 "click_item" => {
481 use aylis_core::automation::ItemAction;
482 let id = target(ui, obj)?;
483 let action = match obj.get("action").and_then(Value::as_str).unwrap_or("click") {
484 "select" => ItemAction::Select,
485 "expand" => ItemAction::Expand,
486 "collapse" => ItemAction::Collapse,
487 _ => ItemAction::Click,
488 };
489 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())));
490 let done = match (named, obj.get("index").and_then(Value::as_u64)) {
491 (Some(i), _) => ui.access_action(id, i, action),
492 (None, Some(i)) => ui.access_action(id, i as usize, action),
493 _ => return Err("click_item: informe \"item\" (o texto) ou \"index\"".into()),
494 };
495 if done { Ok(Value::Null) } else { Err("item não encontrado ou sem ação".into()) }
496 }
497 "focus" => {
498 let id = target(ui, obj)?;
499 Ok(Value::Bool(ui.set_focus(id)))
500 }
501 "focused" => {
503 let form = target(ui, obj)?;
504 let root = ui.root_of(form);
505 Ok(ui.focused(root).and_then(|f| ui.name(f).map(|n| Value::String(n.to_string()))).unwrap_or(Value::Null))
506 }
507 "key" => {
511 let form = target(ui, obj)?;
512 let root = ui.root_of(form);
513 let (mut modifiers, key) = aylis_core::parse_shortcut(string(obj, "key")?).ok_or("tecla inválida (ex.: \"Enter\", \"Shift+Tab\", \"Ctrl+A\", \"Alt+S\")")?;
514 let extra = self::modifiers(obj)?;
515 modifiers.shift |= extra.shift;
516 modifiers.ctrl |= extra.ctrl;
517 modifiers.alt |= extra.alt;
518 modifiers.meta |= extra.meta;
519 let event = aylis_core::KeyEvent { key, modifiers, repeat: false };
520 ui.key_down(root, event);
521 ui.key_up(root, event);
522 Ok(Value::Null)
523 }
524 "type" => {
526 let form = target(ui, obj)?;
527 let root = ui.root_of(form);
528 ui.text_input(root, string(obj, "text")?);
529 Ok(Value::Null)
530 }
531 "focus_next" | "focus_prev" => {
533 let form = target(ui, obj)?;
534 let root = ui.root_of(form);
535 Ok(Value::Bool(ui.focus_next(root, cmd == "focus_next")))
536 }
537 "find" => {
538 let name = string(obj, "name")?;
539 Ok(ui.find(name).map_or(Value::Null, |id| Value::from(id.to_u64())))
540 }
541 "save" => {
542 let id = target(ui, obj)?;
543 aylis_json::save_value(ui, id).map_err(|e| e.to_string())
544 }
545 "theme" => {
546 let theme = match (obj.get("theme"), obj.get("name").and_then(Value::as_str)) {
547 (Some(theme), _) => aylis_json::theme_from_value(theme).map_err(|e| e.to_string())?,
548 (None, Some("dark")) => Theme::dark(),
549 (None, Some("light")) => Theme::light(),
550 _ => return Err("informe \"theme\" (JSON) ou \"name\": \"light\"/\"dark\"".into()),
551 };
552 ui.set_theme(theme);
553 Ok(Value::Null)
554 }
555 "locale" => {
556 let locale = match string(obj, "locale")? {
557 "pt-BR" | "pt_BR" | "pt" => LocaleInfo::pt_br(),
558 "en-US" | "en_US" | "en" => LocaleInfo::en_us(),
559 other => return Err(format!("idioma '{other}' não suportado (use pt-BR ou en-US)")),
560 };
561 ui.services_mut().locale = Some(Box::new(locale));
562 Ok(Value::Null)
563 }
564 "data" => data_command(ui, obj),
565 "batch" => {
566 let commands = obj.get("commands").and_then(Value::as_array).ok_or("falta \"commands\" (lista)")?;
567 Ok(Value::Array(
568 commands
569 .iter()
570 .map(|c| execute(ui, c).unwrap_or_else(|e| json!({ "error": e })))
571 .collect(),
572 ))
573 }
574 "create_form" => {
575 let name = string(obj, "name")?;
577 let fresh = obj.get("new").and_then(Value::as_bool).unwrap_or(false);
578 let id = if fresh { ui.create_form_instance(name) } else { ui.create_form(name) }.map_err(|e| e.to_string())?;
579 aylis_data::open_active(ui);
580 Ok(json!({ "id": id.to_u64(), "name": ui.name(id) }))
581 }
582 "show" => {
583 let id = target(ui, obj)?;
584 ui.show(id).map_err(|e| e.to_string())?;
585 Ok(Value::Null)
586 }
587 "show_modal" => {
588 let id = target(ui, obj)?;
589 let handler = obj.get("handler").and_then(Value::as_str).map(str::to_string);
590 let reply = if obj.get("wait").and_then(Value::as_bool) == Some(true) { defer_reply(ui) } else { None };
592 let waiting = ui.backend_busy();
594 if waiting {
595 ui.backend_waiting_user(true);
596 }
597 ui.show_modal(id, move |ui, result| {
598 if waiting {
599 ui.backend_waiting_user(false);
600 }
601 if let Some(reply) = reply {
602 send_reply(ui, reply, Ok(json!(result.name())));
603 }
604 if let Some(handler) = handler {
605 let args = EventArgs::Value(PropValue::Enum(result.name().to_string()));
606 ui.call_handler(id, "on_modal_result", &handler, &args);
607 }
608 })
609 .map_err(|e| e.to_string())?;
610 Ok(Value::Null)
611 }
612 "components" => {
616 let form = target(ui, obj)?;
617 let mut out = Vec::new();
618 let mut stack = ui.children(form).to_vec();
619 while let Some(id) = stack.pop() {
620 if ui.form_of(id) != form {
621 continue;
622 }
623 if let Some(name) = ui.name(id).filter(|n| !n.is_empty()) {
624 out.push(json!({ "name": name, "id": id.to_u64(), "class": ui.class_name(id).unwrap_or_default() }));
625 }
626 stack.extend(ui.children(id).iter().copied());
627 }
628 Ok(Value::Array(out))
629 }
630 "close" => match obj.get("target") {
631 Some(t) => {
632 let id = resolve(ui, t)?;
633 Ok(Value::Bool(ui.close(id)))
634 }
635 None => {
636 ui.request_close();
637 Ok(Value::Null)
638 }
639 },
640 "media" => media(ui, obj),
641 "tree" => {
642 let root = optional_target(ui, obj.get("target"))?;
643 let depth = obj.get("depth").and_then(Value::as_u64).map_or(usize::MAX, |d| d as usize);
645 let visible_only = obj.get("visible_only").and_then(Value::as_bool).unwrap_or(false);
646 Ok(inspect::tree_with(ui, root, depth, visible_only))
647 }
648 "props" => {
649 let id = target(ui, obj)?;
650 Ok(inspect::props(ui, id))
651 }
652 "rect" => {
654 let id = target(ui, obj)?;
655 ui.layout();
656 let abs = ui.absolute_rect(id).ok_or("componente sem posição")?;
657 let own = ui.bounds(id).ok_or("componente sem posição")?;
658 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] }))
659 }
660 "highlight" => {
661 let id = target(ui, obj)?;
662 inspect::highlight(ui, id)?;
663 Ok(Value::Null)
664 }
665 "tr" => Ok(Value::String(ui.tr(string(obj, "text")?))),
666 "set_language" => {
667 aylis_project::i18n::set_language(ui, string(obj, "language")?);
668 Ok(Value::Null)
669 }
670 "toast" => {
671 aylis_controls::toast(ui, string(obj, "text")?);
672 Ok(Value::Null)
673 }
674 "profile_begin" => {
677 let name = string(obj, "name")?.to_string();
678 PROFILE_MARKS.with(|m| m.borrow_mut().push((name, aylis_core::profile::now())));
679 Ok(Value::Null)
680 }
681 "profile_end" => {
682 if let Some((name, start)) = PROFILE_MARKS.with(|m| m.borrow_mut().pop()) {
683 aylis_core::profile::record(aylis_core::profile::Lane::Mark, &name, start, (aylis_core::profile::now() - start).max(0.0));
684 }
685 Ok(Value::Null)
686 }
687 "message_dlg" => {
688 use aylis_controls::DlgKind;
689 let text = string(obj, "text")?.to_string();
690 let kind = match obj.get("kind").and_then(Value::as_str).unwrap_or("information") {
691 "warning" => DlgKind::Warning,
692 "error" => DlgKind::Error,
693 "confirmation" => DlgKind::Confirmation,
694 _ => DlgKind::Information,
695 };
696 let buttons: Vec<ModalResult> = obj
697 .get("buttons")
698 .and_then(Value::as_array)
699 .map(|a| a.iter().filter_map(|b| b.as_str().and_then(ModalResult::from_name)).collect())
700 .unwrap_or_default();
701 let handler = obj.get("handler").and_then(Value::as_str).map(str::to_string);
702 let reply = if obj.get("wait").and_then(Value::as_bool) == Some(true) { defer_reply(ui) } else { None };
703 let waiting = ui.backend_busy();
704 if waiting {
705 ui.backend_waiting_user(true);
706 }
707 let form = aylis_controls::message_dlg(ui, &text, kind, &buttons, move |ui, result| {
708 if waiting {
709 ui.backend_waiting_user(false);
710 }
711 if let Some(reply) = reply {
712 send_reply(ui, reply, Ok(json!(result.name())));
713 }
714 if let (Some(handler), Some(main)) = (handler, ui.main_form()) {
715 let args = EventArgs::Value(PropValue::Enum(result.name().to_string()));
716 ui.call_handler(main, "on_modal_result", &handler, &args);
717 }
718 });
719 Ok(json!(ui.path_of(form)))
720 }
721 "execute" => {
722 let id = target(ui, obj)?;
723 aylis_controls::OpenDialog::execute(ui, id);
724 Ok(Value::Null)
725 }
726 "hello" => hello(ui, obj),
727 "exception" => {
730 let message = string(obj, "message")?.to_string();
731 let path = obj.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
732 let event = obj.get("handler").and_then(Value::as_str).unwrap_or_default().to_string();
733 ui.raise_exception(aylis_core::Exception { message, path, event });
734 Ok(Value::Null)
735 }
736 "done" => {
740 let seq = obj.get("seq").and_then(Value::as_u64).ok_or("falta 'seq'")?;
741 backend_done(ui, seq);
742 Ok(Value::Null)
743 }
744 "answer" => {
745 let token = obj.get("ask").and_then(Value::as_u64).ok_or("falta 'ask' (o número da pergunta)")?;
746 let answer = match obj.get("error").and_then(Value::as_str) {
747 Some(message) => aylis_core::Answer::Refused(message.to_string()),
748 None => {
749 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();
750 aylis_core::Answer::Accepted(values)
751 }
752 };
753 ui.answer(token, answer);
754 flush_waiting_data(ui);
755 Ok(Value::Null)
756 }
757 "modal_result" => {
758 let id = target(ui, obj)?;
759 let name = string(obj, "result")?;
760 let result = ModalResult::from_name(name).ok_or_else(|| format!("resultado '{name}' inválido (use {})", ModalResult::NAMES.join(", ")))?;
761 ui.set_modal_result(id, result);
762 Ok(Value::Null)
763 }
764 other => Err(format!("comando desconhecido '{other}'")),
765 }
766}
767
768const MEDIA_OPS: &[&str] = &["play", "pause", "stop", "seek", "position", "duration", "playing", "ready"];
770
771fn media(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
773 use aylis_media::{MediaPlayer, VideoPlayer};
774 let id = target(ui, obj)?;
775 let op = string(obj, "op")?;
776 let video = ui.get::<VideoPlayer>(id).is_some();
777 if !video && ui.get::<MediaPlayer>(id).is_none() {
778 return Err("o alvo não é um MediaPlayer nem um VideoPlayer".into());
779 }
780 let seconds = obj.get("seconds").and_then(Value::as_f64).unwrap_or(0.0);
781 Ok(match (op, video) {
782 ("play", true) => VideoPlayer::play(ui, id).map(|_| Value::Null)?,
783 ("play", false) => MediaPlayer::play(ui, id).map(|_| Value::Null)?,
784 ("pause", true) => {
785 VideoPlayer::pause(ui, id);
786 Value::Null
787 }
788 ("pause", false) => {
789 MediaPlayer::pause(ui, id);
790 Value::Null
791 }
792 ("stop", true) => {
793 VideoPlayer::stop(ui, id);
794 Value::Null
795 }
796 ("stop", false) => {
797 MediaPlayer::stop(ui, id);
798 Value::Null
799 }
800 ("seek", true) => {
801 VideoPlayer::seek(ui, id, seconds);
802 Value::Null
803 }
804 ("seek", false) => {
805 MediaPlayer::seek(ui, id, seconds);
806 Value::Null
807 }
808 ("position", true) => json!(VideoPlayer::position(ui, id)),
809 ("position", false) => json!(MediaPlayer::position(ui, id)),
810 ("duration", true) => json!(VideoPlayer::duration(ui, id)),
811 ("duration", false) => json!(MediaPlayer::duration(ui, id)),
812 ("playing", true) => json!(VideoPlayer::is_playing(ui, id)),
813 ("playing", false) => json!(MediaPlayer::is_playing(ui, id)),
814 ("ready", true) => json!(VideoPlayer::is_ready(ui, id)),
815 ("ready", false) => json!(MediaPlayer::is_ready(ui, id)),
816 (other, _) => return Err(format!("operação de mídia desconhecida '{other}'")),
817 })
818}
819
820fn string<'a>(obj: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
821 obj.get(key).and_then(Value::as_str).ok_or_else(|| format!("falta \"{key}\" (texto)"))
822}
823
824pub fn resolve(ui: &Ui, value: &Value) -> Result<ComponentId, String> {
826 match value {
827 Value::String(name) if !name.is_empty() && !name.contains('.') => {
830 let found = named_everywhere(ui, name);
831 match found.as_slice() {
832 [one] => Ok(*one),
833 [] => ui.find_path(name).ok_or_else(|| format!("componente '{name}' não encontrado")),
834 many => Err(format!(
835 "o nome '{name}' está em {} lugares; use o caminho ou o id: {}",
836 many.len(),
837 many.iter().map(|&id| format!("{} (id {})", ui.path_of(id), id.to_u64())).collect::<Vec<_>>().join(", ")
838 )),
839 }
840 }
841 Value::String(name) => ui.find_path(name).ok_or_else(|| format!("componente '{name}' não encontrado")),
842 Value::Number(n) => {
843 let id = ComponentId::from_u64(n.as_u64().ok_or("id inválido")?);
844 if ui.contains(id) { Ok(id) } else { Err(format!("componente {n} não existe (ou foi liberado)")) }
845 }
846 other => Err(format!("alvo inválido: {other} (use o nome ou o id)")),
847 }
848}
849
850fn named_everywhere(ui: &Ui, name: &str) -> Vec<ComponentId> {
852 let mut found = Vec::new();
853 let mut stack: Vec<ComponentId> = ui.roots().to_vec();
854 while let Some(id) = stack.pop() {
855 if ui.name(id).is_some_and(|n| n.eq_ignore_ascii_case(name)) {
856 found.push(id);
857 }
858 stack.extend(ui.children(id).iter().copied());
859 }
860 found
861}
862
863fn start_drag_between_forms(ui: &mut Ui, root: ComponentId, start: aylis_core::PointF, event: aylis_core::PointerEvent) -> Result<(), String> {
868 ui.pointer_move(root, event);
869 ui.pointer_down(root, event);
870 for i in 1..=6 {
872 let at = aylis_core::PointF::new(start.x + 6.0 * i as f32, start.y + 12.0 * i as f32);
873 ui.pointer_move(root, aylis_core::PointerEvent { position: at, ..event });
874 ui.process_events();
875 }
876 if !ui.dragging(root) {
877 ui.pointer_up(root, event);
878 return Err("drag: o arrasto não começou (o componente em \"from\" não arrasta)".into());
879 }
880 Ok(())
881}
882
883fn point_in(ui: &mut Ui, id: ComponentId, x: Option<&Value>, y: Option<&Value>) -> Result<(ComponentId, aylis_core::PointF), String> {
884 ui.update_layout();
885 let rect = ui.absolute_rect(id).ok_or("o componente não está numa tela")?;
886 let coord = |v: Option<&Value>, size: f32, name: &str| -> Result<f32, String> {
887 match v {
888 None | Some(Value::Null) => Ok(size / 2.0),
889 Some(v) => v.as_f64().map(|n| n as f32).ok_or(format!("\"{name}\" tem de ser um número")),
890 }
891 };
892 let at = aylis_core::PointF::new(rect.x + coord(x, rect.width, "x")?, rect.y + coord(y, rect.height, "y")?);
893 Ok((ui.root_of(id), at))
894}
895
896fn modifiers(obj: &Map<String, Value>) -> Result<aylis_core::Modifiers, String> {
899 let names: Vec<String> = match obj.get("modifiers") {
900 None | Some(Value::Null) => return Ok(aylis_core::Modifiers::default()),
901 Some(Value::String(s)) => s.split('+').map(|p| p.trim().to_lowercase()).filter(|p| !p.is_empty()).collect(),
902 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<_, _>>()?,
903 Some(_) => return Err("\"modifiers\": \"Ctrl+Shift\" ou [\"ctrl\", \"shift\"]".into()),
904 };
905 let mut m = aylis_core::Modifiers::default();
906 for name in names {
907 match name.as_str() {
908 "ctrl" | "control" => m.ctrl = true,
909 "shift" => m.shift = true,
910 "alt" => m.alt = true,
911 "meta" | "cmd" | "win" => m.meta = true,
912 other => return Err(format!("tecla modificadora desconhecida: {other} (use ctrl, shift, alt, meta)")),
913 }
914 }
915 Ok(m)
916}
917
918fn button(obj: &Map<String, Value>) -> Result<PointerButton, String> {
920 match obj.get("button").and_then(Value::as_str).unwrap_or("left") {
921 "left" | "primary" => Ok(PointerButton::Primary),
922 "right" | "secondary" => Ok(PointerButton::Secondary),
923 "middle" => Ok(PointerButton::Middle),
924 other => Err(format!("botão desconhecido: {other} (use left, right, middle)")),
925 }
926}
927
928fn target(ui: &Ui, obj: &Map<String, Value>) -> Result<ComponentId, String> {
929 resolve(ui, obj.get("target").ok_or("falta \"target\"")?)
930}
931
932fn optional_target(ui: &Ui, value: Option<&Value>) -> Result<Option<ComponentId>, String> {
933 match value {
934 None | Some(Value::Null) => Ok(None),
935 Some(v) => resolve(ui, v).map(Some),
936 }
937}
938
939fn json_arg(v: &Value) -> PropValue {
941 match v {
942 Value::Bool(b) => PropValue::Bool(*b),
943 Value::Number(n) => n.as_i64().map(PropValue::Int).unwrap_or_else(|| PropValue::Float(n.as_f64().unwrap_or(0.0))),
944 Value::String(s) => PropValue::String(s.clone()),
945 Value::Null => PropValue::Null,
946 other => PropValue::String(other.to_string()),
947 }
948}
949
950fn get(ui: &Ui, id: ComponentId, name: &str) -> Result<Value, String> {
951 let value = ui.get_prop(id, name).map_err(|e| e.to_string())?;
952 Ok(aylis_json::prop_to_json(ui, &value))
953}
954
955fn json_key(json: &Value) -> aylis_data::Value {
959 match json {
960 Value::Null => aylis_data::Value::Null,
961 Value::Bool(b) => aylis_data::Value::Bool(*b),
962 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))),
963 Value::String(s) => aylis_data::Value::String(s.clone()),
964 other => aylis_data::Value::String(other.to_string()),
965 }
966}
967
968fn data(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
969 let id = target(ui, obj)?;
970 if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
971 return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
972 }
973 let op = string(obj, "op")?;
974 let mut ds = data_set(ui, id);
975 let ok = |r: aylis_data::DataResult| r.map(|_| Value::Null).map_err(|e| e.message);
976 match op {
977 "load" => ok(ds.load_json(obj.get("rows").ok_or("falta \"rows\"")?)),
978 "load_columns" => ok(ds.load_columns(obj.get("fields").ok_or("falta \"fields\"")?, obj.get("columns").ok_or("falta \"columns\"")?)),
980 "append" => {
981 let more = obj.get("has_more").and_then(Value::as_bool).unwrap_or(false);
982 ok(ds.append_json(obj.get("rows").ok_or("falta \"rows\"")?, more))
983 }
984 "reconcile" => {
986 let results = obj.get("results").ok_or("falta \"results\"")?;
987 let results = ds.parse_results(&json!({ "results": results }).to_string()).map_err(|e| e.message)?;
988 let rejected: Vec<&str> = results.iter().filter_map(|r| r.error.as_deref()).collect();
989 let rejected = json!({ "rejected": rejected });
990 let _ = ds.reconcile(&results);
991 Ok(rejected)
992 }
993 "first" => ok(ds.first()),
994 "prior" => ok(ds.prior()),
995 "next" => ok(ds.next()),
996 "last" => ok(ds.last()),
997 "move_to" => ok(ds.move_to(obj.get("index").and_then(Value::as_u64).ok_or("falta \"index\"")? as usize)),
998 "edit" => ok(ds.edit()),
999 "insert" => ok(ds.insert()),
1000 "append_record" => ok(ds.append()),
1001 "post" => {
1003 ok(ds.post())?;
1004 if ds.is_asking() || ds.awaiting_text() {
1005 if let Some(reply) = defer_reply(ds.ui()) {
1006 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "post".into(), replay: None });
1007 }
1008 }
1009 Ok(Value::Null)
1010 }
1011 "cancel" => ok(ds.cancel()),
1012 "delete" => {
1013 ok(ds.delete())?;
1014 if ds.is_asking() {
1015 if let Some(reply) = defer_reply(ds.ui()) {
1016 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "delete".into(), replay: None });
1017 }
1018 }
1019 Ok(Value::Null)
1020 }
1021 "apply" => {
1024 let result = ds.apply_updates();
1025 if ds.is_applying() {
1026 if let Some(reply) = defer_reply(ds.ui()) {
1027 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "apply".into(), replay: None });
1028 }
1029 return Ok(Value::Null);
1030 }
1031 match result {
1032 Err(e) if ds.apply_errors() == 0 => Err(e.message),
1033 _ => Ok(json!(ds.apply_errors())),
1034 }
1035 }
1036 "cancel_updates" => ok(ds.cancel_updates()),
1037 "refresh" => {
1038 ds.refresh_links();
1039 Ok(Value::Null)
1040 }
1041 "set_has_more" => ok(ds.set_has_more(obj.get("value").and_then(Value::as_bool).unwrap_or(false))),
1042 "set_value" => {
1043 let field = string(obj, "field")?;
1044 let json = obj.get("value").cloned().unwrap_or(Value::Null);
1045 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
1046 ok(ds.set_value(field, value))
1047 }
1048 "set_text" => {
1049 let field = string(obj, "field")?;
1050 ok(ds.set_text(field, string(obj, "text")?))
1051 }
1052 "set_values" => {
1055 let values = obj.get("values").and_then(Value::as_object).ok_or("falta \"values\" (objeto)")?;
1056 if !ds.state().is_editing() {
1057 ds.edit().map_err(|e| e.message)?;
1058 }
1059 for (field, json) in values {
1060 let value = json_to_value(json, ds.view().field(field).map_err(|e| e.message)?)?;
1061 ds.set_value(field, value).map_err(|e| format!("{field}: {}", e.message))?;
1062 }
1063 Ok(Value::Null)
1064 }
1065 "locate" => {
1066 let field = string(obj, "field")?;
1067 let json = obj.get("value").cloned().unwrap_or(Value::Null);
1068 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
1069 ds.locate(field, value).map(Value::Bool).map_err(|e| e.message)
1070 }
1071 "set_filter" => ok(ds.set_filter(obj.get("filter").and_then(Value::as_str).unwrap_or_default())),
1072 "set_index" => ok(ds.set_index(obj.get("index").and_then(Value::as_str).unwrap_or_default())),
1073 "set_index_name" => ok(ds.set_index_name(obj.get("name").and_then(Value::as_str).unwrap_or_default())),
1074 "set_param" => {
1076 let name = string(obj, "name")?;
1077 ok(ds.set_param(name, json_key(obj.get("value").unwrap_or(&Value::Null))))
1078 }
1079 "revert_record" => ok(ds.revert_record()),
1080 "field_texts" => {
1082 let field = string(obj, "field")?;
1083 let pairs = obj.get("texts").and_then(Value::as_array).ok_or("falta \"texts\" (lista de [valor, texto])")?;
1084 let texts = pairs
1085 .iter()
1086 .filter_map(|p| {
1087 let p = p.as_array()?;
1088 Some((json_key(p.first()?), p.get(1)?.as_str().unwrap_or_default().to_string()))
1089 })
1090 .collect();
1091 ok(ds.set_field_texts(field, texts))
1092 }
1093 "field_error" => {
1096 let field = string(obj, "field")?;
1097 let message = obj.get("message").and_then(Value::as_str).map(str::to_string);
1098 ok(ds.set_field_error(field, message))
1099 }
1100 "lookup" => {
1101 let key_fields = string(obj, "key_fields")?;
1102 let result = string(obj, "result_field")?;
1103 let keys: Vec<aylis_data::Value> = match obj.get("keys") {
1104 Some(Value::Array(list)) => list.iter().map(json_key).collect(),
1105 Some(k) => vec![json_key(k)],
1106 None => return Err("falta \"keys\"".into()),
1107 };
1108 Ok(ds.view().lookup(key_fields, &keys, result).map(|v| value_to_json(&v)).unwrap_or(Value::Null))
1109 }
1110 "value" => ds.value(string(obj, "field")?).map(|v| value_to_json(&v)).map_err(|e| e.message),
1111 "text" => ds.text(string(obj, "field")?).map(Value::String).map_err(|e| e.message),
1112 "record" => record(&ds),
1113 "info" => {
1114 let v = ds.view();
1115 Ok(json!({
1116 "state": format!("{:?}", v.state()).to_lowercase(),
1117 "rec_no": v.rec_no(),
1118 "count": v.record_count(),
1119 "changes": v.change_count(),
1120 "has_more": v.has_more(),
1121 "bof": v.bof(),
1122 "eof": v.eof(),
1123 "status": v.update_status().map(|s| format!("{s:?}").to_lowercase()),
1125 }))
1126 }
1127 "delta" => {
1128 let changes = ds.delta_with_details().map_err(|e| e.message)?;
1129 let name = ds.ui().name(id).unwrap_or_default().to_string();
1130 serde_json::from_str(&aylis_data::json::delta_to_json(&name, &changes)).map_err(|e| e.to_string())
1131 }
1132 other => Err(format!("operação de dados desconhecida '{other}'")),
1133 }
1134}
1135
1136fn answer_value(v: &Value) -> PropValue {
1138 match v {
1139 Value::Bool(b) => PropValue::Bool(*b),
1140 Value::Number(n) if n.is_i64() => PropValue::Int(n.as_i64().unwrap_or_default()),
1141 Value::Number(n) => PropValue::Float(n.as_f64().unwrap_or_default()),
1142 Value::String(s) => PropValue::String(s.clone()),
1143 Value::Null => PropValue::Null,
1144 other => PropValue::String(other.to_string()),
1145 }
1146}
1147
1148fn record(ds: &DataSet<'_>) -> Result<Value, String> {
1149 let v = ds.view();
1150 let mut out = Map::new();
1151 for name in v.field_names() {
1152 out.insert(name.clone(), value_to_json(&v.value(&name).map_err(|e| e.message)?));
1153 }
1154 Ok(Value::Object(out))
1155}
1156
1157pub fn event_to_json(ui: &Ui, sender: ComponentId, event: &str, handler: &str, args: &EventArgs) -> Value {
1161 let mut message = json!({
1162 "event": event,
1163 "handler": handler,
1164 "form": ui.form_class(ui.form_of(sender)).or_else(|| ui.name(ui.form_of(sender))).unwrap_or_default(),
1167 "form_id": ui.form_of(sender).to_u64(),
1169 "sender": {
1170 "id": sender.to_u64(),
1171 "name": ui.name(sender).unwrap_or_default(),
1172 "path": ui.path_of(sender),
1173 "class": ui.class_name(sender).unwrap_or_default(),
1174 },
1175 "args": args_to_json(ui, args),
1176 });
1177 if event == "on_click"
1180 && let Some(p) = ui.click_pointer()
1181 {
1182 message["pointer"] = pointer_to_json(&p);
1183 }
1184 let info = ui.component(sender).map(|c| c.event_info(event)).unwrap_or_default();
1187 if !info.is_empty() {
1188 message["info"] = Value::Object(info.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect());
1189 }
1190 message
1191}
1192
1193fn button_name(button: PointerButton) -> &'static str {
1194 match button {
1195 PointerButton::Primary => "primary",
1196 PointerButton::Secondary => "secondary",
1197 PointerButton::Middle => "middle",
1198 PointerButton::Back => "back",
1199 PointerButton::Forward => "forward",
1200 }
1201}
1202
1203fn pointer_to_json(p: &aylis_core::ClickPointer) -> Value {
1205 let m = p.modifiers;
1206 let modifiers: Vec<&str> =
1207 [(m.ctrl, "ctrl"), (m.shift, "shift"), (m.alt, "alt"), (m.meta, "meta")].into_iter().filter(|(on, _)| *on).map(|(_, n)| n).collect();
1208 json!({
1209 "x": p.position.x,
1210 "y": p.position.y,
1211 "form_x": p.form_position.x,
1212 "form_y": p.form_position.y,
1213 "button": button_name(p.button),
1214 "modifiers": modifiers,
1215 "kind": match p.kind {
1216 aylis_core::PointerKind::Mouse => "mouse",
1217 aylis_core::PointerKind::Touch => "touch",
1218 aylis_core::PointerKind::Pen => "pen",
1219 },
1220 "clicks": p.click_count,
1221 })
1222}
1223
1224fn args_to_json(ui: &Ui, args: &EventArgs) -> Value {
1225 match args {
1226 EventArgs::None => Value::Null,
1227 EventArgs::Pointer(p) => json!({
1228 "x": p.position.x,
1229 "y": p.position.y,
1230 "button": button_name(p.button),
1231 "clicks": p.click_count,
1232 }),
1233 EventArgs::Wheel(w) => json!({ "x": w.position.x, "y": w.position.y, "dx": w.delta.x, "dy": w.delta.y }),
1234 EventArgs::Gesture(g) => json!({
1235 "phase": match g.phase { aylis_core::GesturePhase::Begin => "begin", aylis_core::GesturePhase::Update => "update", aylis_core::GesturePhase::End => "end" },
1236 "x": g.center.x, "y": g.center.y, "scale": g.scale, "delta_scale": g.delta_scale,
1237 "rotation": g.rotation, "delta_rotation": g.delta_rotation, "pan_x": g.pan.x, "pan_y": g.pan.y,
1238 }),
1239 EventArgs::Swipe(s) => json!({
1240 "direction": s.direction.name(), "x": s.start.x, "y": s.start.y,
1241 "dx": s.distance.x, "dy": s.distance.y, "vx": s.velocity.x, "vy": s.velocity.y,
1242 }),
1243 EventArgs::Key(k) => json!({
1244 "key": key_name(k.key),
1245 "ctrl": k.modifiers.ctrl,
1246 "shift": k.modifiers.shift,
1247 "alt": k.modifiers.alt,
1248 }),
1249 EventArgs::Text(text) => match serde_json::from_str::<Value>(text) {
1251 Ok(v @ (Value::Object(_) | Value::Array(_))) => v,
1252 _ => Value::String(text.clone()),
1253 },
1254 EventArgs::Value(PropValue::Component(c)) => c.map_or(Value::Null, |id| Value::from(id.to_u64())),
1255 EventArgs::Value(v) => aylis_json::prop_to_json(ui, v),
1256 EventArgs::Intercept(i) => {
1259 let sender = i.sender.map_or(Value::Null, |id| {
1260 json!({
1261 "id": id.to_u64(),
1262 "name": ui.name(id).unwrap_or_default(),
1263 "path": ui.path_of(id),
1264 "class": ui.class_name(id).unwrap_or_default(),
1265 })
1266 });
1267 json!({
1268 "form": i.form.and_then(|f| ui.name(f)).unwrap_or_default(),
1269 "form_id": i.form.map_or(Value::Null, |f| Value::from(f.to_u64())),
1270 "sender": sender,
1271 "event": i.event,
1272 "handler": i.handler,
1273 "args": args_to_json(ui, &i.args),
1274 })
1275 }
1276 }
1277}
1278
1279fn key_name(key: Key) -> String {
1280 match key {
1281 Key::Char(c) => c.to_string(),
1282 Key::F(n) => format!("f{n}"),
1283 other => format!("{other:?}").to_lowercase(),
1284 }
1285}
1286
1287pub fn forward_events(ui: &mut Ui, send: impl Fn(&mut Ui, Value) + 'static) {
1290 let send: std::rc::Rc<dyn Fn(&mut Ui, Value)> = std::rc::Rc::new(send);
1291 ui.extension::<Remote>().sink = Some(send.clone());
1293 ui.on_forms_freed(|ui, forms| {
1295 let ids: Vec<Value> = forms.iter().map(|f| Value::from(f.to_u64())).collect();
1296 send_event(ui, None, json!({ "event": "__freed", "forms": ids }));
1297 });
1298 ui.set_event_sink(move |ui, sender, event, handler, args| {
1299 let mut json = event_to_json(ui, sender, event, handler, args);
1300 if ui.asking() {
1303 json["ask"] = Value::from(ui.defer_question());
1304 }
1305 let key = (sender.to_u64(), event.to_string());
1307 let joined = {
1308 let coalesce = coalesces(ui, sender, event);
1309 let b = &mut ui.extension::<Remote>().busy;
1310 if b.tracking && json.get("ask").is_none() && b.running.values().any(|k| *k == key) && coalesce {
1311 b.latest.insert(key.clone(), json.clone());
1312 true
1313 } else {
1314 false
1315 }
1316 };
1317 if !joined {
1318 send_event(ui, Some(sender), json);
1319 }
1320 });
1321}
1322
1323fn defer_reply(ui: &Ui) -> Option<Value> {
1326 if ui.extension_ref::<Remote>().is_none_or(|r| r.sink.is_none()) {
1327 return None;
1328 }
1329 CURRENT_ID.with(|c| c.borrow_mut().take())
1330}
1331
1332fn send_reply(ui: &mut Ui, id: Value, result: Result<Value, String>) {
1334 let message = match result {
1335 Ok(result) => json!({ "id": id, "result": result }),
1336 Err(error) => json!({ "id": id, "error": error }),
1337 };
1338 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1339 sink(ui, message);
1340 }
1341}
1342
1343fn flush_waiting_data(ui: &mut Ui) {
1346 let waiting = std::mem::take(&mut ui.extension::<Remote>().waiting);
1347 let mut still = Vec::new();
1348 for w in waiting {
1349 let ds = data_set(ui, w.ds);
1350 if ds.is_asking() || ds.awaiting_text() {
1351 still.push(w);
1352 continue;
1353 }
1354 let editing = ds.state().is_editing();
1355 let result = match w.replay {
1356 Some(_) if editing => Err("a gravação foi recusada".to_string()),
1358 Some(command) => {
1359 let had_id = w.reply.is_some();
1361 CURRENT_ID.with(|c| *c.borrow_mut() = w.reply.clone());
1362 let result = data_command(ui, &command);
1363 if had_id && CURRENT_ID.with(|c| c.borrow_mut().take()).is_none() {
1364 continue;
1365 }
1366 result
1367 }
1368 None if w.op == "post" && editing => Err("a gravação foi recusada".to_string()),
1369 None if w.op == "apply" => match ds.apply_errors() {
1370 usize::MAX => Err("a gravação foi recusada".to_string()),
1371 n => Ok(json!(n)),
1372 },
1373 None => Ok(Value::Null),
1374 };
1375 match (w.reply, result) {
1376 (Some(reply), result) => send_reply(ui, reply, result),
1377 (None, Err(error)) => {
1379 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1380 sink(ui, json!({ "event": "error", "cmd": "data", "message": error }));
1381 }
1382 }
1383 (None, Ok(_)) => {}
1384 }
1385 }
1386 ui.extension::<Remote>().waiting.extend(still);
1387}
1388
1389struct Waiting {
1391 reply: Option<Value>,
1393 ds: ComponentId,
1394 op: String,
1395 replay: Option<Map<String, Value>>,
1397}
1398
1399fn data_command(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
1402 match data(ui, obj) {
1403 Err(error) if error == aylis_data::DataError::waiting().message => {
1404 let ds = target(ui, obj)?;
1405 let reply = defer_reply(ui);
1406 let op = string(obj, "op")?.to_string();
1407 ui.extension::<Remote>().waiting.push(Waiting { reply, ds, op, replay: Some(obj.clone()) });
1408 Ok(Value::Null)
1409 }
1410 other => other,
1411 }
1412}
1413
1414#[derive(Default)]
1416struct BusyTrack {
1417 tracking: bool,
1420 next: u64,
1421 running: std::collections::HashMap<u64, (u64, String)>,
1423 latest: std::collections::HashMap<(u64, String), Value>,
1425}
1426
1427pub fn coalesces(ui: &Ui, sender: ComponentId, event: &str) -> bool {
1431 aylis_core::question::COALESCED_EVENTS.contains(&event)
1432 || (event == "on_change" && matches!(ui.class_name(sender), Some("TrackBar" | "Slider" | "RangeSlider" | "ScrollBar" | "Knob" | "Gauge")))
1433}
1434
1435fn backend_done(ui: &mut Ui, seq: u64) {
1437 let next = {
1438 let b = &mut ui.extension::<Remote>().busy;
1439 b.running.remove(&seq).and_then(|key| b.latest.remove(&key))
1440 };
1441 ui.backend_done(seq);
1442 if let Some(json) = next {
1443 let sender = json["sender"]["id"].as_u64().map(ComponentId::from_u64);
1444 send_event(ui, sender, json);
1445 }
1446}
1447
1448fn send_event(ui: &mut Ui, sender: Option<ComponentId>, mut json: Value) {
1450 if ui.extension::<Remote>().busy.tracking {
1451 let seq = {
1452 let b = &mut ui.extension::<Remote>().busy;
1453 b.next += 1;
1454 b.next
1455 };
1456 json["seq"] = Value::from(seq);
1457 if let Some(sender) = sender {
1458 ui.backend_event_sent(seq, sender);
1459 let event = json["event"].as_str().unwrap_or_default().to_string();
1460 if coalesces(ui, sender, &event) {
1461 ui.extension::<Remote>().busy.running.insert(seq, (sender.to_u64(), event));
1462 }
1463 }
1464 }
1465 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1466 sink(ui, json);
1467 }
1468}
1469
1470#[derive(Default)]
1473struct Remote {
1474 sink: Option<std::rc::Rc<dyn Fn(&mut Ui, Value)>>,
1476 busy: BusyTrack,
1477 waiting: Vec<Waiting>,
1479}