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