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