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 Ok(inspect::tree(ui, root))
517 }
518 "props" => {
519 let id = target(ui, obj)?;
520 Ok(inspect::props(ui, id))
521 }
522 "highlight" => {
523 let id = target(ui, obj)?;
524 inspect::highlight(ui, id)?;
525 Ok(Value::Null)
526 }
527 "tr" => Ok(Value::String(ui.tr(string(obj, "text")?))),
528 "set_language" => {
529 aylis_project::i18n::set_language(ui, string(obj, "language")?);
530 Ok(Value::Null)
531 }
532 "toast" => {
533 aylis_controls::toast(ui, string(obj, "text")?);
534 Ok(Value::Null)
535 }
536 "profile_begin" => {
539 let name = string(obj, "name")?.to_string();
540 PROFILE_MARKS.with(|m| m.borrow_mut().push((name, aylis_core::profile::now())));
541 Ok(Value::Null)
542 }
543 "profile_end" => {
544 if let Some((name, start)) = PROFILE_MARKS.with(|m| m.borrow_mut().pop()) {
545 aylis_core::profile::record(aylis_core::profile::Lane::Mark, &name, start, (aylis_core::profile::now() - start).max(0.0));
546 }
547 Ok(Value::Null)
548 }
549 "message_dlg" => {
550 use aylis_controls::DlgKind;
551 let text = string(obj, "text")?.to_string();
552 let kind = match obj.get("kind").and_then(Value::as_str).unwrap_or("information") {
553 "warning" => DlgKind::Warning,
554 "error" => DlgKind::Error,
555 "confirmation" => DlgKind::Confirmation,
556 _ => DlgKind::Information,
557 };
558 let buttons: Vec<ModalResult> = obj
559 .get("buttons")
560 .and_then(Value::as_array)
561 .map(|a| a.iter().filter_map(|b| b.as_str().and_then(ModalResult::from_name)).collect())
562 .unwrap_or_default();
563 let handler = obj.get("handler").and_then(Value::as_str).map(str::to_string);
564 let reply = if obj.get("wait").and_then(Value::as_bool) == Some(true) { defer_reply(ui) } else { None };
565 let waiting = ui.backend_busy();
566 if waiting {
567 ui.backend_waiting_user(true);
568 }
569 let form = aylis_controls::message_dlg(ui, &text, kind, &buttons, move |ui, result| {
570 if waiting {
571 ui.backend_waiting_user(false);
572 }
573 if let Some(reply) = reply {
574 send_reply(ui, reply, Ok(json!(result.name())));
575 }
576 if let (Some(handler), Some(main)) = (handler, ui.main_form()) {
577 let args = EventArgs::Value(PropValue::Enum(result.name().to_string()));
578 ui.call_handler(main, "on_modal_result", &handler, &args);
579 }
580 });
581 Ok(json!(ui.path_of(form)))
582 }
583 "execute" => {
584 let id = target(ui, obj)?;
585 aylis_controls::OpenDialog::execute(ui, id);
586 Ok(Value::Null)
587 }
588 "hello" => hello(ui, obj),
589 "exception" => {
592 let message = string(obj, "message")?.to_string();
593 let path = obj.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
594 let event = obj.get("handler").and_then(Value::as_str).unwrap_or_default().to_string();
595 ui.raise_exception(aylis_core::Exception { message, path, event });
596 Ok(Value::Null)
597 }
598 "done" => {
602 let seq = obj.get("seq").and_then(Value::as_u64).ok_or("falta 'seq'")?;
603 backend_done(ui, seq);
604 Ok(Value::Null)
605 }
606 "answer" => {
607 let token = obj.get("ask").and_then(Value::as_u64).ok_or("falta 'ask' (o número da pergunta)")?;
608 let answer = match obj.get("error").and_then(Value::as_str) {
609 Some(message) => aylis_core::Answer::Refused(message.to_string()),
610 None => {
611 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();
612 aylis_core::Answer::Accepted(values)
613 }
614 };
615 ui.answer(token, answer);
616 flush_waiting_data(ui);
617 Ok(Value::Null)
618 }
619 "modal_result" => {
620 let id = target(ui, obj)?;
621 let name = string(obj, "result")?;
622 let result = ModalResult::from_name(name).ok_or_else(|| format!("resultado '{name}' inválido (use {})", ModalResult::NAMES.join(", ")))?;
623 ui.set_modal_result(id, result);
624 Ok(Value::Null)
625 }
626 other => Err(format!("comando desconhecido '{other}'")),
627 }
628}
629
630fn media(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
632 use aylis_media::{MediaPlayer, VideoPlayer};
633 let id = target(ui, obj)?;
634 let op = string(obj, "op")?;
635 let video = ui.get::<VideoPlayer>(id).is_some();
636 if !video && ui.get::<MediaPlayer>(id).is_none() {
637 return Err("o alvo não é um MediaPlayer nem um VideoPlayer".into());
638 }
639 let seconds = obj.get("seconds").and_then(Value::as_f64).unwrap_or(0.0);
640 Ok(match (op, video) {
641 ("play", true) => VideoPlayer::play(ui, id).map(|_| Value::Null)?,
642 ("play", false) => MediaPlayer::play(ui, id).map(|_| Value::Null)?,
643 ("pause", true) => {
644 VideoPlayer::pause(ui, id);
645 Value::Null
646 }
647 ("pause", false) => {
648 MediaPlayer::pause(ui, id);
649 Value::Null
650 }
651 ("stop", true) => {
652 VideoPlayer::stop(ui, id);
653 Value::Null
654 }
655 ("stop", false) => {
656 MediaPlayer::stop(ui, id);
657 Value::Null
658 }
659 ("seek", true) => {
660 VideoPlayer::seek(ui, id, seconds);
661 Value::Null
662 }
663 ("seek", false) => {
664 MediaPlayer::seek(ui, id, seconds);
665 Value::Null
666 }
667 ("position", true) => json!(VideoPlayer::position(ui, id)),
668 ("position", false) => json!(MediaPlayer::position(ui, id)),
669 ("duration", true) => json!(VideoPlayer::duration(ui, id)),
670 ("duration", false) => json!(MediaPlayer::duration(ui, id)),
671 ("playing", true) => json!(VideoPlayer::is_playing(ui, id)),
672 ("playing", false) => json!(MediaPlayer::is_playing(ui, id)),
673 (other, _) => return Err(format!("operação de mídia desconhecida '{other}'")),
674 })
675}
676
677fn string<'a>(obj: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
678 obj.get(key).and_then(Value::as_str).ok_or_else(|| format!("falta \"{key}\" (texto)"))
679}
680
681pub fn resolve(ui: &Ui, value: &Value) -> Result<ComponentId, String> {
683 match value {
684 Value::String(name) => ui.find_path(name).ok_or_else(|| format!("componente '{name}' não encontrado")),
685 Value::Number(n) => {
686 let id = ComponentId::from_u64(n.as_u64().ok_or("id inválido")?);
687 if ui.contains(id) { Ok(id) } else { Err(format!("componente {n} não existe (ou foi liberado)")) }
688 }
689 other => Err(format!("alvo inválido: {other} (use o nome ou o id)")),
690 }
691}
692
693fn target(ui: &Ui, obj: &Map<String, Value>) -> Result<ComponentId, String> {
694 resolve(ui, obj.get("target").ok_or("falta \"target\"")?)
695}
696
697fn optional_target(ui: &Ui, value: Option<&Value>) -> Result<Option<ComponentId>, String> {
698 match value {
699 None | Some(Value::Null) => Ok(None),
700 Some(v) => resolve(ui, v).map(Some),
701 }
702}
703
704fn json_arg(v: &Value) -> PropValue {
706 match v {
707 Value::Bool(b) => PropValue::Bool(*b),
708 Value::Number(n) => n.as_i64().map(PropValue::Int).unwrap_or_else(|| PropValue::Float(n.as_f64().unwrap_or(0.0))),
709 Value::String(s) => PropValue::String(s.clone()),
710 Value::Null => PropValue::Null,
711 other => PropValue::String(other.to_string()),
712 }
713}
714
715fn get(ui: &Ui, id: ComponentId, name: &str) -> Result<Value, String> {
716 let value = ui.get_prop(id, name).map_err(|e| e.to_string())?;
717 Ok(aylis_json::prop_to_json(ui, &value))
718}
719
720fn json_key(json: &Value) -> aylis_data::Value {
724 match json {
725 Value::Null => aylis_data::Value::Null,
726 Value::Bool(b) => aylis_data::Value::Bool(*b),
727 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))),
728 Value::String(s) => aylis_data::Value::String(s.clone()),
729 other => aylis_data::Value::String(other.to_string()),
730 }
731}
732
733fn data(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
734 let id = target(ui, obj)?;
735 if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
736 return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
737 }
738 let op = string(obj, "op")?;
739 let mut ds = data_set(ui, id);
740 let ok = |r: aylis_data::DataResult| r.map(|_| Value::Null).map_err(|e| e.message);
741 match op {
742 "load" => ok(ds.load_json(obj.get("rows").ok_or("falta \"rows\"")?)),
743 "load_columns" => ok(ds.load_columns(obj.get("fields").ok_or("falta \"fields\"")?, obj.get("columns").ok_or("falta \"columns\"")?)),
745 "append" => {
746 let more = obj.get("has_more").and_then(Value::as_bool).unwrap_or(false);
747 ok(ds.append_json(obj.get("rows").ok_or("falta \"rows\"")?, more))
748 }
749 "reconcile" => {
751 let results = obj.get("results").ok_or("falta \"results\"")?;
752 let results = ds.parse_results(&json!({ "results": results }).to_string()).map_err(|e| e.message)?;
753 let rejected: Vec<&str> = results.iter().filter_map(|r| r.error.as_deref()).collect();
754 let rejected = json!({ "rejected": rejected });
755 let _ = ds.reconcile(&results);
756 Ok(rejected)
757 }
758 "first" => ok(ds.first()),
759 "prior" => ok(ds.prior()),
760 "next" => ok(ds.next()),
761 "last" => ok(ds.last()),
762 "move_to" => ok(ds.move_to(obj.get("index").and_then(Value::as_u64).ok_or("falta \"index\"")? as usize)),
763 "edit" => ok(ds.edit()),
764 "insert" => ok(ds.insert()),
765 "append_record" => ok(ds.append()),
766 "post" => {
768 ok(ds.post())?;
769 if ds.is_asking() || ds.awaiting_text() {
770 if let Some(reply) = defer_reply(ds.ui()) {
771 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "post".into(), replay: None });
772 }
773 }
774 Ok(Value::Null)
775 }
776 "cancel" => ok(ds.cancel()),
777 "delete" => {
778 ok(ds.delete())?;
779 if ds.is_asking() {
780 if let Some(reply) = defer_reply(ds.ui()) {
781 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "delete".into(), replay: None });
782 }
783 }
784 Ok(Value::Null)
785 }
786 "apply" => {
789 let result = ds.apply_updates();
790 if ds.is_applying() {
791 if let Some(reply) = defer_reply(ds.ui()) {
792 ds.ui().extension::<Remote>().waiting.push(Waiting { reply: Some(reply), ds: id, op: "apply".into(), replay: None });
793 }
794 return Ok(Value::Null);
795 }
796 match result {
797 Err(e) if ds.apply_errors() == 0 => Err(e.message),
798 _ => Ok(json!(ds.apply_errors())),
799 }
800 }
801 "cancel_updates" => ok(ds.cancel_updates()),
802 "refresh" => {
803 ds.refresh_links();
804 Ok(Value::Null)
805 }
806 "set_has_more" => ok(ds.set_has_more(obj.get("value").and_then(Value::as_bool).unwrap_or(false))),
807 "set_value" => {
808 let field = string(obj, "field")?;
809 let json = obj.get("value").cloned().unwrap_or(Value::Null);
810 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
811 ok(ds.set_value(field, value))
812 }
813 "set_text" => {
814 let field = string(obj, "field")?;
815 ok(ds.set_text(field, string(obj, "text")?))
816 }
817 "set_values" => {
820 let values = obj.get("values").and_then(Value::as_object).ok_or("falta \"values\" (objeto)")?;
821 if !ds.state().is_editing() {
822 ds.edit().map_err(|e| e.message)?;
823 }
824 for (field, json) in values {
825 let value = json_to_value(json, ds.view().field(field).map_err(|e| e.message)?)?;
826 ds.set_value(field, value).map_err(|e| format!("{field}: {}", e.message))?;
827 }
828 Ok(Value::Null)
829 }
830 "locate" => {
831 let field = string(obj, "field")?;
832 let json = obj.get("value").cloned().unwrap_or(Value::Null);
833 let value = json_to_value(&json, ds.view().field(field).map_err(|e| e.message)?)?;
834 ds.locate(field, value).map(Value::Bool).map_err(|e| e.message)
835 }
836 "set_filter" => ok(ds.set_filter(obj.get("filter").and_then(Value::as_str).unwrap_or_default())),
837 "set_index" => ok(ds.set_index(obj.get("index").and_then(Value::as_str).unwrap_or_default())),
838 "set_index_name" => ok(ds.set_index_name(obj.get("name").and_then(Value::as_str).unwrap_or_default())),
839 "set_param" => {
841 let name = string(obj, "name")?;
842 ok(ds.set_param(name, json_key(obj.get("value").unwrap_or(&Value::Null))))
843 }
844 "revert_record" => ok(ds.revert_record()),
845 "field_texts" => {
847 let field = string(obj, "field")?;
848 let pairs = obj.get("texts").and_then(Value::as_array).ok_or("falta \"texts\" (lista de [valor, texto])")?;
849 let texts = pairs
850 .iter()
851 .filter_map(|p| {
852 let p = p.as_array()?;
853 Some((json_key(p.first()?), p.get(1)?.as_str().unwrap_or_default().to_string()))
854 })
855 .collect();
856 ok(ds.set_field_texts(field, texts))
857 }
858 "field_error" => {
861 let field = string(obj, "field")?;
862 let message = obj.get("message").and_then(Value::as_str).map(str::to_string);
863 ok(ds.set_field_error(field, message))
864 }
865 "lookup" => {
866 let key_fields = string(obj, "key_fields")?;
867 let result = string(obj, "result_field")?;
868 let keys: Vec<aylis_data::Value> = match obj.get("keys") {
869 Some(Value::Array(list)) => list.iter().map(json_key).collect(),
870 Some(k) => vec![json_key(k)],
871 None => return Err("falta \"keys\"".into()),
872 };
873 Ok(ds.view().lookup(key_fields, &keys, result).map(|v| value_to_json(&v)).unwrap_or(Value::Null))
874 }
875 "value" => ds.value(string(obj, "field")?).map(|v| value_to_json(&v)).map_err(|e| e.message),
876 "text" => ds.text(string(obj, "field")?).map(Value::String).map_err(|e| e.message),
877 "record" => record(&ds),
878 "info" => {
879 let v = ds.view();
880 Ok(json!({
881 "state": format!("{:?}", v.state()).to_lowercase(),
882 "rec_no": v.rec_no(),
883 "count": v.record_count(),
884 "changes": v.change_count(),
885 "has_more": v.has_more(),
886 "bof": v.bof(),
887 "eof": v.eof(),
888 "status": v.update_status().map(|s| format!("{s:?}").to_lowercase()),
890 }))
891 }
892 "delta" => {
893 let changes = ds.delta_with_details().map_err(|e| e.message)?;
894 let name = ds.ui().name(id).unwrap_or_default().to_string();
895 serde_json::from_str(&aylis_data::json::delta_to_json(&name, &changes)).map_err(|e| e.to_string())
896 }
897 other => Err(format!("operação de dados desconhecida '{other}'")),
898 }
899}
900
901fn answer_value(v: &Value) -> PropValue {
903 match v {
904 Value::Bool(b) => PropValue::Bool(*b),
905 Value::Number(n) if n.is_i64() => PropValue::Int(n.as_i64().unwrap_or_default()),
906 Value::Number(n) => PropValue::Float(n.as_f64().unwrap_or_default()),
907 Value::String(s) => PropValue::String(s.clone()),
908 Value::Null => PropValue::Null,
909 other => PropValue::String(other.to_string()),
910 }
911}
912
913fn record(ds: &DataSet<'_>) -> Result<Value, String> {
914 let v = ds.view();
915 let mut out = Map::new();
916 for name in v.field_names() {
917 out.insert(name.clone(), value_to_json(&v.value(&name).map_err(|e| e.message)?));
918 }
919 Ok(Value::Object(out))
920}
921
922pub fn event_to_json(ui: &Ui, sender: ComponentId, event: &str, handler: &str, args: &EventArgs) -> Value {
926 let mut message = json!({
927 "event": event,
928 "handler": handler,
929 "form": ui.form_class(ui.form_of(sender)).or_else(|| ui.name(ui.form_of(sender))).unwrap_or_default(),
932 "form_id": ui.form_of(sender).to_u64(),
934 "sender": {
935 "id": sender.to_u64(),
936 "name": ui.name(sender).unwrap_or_default(),
937 "path": ui.path_of(sender),
938 "class": ui.class_name(sender).unwrap_or_default(),
939 },
940 "args": args_to_json(ui, args),
941 });
942 let info = ui.component(sender).map(|c| c.event_info(event)).unwrap_or_default();
945 if !info.is_empty() {
946 message["info"] = Value::Object(info.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect());
947 }
948 message
949}
950
951fn args_to_json(ui: &Ui, args: &EventArgs) -> Value {
952 match args {
953 EventArgs::None => Value::Null,
954 EventArgs::Pointer(p) => json!({
955 "x": p.position.x,
956 "y": p.position.y,
957 "button": match p.button {
958 PointerButton::Primary => "primary",
959 PointerButton::Secondary => "secondary",
960 PointerButton::Middle => "middle",
961 PointerButton::Back => "back",
962 PointerButton::Forward => "forward",
963 },
964 "clicks": p.click_count,
965 }),
966 EventArgs::Wheel(w) => json!({ "x": w.position.x, "y": w.position.y, "dx": w.delta.x, "dy": w.delta.y }),
967 EventArgs::Gesture(g) => json!({
968 "phase": match g.phase { aylis_core::GesturePhase::Begin => "begin", aylis_core::GesturePhase::Update => "update", aylis_core::GesturePhase::End => "end" },
969 "x": g.center.x, "y": g.center.y, "scale": g.scale, "delta_scale": g.delta_scale,
970 "rotation": g.rotation, "delta_rotation": g.delta_rotation, "pan_x": g.pan.x, "pan_y": g.pan.y,
971 }),
972 EventArgs::Key(k) => json!({
973 "key": key_name(k.key),
974 "ctrl": k.modifiers.ctrl,
975 "shift": k.modifiers.shift,
976 "alt": k.modifiers.alt,
977 }),
978 EventArgs::Text(text) => match serde_json::from_str::<Value>(text) {
980 Ok(v @ (Value::Object(_) | Value::Array(_))) => v,
981 _ => Value::String(text.clone()),
982 },
983 EventArgs::Value(PropValue::Component(c)) => c.map_or(Value::Null, |id| Value::from(id.to_u64())),
984 EventArgs::Value(v) => aylis_json::prop_to_json(ui, v),
985 EventArgs::Intercept(i) => {
988 let sender = i.sender.map_or(Value::Null, |id| {
989 json!({
990 "id": id.to_u64(),
991 "name": ui.name(id).unwrap_or_default(),
992 "path": ui.path_of(id),
993 "class": ui.class_name(id).unwrap_or_default(),
994 })
995 });
996 json!({
997 "form": i.form.and_then(|f| ui.name(f)).unwrap_or_default(),
998 "form_id": i.form.map_or(Value::Null, |f| Value::from(f.to_u64())),
999 "sender": sender,
1000 "event": i.event,
1001 "handler": i.handler,
1002 "args": args_to_json(ui, &i.args),
1003 })
1004 }
1005 }
1006}
1007
1008fn key_name(key: Key) -> String {
1009 match key {
1010 Key::Char(c) => c.to_string(),
1011 Key::F(n) => format!("f{n}"),
1012 other => format!("{other:?}").to_lowercase(),
1013 }
1014}
1015
1016pub fn forward_events(ui: &mut Ui, send: impl Fn(&mut Ui, Value) + 'static) {
1019 let send: std::rc::Rc<dyn Fn(&mut Ui, Value)> = std::rc::Rc::new(send);
1020 ui.extension::<Remote>().sink = Some(send.clone());
1022 ui.on_forms_freed(|ui, forms| {
1024 let ids: Vec<Value> = forms.iter().map(|f| Value::from(f.to_u64())).collect();
1025 send_event(ui, None, json!({ "event": "__freed", "forms": ids }));
1026 });
1027 ui.set_event_sink(move |ui, sender, event, handler, args| {
1028 let mut json = event_to_json(ui, sender, event, handler, args);
1029 if ui.asking() {
1032 json["ask"] = Value::from(ui.defer_question());
1033 }
1034 let key = (sender.to_u64(), event.to_string());
1036 let joined = {
1037 let coalesce = coalesces(ui, sender, event);
1038 let b = &mut ui.extension::<Remote>().busy;
1039 if b.tracking && json.get("ask").is_none() && b.running.values().any(|k| *k == key) && coalesce {
1040 b.latest.insert(key.clone(), json.clone());
1041 true
1042 } else {
1043 false
1044 }
1045 };
1046 if !joined {
1047 send_event(ui, Some(sender), json);
1048 }
1049 });
1050}
1051
1052fn defer_reply(ui: &Ui) -> Option<Value> {
1055 if ui.extension_ref::<Remote>().is_none_or(|r| r.sink.is_none()) {
1056 return None;
1057 }
1058 CURRENT_ID.with(|c| c.borrow_mut().take())
1059}
1060
1061fn send_reply(ui: &mut Ui, id: Value, result: Result<Value, String>) {
1063 let message = match result {
1064 Ok(result) => json!({ "id": id, "result": result }),
1065 Err(error) => json!({ "id": id, "error": error }),
1066 };
1067 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1068 sink(ui, message);
1069 }
1070}
1071
1072fn flush_waiting_data(ui: &mut Ui) {
1075 let waiting = std::mem::take(&mut ui.extension::<Remote>().waiting);
1076 let mut still = Vec::new();
1077 for w in waiting {
1078 let ds = data_set(ui, w.ds);
1079 if ds.is_asking() || ds.awaiting_text() {
1080 still.push(w);
1081 continue;
1082 }
1083 let editing = ds.state().is_editing();
1084 let result = match w.replay {
1085 Some(_) if editing => Err("a gravação foi recusada".to_string()),
1087 Some(command) => {
1088 let had_id = w.reply.is_some();
1090 CURRENT_ID.with(|c| *c.borrow_mut() = w.reply.clone());
1091 let result = data_command(ui, &command);
1092 if had_id && CURRENT_ID.with(|c| c.borrow_mut().take()).is_none() {
1093 continue;
1094 }
1095 result
1096 }
1097 None if w.op == "post" && editing => Err("a gravação foi recusada".to_string()),
1098 None if w.op == "apply" => match ds.apply_errors() {
1099 usize::MAX => Err("a gravação foi recusada".to_string()),
1100 n => Ok(json!(n)),
1101 },
1102 None => Ok(Value::Null),
1103 };
1104 match (w.reply, result) {
1105 (Some(reply), result) => send_reply(ui, reply, result),
1106 (None, Err(error)) => {
1108 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1109 sink(ui, json!({ "event": "error", "cmd": "data", "message": error }));
1110 }
1111 }
1112 (None, Ok(_)) => {}
1113 }
1114 }
1115 ui.extension::<Remote>().waiting.extend(still);
1116}
1117
1118struct Waiting {
1120 reply: Option<Value>,
1122 ds: ComponentId,
1123 op: String,
1124 replay: Option<Map<String, Value>>,
1126}
1127
1128fn data_command(ui: &mut Ui, obj: &Map<String, Value>) -> Result<Value, String> {
1131 match data(ui, obj) {
1132 Err(error) if error == aylis_data::DataError::waiting().message => {
1133 let ds = target(ui, obj)?;
1134 let reply = defer_reply(ui);
1135 let op = string(obj, "op")?.to_string();
1136 ui.extension::<Remote>().waiting.push(Waiting { reply, ds, op, replay: Some(obj.clone()) });
1137 Ok(Value::Null)
1138 }
1139 other => other,
1140 }
1141}
1142
1143#[derive(Default)]
1145struct BusyTrack {
1146 tracking: bool,
1149 next: u64,
1150 running: std::collections::HashMap<u64, (u64, String)>,
1152 latest: std::collections::HashMap<(u64, String), Value>,
1154}
1155
1156pub fn coalesces(ui: &Ui, sender: ComponentId, event: &str) -> bool {
1160 aylis_core::question::COALESCED_EVENTS.contains(&event)
1161 || (event == "on_change" && matches!(ui.class_name(sender), Some("TrackBar" | "Slider" | "RangeSlider" | "ScrollBar" | "Knob" | "Gauge")))
1162}
1163
1164fn backend_done(ui: &mut Ui, seq: u64) {
1166 let next = {
1167 let b = &mut ui.extension::<Remote>().busy;
1168 b.running.remove(&seq).and_then(|key| b.latest.remove(&key))
1169 };
1170 ui.backend_done(seq);
1171 if let Some(json) = next {
1172 let sender = json["sender"]["id"].as_u64().map(ComponentId::from_u64);
1173 send_event(ui, sender, json);
1174 }
1175}
1176
1177fn send_event(ui: &mut Ui, sender: Option<ComponentId>, mut json: Value) {
1179 if ui.extension::<Remote>().busy.tracking {
1180 let seq = {
1181 let b = &mut ui.extension::<Remote>().busy;
1182 b.next += 1;
1183 b.next
1184 };
1185 json["seq"] = Value::from(seq);
1186 if let Some(sender) = sender {
1187 ui.backend_event_sent(seq, sender);
1188 let event = json["event"].as_str().unwrap_or_default().to_string();
1189 if coalesces(ui, sender, &event) {
1190 ui.extension::<Remote>().busy.running.insert(seq, (sender.to_u64(), event));
1191 }
1192 }
1193 }
1194 if let Some(sink) = ui.extension::<Remote>().sink.clone() {
1195 sink(ui, json);
1196 }
1197}
1198
1199#[derive(Default)]
1202struct Remote {
1203 sink: Option<std::rc::Rc<dyn Fn(&mut Ui, Value)>>,
1205 busy: BusyTrack,
1206 waiting: Vec<Waiting>,
1208}