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