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