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