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