1use std::collections::BTreeMap;
11use std::io::{BufRead, BufReader, Write};
12use std::net::{TcpListener, TcpStream};
13use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
14use std::sync::{Arc, mpsc};
15use std::time::{Duration, Instant};
16
17use day_core::{NodeProbe, rnode_to_id, with_tree};
18
19pub mod record;
23pub use record::play;
24pub mod conformance;
26mod memory;
27mod memory_watch;
28pub mod png;
30
31pub const DEFAULT_MAIN_TIMEOUT_SECS: f64 = 30.0;
41
42pub use day_script_protocol::{DEFAULT_TIMEOUT_SECS, DialogMode, Reply, Request, Step};
44
45fn parse_width_class(s: &str) -> Option<day_spec::WidthClass> {
47 use day_spec::WidthClass as W;
48 match s {
49 "compact" => Some(W::Compact),
50 "medium" => Some(W::Medium),
51 "expanded" => Some(W::Expanded),
52 "large" => Some(W::Large),
53 "extra-large" => Some(W::ExtraLarge),
54 _ => None,
55 }
56}
57
58fn parse_height_class(s: &str) -> Option<day_spec::HeightClass> {
60 use day_spec::HeightClass as H;
61 match s {
62 "compact" => Some(H::Compact),
63 "medium" => Some(H::Medium),
64 "expanded" => Some(H::Expanded),
65 _ => None,
66 }
67}
68
69fn drive_undo(redo: bool) -> Result<Reply, Reply> {
72 if day_core::invoke_undo(redo) {
73 day_reactive::flush_sync();
74 Ok(Reply::ok())
75 } else {
76 Err(Reply::fail("no undo stack installed".to_string(), false))
77 }
78}
79
80pub fn init() {
86 if let Some(path) = std::env::var_os("DAY_RECORD").filter(|p| !p.is_empty()) {
92 record::start_to_file(path);
93 }
94 if std::env::var("DAY_LOG_ACTIONS").is_ok_and(|v| v == "1") {
98 record::log_actions(true);
99 }
100 let (Ok(port), Ok(token)) = (
101 std::env::var("DAYSCRIPT_PORT"),
102 std::env::var("DAYSCRIPT_TOKEN"),
103 ) else {
104 return;
105 };
106 let Ok(port) = port.parse::<u16>() else {
107 return;
108 };
109 std::thread::spawn(move || serve(port, &token));
110}
111
112const RETRY_MS: u32 = 100;
123
124#[cfg(target_arch = "wasm32")]
125mod web {
126 use super::*;
127 use std::cell::RefCell;
128
129 type WebSender = Box<dyn Fn(&str)>;
131
132 thread_local! {
133 static WEB: RefCell<Option<(String, WebSender)>> = const { RefCell::new(None) };
135 static WATCH: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
136 }
137
138 pub fn web_init(token: String, send: impl Fn(&str) + 'static) {
141 WATCH.with(|w| w.set(w.get() + 1));
142 WEB.with(|w| *w.borrow_mut() = Some((token, Box::new(send))));
143 }
144
145 pub fn web_line(line: &str) {
150 let reply = match serde_json::from_str::<Request>(line.trim()) {
151 Ok(req) => {
152 let authed =
153 WEB.with(|w| w.borrow().as_ref().is_some_and(|(t, _)| *t == req.token));
154 if authed {
155 if let Step::MemoryWatch { interval_ms } = req.step {
156 if !memory_watch::valid_interval(interval_ms) {
157 send_reply(&Reply::fail(
158 "memory_watch interval must be 0 or 100..60000 ms",
159 false,
160 ));
161 return;
162 }
163 let generation = WATCH.with(|w| {
164 w.set(w.get() + 1);
165 w.get()
166 });
167 send_reply(&memory_watch::sample());
168 if interval_ms > 0 {
169 watch_tick(generation, interval_ms as u32);
170 }
171 send_reply(&Reply::ok());
172 return;
173 }
174 let budget_ms = (req.step.wait_budget_secs() * 1000.0) as u32;
175 attempt(req.step, budget_ms, next_capture_revision());
176 return;
177 }
178 Reply::fail("bad token", false)
179 }
180 Err(e) => Reply::fail(format!("bad request: {e}"), false),
181 };
182 send_reply(&reply);
183 }
184
185 fn attempt(step: Step, remaining_ms: u32, revision: u32) {
186 let reply = exec(step.clone(), revision);
187 if reply.ok || !reply.retryable || remaining_ms == 0 {
188 send_reply(&reply);
189 return;
190 }
191 let interval = if reply.capture_pending { 16 } else { RETRY_MS };
192 let delay = interval.min(remaining_ms);
193 day_reactive::on_main_delayed(delay, move || attempt(step, remaining_ms - delay, revision));
194 }
195
196 fn watch_tick(generation: u64, interval: u32) {
197 day_reactive::on_main_delayed(interval, move || {
198 if WATCH.with(std::cell::Cell::get) == generation {
199 send_reply(&memory_watch::sample());
200 watch_tick(generation, interval);
201 }
202 });
203 }
204
205 fn send_reply(reply: &Reply) {
206 let mut out = serde_json::to_string(reply).unwrap_or_else(|_| "{\"ok\":false}".into());
207 out.push('\n');
208 WEB.with(|w| {
209 if let Some((_, send)) = w.borrow().as_ref() {
210 send(&out);
211 }
212 });
213 }
214}
215#[cfg(target_arch = "wasm32")]
216pub use web::{web_init, web_line};
217
218fn serve(port: u16, token: &str) {
219 std::thread::sleep(Duration::from_millis(300));
221 let deadline = std::time::Instant::now() + Duration::from_secs(15);
229 let mut said = false;
230 let listener = loop {
231 match TcpListener::bind(("127.0.0.1", port)) {
232 Ok(l) => break l,
233 Err(e) if std::time::Instant::now() < deadline => {
234 if !said {
237 said = true;
238 log::warn!("day-script: 127.0.0.1:{port} still busy ({e}) — waiting for it");
239 }
240 std::thread::sleep(Duration::from_millis(250));
241 }
242 Err(e) => {
243 log::error!(
246 "day-script: bind 127.0.0.1:{port} failed after 15s: {e} — this app has NO \
247 dayscript engine; anything driving this port is reaching a DIFFERENT process"
248 );
249 return;
250 }
251 }
252 };
253 for stream in listener.incoming().flatten() {
254 handle_conn(stream, token);
255 }
256}
257
258fn handle_conn(stream: TcpStream, token: &str) {
259 let _ = stream.set_nodelay(true);
260 let _ = stream.set_write_timeout(Some(Duration::from_secs(15)));
261 let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
262 let writer = Arc::new(std::sync::Mutex::new(stream));
263 let mut watch = None;
264 let mut line = String::new();
265 loop {
266 line.clear();
267 match reader.read_line(&mut line) {
268 Ok(0) | Err(_) => return,
269 Ok(_) => {}
270 }
271 let reply = match serde_json::from_str::<Request>(line.trim()) {
272 Ok(req) if req.token == token => {
273 if let Step::MemoryWatch { interval_ms } = req.step {
274 if memory_watch::valid_interval(interval_ms) {
275 drop(watch.take());
276 if interval_ms > 0 {
277 watch = Some(memory_watch::Watch::start(writer.clone(), interval_ms));
278 }
279 Reply::ok()
280 } else {
281 Reply::fail("memory_watch interval must be 0 or 100..60000 ms", false)
282 }
283 } else {
284 run_step_with_wait(&req.step)
285 }
286 }
287 Ok(_) => Reply::fail("bad token", false),
288 Err(e) => Reply::fail(format!("bad request: {e}"), false),
289 };
290 let mut out = serde_json::to_string(&reply).unwrap_or_else(|_| "{\"ok\":false}".into());
291 out.push('\n');
292 if writer.lock().unwrap().write_all(out.as_bytes()).is_err() {
293 return;
294 }
295 }
296}
297
298const SNAPSHOT_RETRIES: u32 = 30;
301static SNAPSHOT_MISSES: AtomicU32 = AtomicU32::new(0);
303static SNAPSHOT_WORKS: AtomicBool = AtomicBool::new(false);
306static SNAPSHOT_NEVER: AtomicBool = AtomicBool::new(false);
309
310const FOCUS_WAIT_POLLS: u32 = 10;
313static FOCUS_WAITS: AtomicU32 = AtomicU32::new(0);
315
316static CAPTURE_REVISION: AtomicU32 = AtomicU32::new(1);
319fn next_capture_revision() -> u32 {
320 CAPTURE_REVISION.fetch_add(1, Ordering::Relaxed)
321}
322
323#[must_use]
327pub fn step(step: Step) -> Reply {
328 exec(step, next_capture_revision())
329}
330
331fn run_step_with_wait(step: &Step) -> Reply {
332 let revision = next_capture_revision();
333 let budget = Duration::from_secs_f64(step.wait_budget_secs());
334 let deadline = Instant::now() + budget;
335 let main_budget = main_thread_budget(budget);
336 loop {
337 let reply = run_on_main(step.clone(), main_budget, revision);
338 if reply.ok || !reply.retryable || Instant::now() > deadline {
339 return reply;
340 }
341 let retry_ms = if reply.capture_pending { 16 } else { RETRY_MS };
342 std::thread::sleep(Duration::from_millis(u64::from(retry_ms)));
343 }
344}
345
346fn main_thread_budget(step_budget: Duration) -> Duration {
350 let secs = std::env::var("DAY_SCRIPT_MAIN_TIMEOUT_SECS")
351 .ok()
352 .and_then(|v| v.parse::<f64>().ok())
353 .filter(|v| v.is_finite() && *v > 0.0)
354 .unwrap_or(DEFAULT_MAIN_TIMEOUT_SECS);
355 Duration::from_secs_f64(secs).max(step_budget)
356}
357
358fn run_on_main(step: Step, budget: Duration, revision: u32) -> Reply {
359 let (tx, rx) = mpsc::sync_channel::<Reply>(1);
360 let abandoned = Arc::new(AtomicBool::new(false));
367 let flag = Arc::clone(&abandoned);
368 day_reactive::on_main(move || {
369 if flag.load(Ordering::SeqCst) {
370 return;
371 }
372 if !day_core::has_tree() {
379 let _ = tx.send(Reply::fail("the app is still starting", true));
380 return;
381 }
382 let _ = tx.send(exec(step, revision));
383 });
384 if let Ok(reply) = rx.recv_timeout(budget) {
385 reply
386 } else {
387 abandoned.store(true, Ordering::SeqCst);
388 Reply {
389 main_thread_stalled: true,
390 ..Reply::fail(
391 format!(
392 "main thread did not respond within {:.0}s — raise \
393 DAY_SCRIPT_MAIN_TIMEOUT_SECS if this machine is just slow",
394 budget.as_secs_f64()
395 ),
396 false,
397 )
398 }
399 }
400}
401
402fn parse_modifiers(names: &[String]) -> day_spec::Modifiers {
414 let mut m = day_spec::Modifiers::default();
415 for n in names {
416 match n.to_ascii_lowercase().as_str() {
417 "shift" => m.shift = true,
418 "primary" | "cmd" | "ctrl" | "meta" => m.primary = true,
419 "alt" | "option" => m.alt = true,
420 _ => {}
421 }
422 }
423 m
424}
425
426fn find_menu_actions(
427 items: &[day_spec::MenuItem],
428 target_label: &str,
429 target_key: Option<&str>,
430 target_id: Option<&str>,
431 path: &[(String, String)],
432) -> Vec<(u64, bool, Vec<String>)> {
433 fn role_key(role: day_spec::MenuRole) -> &'static str {
435 use day_spec::MenuRole as R;
436 match role {
437 R::Cut => "day_cut",
438 R::Copy => "day_copy",
439 R::Paste => "day_paste",
440 R::SelectAll => "day_select_all",
441 R::Undo => "day_undo",
442 R::Redo => "day_redo",
443 R::Delete => "day_delete",
444 R::About => "day_about",
445 R::Quit => "day_quit",
446 R::Preferences => "day_preferences",
447 R::Minimize => "day_minimize",
448 R::CloseWindow => "day_close",
449 R::Fullscreen => "day_fullscreen",
450 R::NewWindow => "day_new_window",
451 R::CheckForUpdates => "day_check_for_updates",
452 }
453 }
454 #[allow(clippy::too_many_arguments)]
455 fn walk(
456 items: &[day_spec::MenuItem],
457 trail: &mut Vec<String>,
458 target_label: &str,
459 target_key: Option<&str>,
460 target_id: Option<&str>,
461 path: &[(String, String)],
462 out: &mut Vec<(u64, bool, Vec<String>)>,
463 ) {
464 for it in items {
465 match it {
466 day_spec::MenuItem::Action {
467 id,
468 action,
469 label,
470 enabled,
471 role,
472 ..
473 } => {
474 let by_id = target_id.is_some_and(|w| id.as_deref() == Some(w));
478 let by_label =
479 target_id.is_none() && !label.is_empty() && label == target_label;
480 let by_key = target_id.is_none()
481 && target_key.is_some_and(|k| role.is_some_and(|r| role_key(r) == k));
482 let path_ok = path.is_empty()
483 || (path.len() <= trail.len()
484 && trail[trail.len() - path.len()..]
485 .iter()
486 .zip(path)
487 .all(|(seen, want)| seen == &want.0 || seen == &want.1));
488 if (by_id || by_label || by_key) && path_ok {
489 out.push((*action, *enabled, trail.clone()));
490 }
491 }
492 day_spec::MenuItem::Submenu { label, items, .. } => {
493 trail.push(label.clone());
494 walk(items, trail, target_label, target_key, target_id, path, out);
495 trail.pop();
496 }
497 day_spec::MenuItem::Separator => {}
498 }
499 }
500 }
501 let mut out = Vec::new();
502 walk(
503 items,
504 &mut Vec::new(),
505 target_label,
506 target_key,
507 target_id,
508 path,
509 &mut out,
510 );
511 out
512}
513
514fn format_key(key: &str, args: Option<BTreeMap<String, serde_json::Value>>) -> String {
515 let mut lt = day_localization_ui::tr(key);
516 for (name, v) in args.unwrap_or_default() {
517 lt = match v {
518 serde_json::Value::Number(n) => lt.arg(&name, n.as_f64().unwrap_or(0.0)),
519 serde_json::Value::String(s) => lt.arg(&name, s),
520 other => lt.arg(&name, other.to_string()),
521 };
522 }
523 lt.format()
524}
525
526fn find(id: &str) -> Result<day_core::RNode, Reply> {
527 with_tree(|t| t.find_by_id(id)).ok_or_else(|| Reply::fail(format!("no element {id:?}"), true))
528}
529
530fn probe(id: &str) -> Result<NodeProbe, Reply> {
531 let node = find(id)?;
532 with_tree(|t| t.node_probe(node)).ok_or_else(|| Reply::fail("element vanished", true))
533}
534
535fn emit(id: &str, ev: day_spec::Event) -> Result<(), Reply> {
536 let node = find(id)?;
537 day_core::enqueue_event(rnode_to_id(node), ev);
538 day_reactive::flush_sync();
539 Ok(())
540}
541
542fn visible(id: &str) -> Result<(), Reply> {
543 let node = find(id)?;
544 let frame = with_tree(|t| t.node_frame(node));
545 match frame {
546 Some(f) if f.size.width > 0.0 && f.size.height > 0.0 => Ok(()),
547 _ => Err(Reply::fail(format!("{id:?} has no visible frame"), true)),
548 }
549}
550
551fn parse_hex_color(s: &str) -> Option<[u8; 3]> {
553 let hex = s.strip_prefix('#')?;
554 if hex.len() != 6 {
555 return None;
556 }
557 let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
558 Some([channel(0)?, channel(2)?, channel(4)?])
559}
560
561fn norm(s: &str) -> String {
562 day_localization_ui::strip_isolates(s)
563}
564
565fn hosts_settled() -> Result<(), Reply> {
569 if day_spec::capture::holds_settled() {
570 Ok(())
571 } else {
572 Err(Reply {
573 capture_pending: true,
574 ..Reply::fail("waiting for a host's pending frame", true)
575 })
576 }
577}
578
579fn id_catalog() -> Result<&'static day_script_protocol::IdCatalog, String> {
580 static CATALOG: std::sync::OnceLock<Result<day_script_protocol::IdCatalog, String>> =
581 std::sync::OnceLock::new();
582 CATALOG
583 .get_or_init(|| {
584 Ok(day_script_protocol::IdCatalog {
585 schema_version: 1,
586 declarations: day_core::element_id::registry()?
587 .iter()
588 .cloned()
589 .map(|d| day_script_protocol::IdDeclaration {
590 family: d.family,
591 keyed: d.keyed,
592 package: d.package,
593 version: d.version,
594 locations: d.locations,
595 })
596 .collect(),
597 })
598 })
599 .as_ref()
600 .map_err(Clone::clone)
601}
602
603fn exec(step: Step, revision: u32) -> Reply {
604 use day_spec::Event;
605 use day_spec::present::PresentResult;
606 let evidence_class = step.evidence_class();
607 let evidence_id = step.element_references().into_iter().next();
608 let absent_optional_action = matches!(&step,
611 Step::Tap { id, if_present: true, .. }
612 | Step::Select { id, if_present: true, .. }
613 | Step::ContextMenu { id, if_present: true, .. } if find(id).is_err());
614
615 let result: Result<Reply, Reply> = (|| {
616 match step {
617 Step::IdMounted => Ok(Reply {
618 data: Some(serde_json::json!(with_tree(|t| t.mounted_id_families()))),
619 ..Reply::ok()
620 }),
621 Step::IdCatalog => {
622 let catalog = id_catalog().map_err(|e| Reply::fail(e, false))?;
623 Ok(Reply {
624 data: Some(serde_json::to_value(catalog).unwrap()),
625 ..Reply::ok()
626 })
627 }
628 Step::WaitFor { id, .. } | Step::AssertVisible { id } => {
629 visible(&id)?;
630 Ok(Reply::ok())
631 }
632 Step::WaitIdle => {
633 day_reactive::flush_sync();
634 if !with_tree(|t| t.ui_idle()) {
635 return Err(Reply::fail("ui transitions still settling", true));
636 }
637 Ok(Reply::ok())
638 }
639 Step::MemoryUsage { fail_if_above } => Ok(memory::sample(fail_if_above)),
640 Step::MemoryWatch { .. } => Err(Reply::fail(
641 "memory_watch requires a transport connection",
642 false,
643 )),
644 Step::Tap {
645 id,
646 if_present,
647 repeat,
648 at,
649 modifiers,
650 } => {
651 day_reactive::flush_sync();
655 if !with_tree(|t| t.ui_idle()) {
656 return Err(Reply::fail("ui transitions still settling", true));
657 }
658 if if_present && with_tree(|t| t.find_by_id(&id)).is_none() {
659 return Ok(Reply::ok());
660 }
661 visible(&id)?;
662 if !probe(&id)?.enabled {
663 return Err(Reply::fail(format!("{id:?} is disabled"), true));
664 }
665 let node = find(&id)?;
670 let point = match at {
671 Some([x, y]) => day_spec::Point::new(x, y),
672 None => with_tree(|t| t.node_frame(node)).map_or(day_spec::Point::ZERO, |f| {
673 day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
674 }),
675 };
676 if !modifiers.is_empty() {
680 day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
681 }
682 for _ in 0..repeat.unwrap_or(1).max(1) {
683 day_core::enqueue_event(rnode_to_id(node), Event::Pressed);
684 day_core::enqueue_event(rnode_to_id(node), Event::Tap(point));
685 }
686 day_reactive::flush_sync();
687 day_core::set_modifier_override(None);
688 Ok(Reply::ok())
689 }
690 Step::Key { key, id, modifiers } => {
691 let target = match &id {
696 Some(id) => rnode_to_id(find(id)?),
697 None => match day_core::focused_node() {
698 Some(n) => rnode_to_id(n),
699 None => {
700 return Err(Reply::fail(
701 "nothing has focus — name an `id`, or `focus:` a piece first",
702 true,
703 ));
704 }
705 },
706 };
707 let m = parse_modifiers(&modifiers);
708 let mut mask = 0u8;
709 if m.shift {
710 mask |= day_spec::KeyEvent::SHIFT;
711 }
712 if m.primary {
713 mask |= day_spec::KeyEvent::PRIMARY;
714 }
715 if m.alt {
716 mask |= day_spec::KeyEvent::ALT;
717 }
718 if modifiers.iter().any(|n| n.eq_ignore_ascii_case("control")) {
721 mask |= day_spec::KeyEvent::CONTROL;
722 }
723 let chord = mask
727 & (day_spec::KeyEvent::PRIMARY
728 | day_spec::KeyEvent::ALT
729 | day_spec::KeyEvent::CONTROL)
730 != 0;
731 let event = if day_spec::keys::text(target)
732 && !chord
733 && !day_spec::KeyEvent::NAMED.contains(&key.as_str())
734 {
735 day_spec::KeyEvent::typed_text(key, mask)
736 } else {
737 day_spec::KeyEvent::named(key, mask)
738 };
739 day_core::enqueue_event(target, Event::Key(event));
740 day_reactive::flush_sync();
741 Ok(Reply::ok())
742 }
743 Step::Drag {
744 id,
745 from,
746 to,
747 steps,
748 modifiers,
749 } => {
750 let node = find(&id)?;
751 let (fx, fy) = (from[0], from[1]);
752 let (tx, ty) = (to[0], to[1]);
753 let n = steps.unwrap_or(4).max(1);
754 let emit_drag = |phase, x: f64, y: f64| {
755 day_core::enqueue_event(
756 rnode_to_id(node),
757 Event::Drag {
758 phase,
759 location: day_spec::Point::new(x, y),
760 translation: day_spec::Point::new(x - fx, y - fy),
761 },
762 );
763 };
764 if !modifiers.is_empty() {
768 day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
769 }
770 emit_drag(day_spec::DragPhase::Began, fx, fy);
771 day_reactive::flush_sync();
772 for i in 1..=n {
773 let f = f64::from(i) / f64::from(n);
774 emit_drag(
775 day_spec::DragPhase::Changed,
776 fx + (tx - fx) * f,
777 fy + (ty - fy) * f,
778 );
779 day_reactive::flush_sync();
780 }
781 emit_drag(day_spec::DragPhase::Ended, tx, ty);
782 day_reactive::flush_sync();
783 day_core::set_modifier_override(None);
784 Ok(Reply::ok())
785 }
786 Step::Hover { id, at, leave } => {
787 let node = find(&id)?;
788 let location = if let Some([x, y]) = at {
789 day_spec::Point::new(x, y)
790 } else {
791 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
792 day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
793 };
794 let phase = if leave {
795 day_spec::DragPhase::Ended
796 } else {
797 day_spec::DragPhase::Began
798 };
799 day_core::enqueue_event(rnode_to_id(node), Event::Hover { phase, location });
800 day_reactive::flush_sync();
801 Ok(Reply::ok())
802 }
803 Step::Pan { id, by, steps } => {
804 let node = find(&id)?;
805 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
806 let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
807 let n = steps.unwrap_or(4).max(1);
808 let emit_pan = |phase, dx: f64, dy: f64| {
809 day_core::enqueue_event(
810 rnode_to_id(node),
811 Event::Pan {
812 phase,
813 delta: day_spec::Point::new(dx, dy),
814 location,
815 },
816 );
817 day_reactive::flush_sync();
818 };
819 emit_pan(day_spec::DragPhase::Began, 0.0, 0.0);
820 for _ in 0..n {
822 emit_pan(
823 day_spec::DragPhase::Changed,
824 by[0] / f64::from(n),
825 by[1] / f64::from(n),
826 );
827 }
828 emit_pan(day_spec::DragPhase::Ended, 0.0, 0.0);
829 Ok(Reply::ok())
830 }
831 Step::Pinch { id, scale, steps } => {
832 let node = find(&id)?;
833 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
834 let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
835 let n = steps.unwrap_or(4).max(1);
836 let emit_pinch = |phase, s: f64| {
837 day_core::enqueue_event(
838 rnode_to_id(node),
839 Event::Pinch {
840 phase,
841 scale: s,
842 location,
843 },
844 );
845 day_reactive::flush_sync();
846 };
847 emit_pinch(day_spec::DragPhase::Began, 1.0);
848 for i in 1..=n {
850 emit_pinch(
851 day_spec::DragPhase::Changed,
852 1.0 + (scale - 1.0) * f64::from(i) / f64::from(n),
853 );
854 }
855 emit_pinch(day_spec::DragPhase::Ended, scale);
856 Ok(Reply::ok())
857 }
858 Step::Rotate {
859 id,
860 rotation,
861 steps,
862 } => {
863 let node = find(&id)?;
864 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
865 let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
866 let n = steps.unwrap_or(4).max(1);
867 let emit_rotate = |phase, r: f64| {
868 day_core::enqueue_event(
869 rnode_to_id(node),
870 Event::Rotate {
871 phase,
872 rotation: r,
873 location,
874 },
875 );
876 day_reactive::flush_sync();
877 };
878 emit_rotate(day_spec::DragPhase::Began, 0.0);
879 for i in 1..=n {
881 emit_rotate(
882 day_spec::DragPhase::Changed,
883 rotation * f64::from(i) / f64::from(n),
884 );
885 }
886 emit_rotate(day_spec::DragPhase::Ended, rotation);
887 Ok(Reply::ok())
888 }
889 Step::Submit { id } => emit(&id, Event::Submitted).map(|()| Reply::ok()),
890 Step::Input {
891 id,
892 text,
893 key,
894 args,
895 } => {
896 let value = match key {
897 Some(k) => format_key(&k, args),
898 None => text.unwrap_or_default(),
899 };
900 let node = find(&id)?;
903 day_core::synthesize_text(node, value);
904 day_reactive::flush_sync();
905 Ok(Reply::ok())
906 }
907 Step::SetValue { id, value } => {
908 emit(&id, Event::ValueChanged(value))?;
912 emit(&id, Event::ValueCommitted(value))?;
913 Ok(Reply::ok())
914 }
915 Step::Toggle { id, value } => {
916 let target = match value {
917 Some(v) => v,
918 None => !probe(&id)?.flag,
919 };
920 emit(&id, Event::ToggleChanged(target))?;
921 Ok(Reply::ok())
922 }
923 Step::Activate { id, index } => {
924 emit(&id, Event::ListActivated(index))?;
925 Ok(Reply::ok())
926 }
927 Step::Select {
928 id,
929 index,
930 if_present,
931 } => {
932 if if_present {
933 day_reactive::flush_sync();
936 if !with_tree(|t| t.ui_idle()) {
937 return Err(Reply::fail("ui transitions still settling", true));
938 }
939 if with_tree(|t| t.find_by_id(&id)).is_none() {
940 return Ok(Reply::ok());
941 }
942 }
943 let node = find(&id)?;
944 let state = probe(&id)?;
945 if with_tree(|t| t.node_kind(node)) == Some(day_spec::kinds::PICKER)
946 && (index < 0 || index as usize >= state.options.len())
947 {
948 return Err(Reply::fail(
949 format!(
950 "select {id:?}: index {index} is out of range for {} options",
951 state.options.len()
952 ),
953 false,
954 ));
955 }
956 emit(&id, Event::SelectionChanged(index))?;
957 Ok(Reply::ok())
958 }
959 Step::Reorder { id, from, to } => {
960 let node = find(&id)?;
961 match day_core::list_try_reorder(node, from, to) {
962 Ok(_) => Ok(Reply::ok()),
963 Err(e) => Err(Reply::fail(
966 format!("reorder {id:?} {from}->{to}: {e}"),
967 false,
968 )),
969 }
970 }
971 Step::Undo => drive_undo(false),
972 Step::Redo => drive_undo(true),
973 Step::Expand { id, row, expanded } => {
974 let node = find(&id)?;
975 let driver = day_core::tree_driver(node).ok_or_else(|| {
976 Reply::fail(format!("expand {id:?}: no tree at this node"), false)
977 })?;
978 let token = (driver.resolve_row)(&row).ok_or_else(|| {
979 Reply::fail(format!("expand {id:?}: no row {row:?}"), true)
982 })?;
983 emit(&id, Event::TreeExpanded { token, expanded })?;
984 Ok(Reply::ok())
985 }
986 Step::TreeMove {
987 id,
988 row,
989 parent,
990 index,
991 } => {
992 let node = find(&id)?;
993 let driver = day_core::tree_driver(node).ok_or_else(|| {
994 Reply::fail(format!("tree_move {id:?}: no tree at this node"), false)
995 })?;
996 let token = (driver.resolve_row)(&row).ok_or_else(|| {
997 Reply::fail(format!("tree_move {id:?}: no row {row:?}"), true)
998 })?;
999 let parent_tok = match &parent {
1000 Some(p) => Some((driver.resolve_row)(p).ok_or_else(|| {
1001 Reply::fail(format!("tree_move {id:?}: no parent row {p:?}"), true)
1002 })?),
1003 None => None,
1004 };
1005 match day_core::tree_try_move(node, token, parent_tok, index) {
1006 Ok(()) => Ok(Reply::ok()),
1007 Err(e) => Err(Reply::fail(format!("tree_move {id:?} {row:?}: {e}"), false)),
1009 }
1010 }
1011 Step::DeleteRow { id, row } => {
1012 let node = find(&id)?;
1013 match day_core::list_try_delete(node, row) {
1014 Ok(()) => Ok(Reply::ok()),
1015 Err(e) => Err(Reply::fail(format!("delete_row {id:?} {row}: {e}"), false)),
1018 }
1019 }
1020 Step::SwipeRow {
1021 id,
1022 row,
1023 edge,
1024 action,
1025 label,
1026 key,
1027 } => {
1028 let node = find(&id)?;
1029 let edge = match edge.as_deref() {
1030 None | Some("trailing") => day_spec::SwipeEdge::Trailing,
1031 Some("leading") => day_spec::SwipeEdge::Leading,
1032 Some(other) => {
1033 return Err(Reply::fail(
1034 format!("swipe_row {id:?}: edge {other:?} (leading|trailing)"),
1035 false,
1036 ));
1037 }
1038 };
1039 let expected = match (&label, &key) {
1040 (Some(l), _) => Some(l.clone()),
1041 (None, Some(k)) => Some(format_key(k, None)),
1042 (None, None) => None,
1043 };
1044 match day_core::list_try_swipe(node, row, edge, action, expected.as_deref()) {
1048 Ok(_) => Ok(Reply::ok()),
1049 Err(e) => Err(Reply::fail(format!("swipe_row {id:?} {row}: {e}"), false)),
1053 }
1054 }
1055 Step::WebEval {
1056 id,
1057 script,
1058 contains,
1059 text,
1060 ..
1061 } => {
1062 use std::cell::RefCell;
1069 use std::rc::Rc;
1070 type EvalCell = Rc<RefCell<Option<Result<String, String>>>>;
1071 thread_local! {
1072 static WEB_EVALS: RefCell<
1073 std::collections::HashMap<(String, String), (u32, EvalCell)>,
1074 > = RefCell::new(std::collections::HashMap::new());
1075 }
1076 let node = find(&id)?;
1077 let key = (id.clone(), script.clone());
1078 let pending = WEB_EVALS.with(|m| m.borrow().get(&key).map(|(_, c)| c.clone()));
1079 let Some(cell) = pending else {
1080 let cell: EvalCell = Rc::new(RefCell::new(None));
1081 let done = {
1082 let cell = cell.clone();
1083 Box::new(move |r: Result<String, String>| *cell.borrow_mut() = Some(r))
1084 };
1085 if !day_core::piece_operation(node, "day.webview.eval", &script, done) {
1086 return Err(Reply::fail(
1087 format!(
1088 "web_eval {id:?}: not a web view (or no webview piece registered an evaluator)"
1089 ),
1090 false,
1091 ));
1092 }
1093 WEB_EVALS.with(|m| m.borrow_mut().insert(key, (0, cell)));
1094 return Err(Reply::fail(
1095 format!("web_eval {id:?}: awaiting the engine"),
1096 true,
1097 ));
1098 };
1099 let Some(result) = cell.borrow_mut().take() else {
1100 let stale = WEB_EVALS.with(|m| {
1104 let mut m = m.borrow_mut();
1105 match m.get_mut(&key) {
1106 Some((polls, _)) => {
1107 *polls += 1;
1108 *polls > 25
1109 }
1110 None => false,
1111 }
1112 });
1113 if stale {
1114 WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1115 }
1116 return Err(Reply::fail(
1117 format!("web_eval {id:?}: awaiting the engine"),
1118 true,
1119 ));
1120 };
1121 WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1122 match result {
1123 Err(e) => Err(Reply::fail(format!("web_eval {id:?}: {e}"), true)),
1126 Ok(json) => {
1127 let value = serde_json::from_str::<serde_json::Value>(&json)
1129 .ok()
1130 .and_then(|v| v.as_str().map(str::to_string))
1131 .unwrap_or(json);
1132 let failed = match (&contains, &text) {
1133 (Some(c), _) if !value.contains(c.as_str()) => {
1134 Some(format!("result {value:?} does not contain {c:?}"))
1135 }
1136 (_, Some(t)) if value != *t => {
1137 Some(format!("result {value:?}, expected {t:?}"))
1138 }
1139 _ => None,
1140 };
1141 match failed {
1142 Some(why) => Err(Reply::fail(format!("web_eval {id:?}: {why}"), true)),
1145 None => Ok(Reply::ok()),
1146 }
1147 }
1148 }
1149 }
1150 Step::ContextMenu {
1151 id,
1152 if_present,
1153 item_id,
1154 item,
1155 key,
1156 path,
1157 } => {
1158 if if_present {
1159 day_reactive::flush_sync();
1161 if !with_tree(|t| t.ui_idle()) {
1162 return Err(Reply::fail("ui transitions still settling", true));
1163 }
1164 if with_tree(|t| t.find_by_id(&id)).is_none() {
1165 return Ok(Reply::ok());
1166 }
1167 }
1168 let node = find(&id)?;
1169 let menu = with_tree(|t| t.context_menu_of(node)).ok_or_else(|| {
1170 Reply::fail(
1171 format!("context_menu {id:?}: the element has no menu"),
1172 true,
1173 )
1174 })?;
1175 let items = menu(day_spec::Point::ZERO);
1178 let target_label = match (&item_id, &item, &key) {
1179 (Some(_), _, _) => String::new(),
1180 (None, Some(l), _) => l.clone(),
1181 (None, None, Some(k)) => format_key(k, None),
1182 (None, None, None) => {
1183 return Err(Reply::fail(
1184 "context_menu: needs `item_id:`, `item:` or `key:`",
1185 false,
1186 ));
1187 }
1188 };
1189 let path: Vec<(String, String)> = path
1190 .unwrap_or_default()
1191 .into_iter()
1192 .map(|p| {
1193 let resolved = format_key(&p, None);
1194 (p, resolved)
1195 })
1196 .collect();
1197 let matches = find_menu_actions(
1198 &items,
1199 &target_label,
1200 key.as_deref(),
1201 item_id.as_deref(),
1202 &path,
1203 );
1204 let what = match &item_id {
1205 Some(want) => format!("id {want:?}"),
1206 None => format!("{target_label:?}"),
1207 };
1208 match matches.as_slice() {
1209 [] => Err(Reply::fail(
1210 format!("context_menu {id:?}: no item {what}"),
1211 true,
1212 )),
1213 [(action, enabled, _)] => {
1214 if *action == 0 {
1215 Err(Reply::fail(
1216 format!(
1217 "context_menu {id:?}: {what} runs a native command (no day \
1218 action)"
1219 ),
1220 false,
1221 ))
1222 } else if !enabled {
1223 Err(Reply::fail(
1226 format!("context_menu {id:?}: {what} is disabled"),
1227 true,
1228 ))
1229 } else {
1230 day_core::dispatch_menu_action(*action);
1231 day_reactive::flush_sync();
1232 Ok(Reply::ok())
1233 }
1234 }
1235 _ => Err(Reply::fail(
1236 format!("context_menu {id:?}: {what} is ambiguous; add a path"),
1237 false,
1238 )),
1239 }
1240 }
1241 Step::Menu {
1242 id,
1243 item,
1244 key,
1245 path,
1246 } => {
1247 let target_label = match (&id, &item, &key) {
1248 (Some(_), _, _) => String::new(),
1249 (None, Some(l), _) => l.clone(),
1250 (None, None, Some(k)) => format_key(k, None),
1251 (None, None, None) => {
1252 return Err(Reply::fail("menu: needs `id:`, `item:` or `key:`", false));
1253 }
1254 };
1255 let path: Vec<(String, String)> = path
1259 .unwrap_or_default()
1260 .into_iter()
1261 .map(|p| {
1262 let resolved = format_key(&p, None);
1263 (p, resolved)
1264 })
1265 .collect();
1266 let matches = find_menu_actions(
1267 &day_core::menu::app_menu_model(),
1268 &target_label,
1269 key.as_deref(),
1270 id.as_deref(),
1271 &path,
1272 );
1273 let auto_id = match (matches.is_empty(), key.as_deref()) {
1277 (true, Some("day_preferences")) => {
1278 Some(day_core::windows::preferences_action_id())
1279 }
1280 (true, Some("day_new_window")) => {
1281 Some(day_core::windows::new_window_action_id())
1282 }
1283 (true, Some("day_about")) => Some(day_core::windows::about_action_id()),
1284 (true, Some("day_check_for_updates")) => {
1285 Some(day_core::windows::check_for_updates_action_id())
1286 }
1287 _ => None,
1288 };
1289 if let Some(id) = auto_id
1290 && id != 0
1291 {
1292 day_core::dispatch_menu_action(id);
1293 day_reactive::flush_sync();
1294 return Ok(Reply::ok());
1295 }
1296 let what = match &id {
1299 Some(want) => format!("id {want:?}"),
1300 None => format!("{target_label:?}"),
1301 };
1302 match matches.as_slice() {
1303 [] => Err(Reply::fail(
1304 format!("menu: no item {what}"),
1306 true,
1307 )),
1308 [(action, enabled, _)] => {
1309 if *action == 0 {
1310 Err(Reply::fail(
1311 format!(
1312 "menu: {what} runs a native selector (no day action) — not \
1313 invokable from dayscript"
1314 ),
1315 false,
1316 ))
1317 } else if !enabled {
1318 Err(Reply::fail(format!("menu: {what} is disabled"), true))
1321 } else {
1322 day_core::dispatch_menu_action(*action);
1323 day_reactive::flush_sync();
1324 Ok(Reply::ok())
1325 }
1326 }
1327 many => Err(Reply::fail(
1328 format!(
1329 "menu: {what} is ambiguous — disambiguate with path: {:?}",
1330 many.iter()
1331 .map(|(_, _, p)| p.join(" ▸ "))
1332 .collect::<Vec<_>>()
1333 ),
1334 false,
1335 )),
1336 }
1337 }
1338 Step::Toolbar {
1339 item,
1340 text,
1341 key,
1342 args,
1343 on,
1344 index,
1345 submit,
1346 } => {
1347 let text = match key {
1350 Some(k) => Some(format_key(&k, args)),
1351 None => text,
1352 };
1353 let model = day_core::toolbar::toolbar_model();
1357 let Some(found) = model.iter().find(|i| i.id == item) else {
1358 if item == day_spec::SEARCH_ITEM_ID
1364 && let Some(host) = day_core::inline_search_host()
1365 {
1366 let Some(t) = text else {
1367 return Err(Reply::fail(
1368 "toolbar: day::search rides the navigation surface here, which takes text (or key) only",
1369 false,
1370 ));
1371 };
1372 day_core::enqueue_event(rnode_to_id(host), Event::SearchChanged(t.clone()));
1373 if submit {
1374 day_core::enqueue_event(rnode_to_id(host), Event::SearchSubmitted(t));
1375 }
1376 day_reactive::flush_sync();
1377 return Ok(Reply::ok());
1378 }
1379 return Err(Reply::fail(format!("toolbar: no item {item:?}"), true));
1381 };
1382 if !found.enabled {
1383 return Err(Reply::fail(format!("toolbar: {item:?} is disabled"), false));
1384 }
1385 if found.action == 0 {
1389 return Err(Reply::fail(
1390 format!("toolbar: {item:?} has no command"),
1391 false,
1392 ));
1393 }
1394 if let day_spec::ToolbarItemKind::Segmented { segments, .. } = &found.kind {
1401 let Some(i) = index else {
1402 return Err(Reply::fail(
1403 format!("toolbar: {item:?} is segmented — say `index: <n>`"),
1404 false,
1405 ));
1406 };
1407 if i >= segments.len() {
1408 return Err(Reply::fail(
1409 format!(
1410 "toolbar: {item:?} has {} segments, asked for {i}",
1411 segments.len()
1412 ),
1413 false,
1414 ));
1415 }
1416 day_core::toolbar::dispatch_toolbar_value(
1417 found.action,
1418 &day_spec::ToolbarValue::Selected(i),
1419 );
1420 day_reactive::flush_sync();
1421 return Ok(Reply::ok());
1422 }
1423 if matches!(found.kind, day_spec::ToolbarItemKind::Toggle { .. })
1424 && on.is_none()
1425 && text.is_none()
1426 {
1427 return Err(Reply::fail(
1428 format!("toolbar: {item:?} is a toggle — say `on: true` or `on: false`"),
1429 false,
1430 ));
1431 }
1432 if submit && text.is_none() {
1433 return Err(Reply::fail(
1434 format!("toolbar: submitting {item:?} needs `text:` (or `key:`)"),
1435 false,
1436 ));
1437 }
1438 match (text, on) {
1439 (Some(t), _) => {
1440 day_core::toolbar::synthesize_toolbar_value(
1441 found.action,
1442 &day_spec::ToolbarValue::Text(t.clone()),
1443 );
1444 if submit {
1445 day_reactive::flush_sync();
1446 day_core::toolbar::dispatch_toolbar_value(
1447 found.action,
1448 &day_spec::ToolbarValue::Submit(t),
1449 );
1450 }
1451 }
1452 (None, Some(v)) => day_core::toolbar::dispatch_toolbar_value(
1453 found.action,
1454 &day_spec::ToolbarValue::On(v),
1455 ),
1456 (None, None) => day_core::dispatch_menu_action(found.action),
1457 }
1458 day_reactive::flush_sync();
1459 Ok(Reply::ok())
1460 }
1461 Step::AssertHidden { id } => {
1462 let Some(node) = with_tree(|t| t.find_by_id(&id)) else {
1463 return Ok(Reply::ok());
1464 };
1465 let empty = with_tree(|t| t.node_frame(node))
1466 .is_none_or(|f| f.size.width <= 0.0 || f.size.height <= 0.0);
1467 let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1468 if empty || (native.found && native.visible == Some(false)) {
1469 Ok(Reply::ok())
1470 } else {
1471 Err(Reply::fail(format!("element {id:?} is shown"), true))
1472 }
1473 }
1474 Step::AssertMissing { id } => match with_tree(|t| t.find_by_id(&id)) {
1475 Some(_) => Err(Reply::fail(format!("element {id:?} is present"), true)),
1476 None => Ok(Reply::ok()),
1477 },
1478 Step::AssertText {
1479 id,
1480 text,
1481 key,
1482 args,
1483 ..
1484 } => {
1485 let actual = norm(&probe(&id)?.text);
1486 let expected = if let Some(k) = key {
1487 norm(&format_key(&k, args))
1488 } else {
1489 norm(&text.unwrap_or_default())
1490 };
1491 if actual == expected {
1492 Ok(Reply::ok())
1493 } else {
1494 Err(Reply::fail(
1495 format!("{id:?}: expected {expected:?}, found {actual:?}"),
1496 true,
1497 ))
1498 }
1499 }
1500 Step::AssertNoPlaceholders { allow } => {
1501 let unexpected: Vec<&str> = day_spec::placeholder::seen()
1502 .into_iter()
1503 .filter(|k| !allow.iter().any(|a| a == k))
1504 .collect();
1505 if unexpected.is_empty() {
1506 Ok(Reply::ok())
1507 } else {
1508 Err(Reply::fail(
1509 format!(
1510 "rendered a placeholder for {} — no renderer on this backend. Enable \
1511 the piece's feature for this toolkit, or add the kind to `allow:` if \
1512 the gap is intended.",
1513 unexpected.join(", ")
1514 ),
1515 true,
1516 ))
1517 }
1518 }
1519 Step::AssertValue { id, value } => {
1520 let p = probe(&id)?;
1521 let ok = match &value {
1522 serde_json::Value::Bool(b) => p.flag == *b,
1523 serde_json::Value::Number(n) => {
1524 (p.value - n.as_f64().unwrap_or(f64::NAN)).abs() < 0.5
1525 }
1526 serde_json::Value::String(s) => norm(&p.text) == norm(s),
1527 _ => false,
1528 };
1529 if ok {
1530 Ok(Reply::ok())
1531 } else {
1532 Err(Reply::fail(
1533 format!(
1534 "{id:?}: expected {value}, probe text={:?} value={} flag={}",
1535 p.text, p.value, p.flag
1536 ),
1537 true,
1538 ))
1539 }
1540 }
1541 Step::AssertAnnounced { text } => {
1542 let said = day_core::conformance::announcements();
1543 if said.iter().any(|s| norm(s) == norm(&text)) {
1544 Ok(Reply::ok())
1545 } else {
1546 Err(Reply::fail(
1547 format!("{text:?} was not announced (announced: {said:?})"),
1548 true,
1549 ))
1550 }
1551 }
1552 Step::AssertOpenedUrl { url } => {
1553 let opened = day_core::conformance::opened_urls();
1554 if opened.contains(&url) {
1555 Ok(Reply::ok())
1556 } else {
1557 Err(Reply::fail(
1558 format!("{url:?} was not opened (opened: {opened:?})"),
1559 true,
1560 ))
1561 }
1562 }
1563 Step::AssertFrame {
1564 id,
1565 width,
1566 height,
1567 x,
1568 y,
1569 relative_to,
1570 tolerance,
1571 } => {
1572 let tol = tolerance.unwrap_or(1.0);
1573 let node = find(&id)?;
1574 let day = with_tree(|t| t.node_frame(node))
1575 .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1576 let native = with_tree(|t| t.read_native(node)).and_then(|n| n.frame);
1577 let (base_day, base_native) = match &relative_to {
1578 Some(other) => {
1579 let o = find(other)?;
1580 let f = with_tree(|t| t.node_frame(o))
1581 .ok_or_else(|| Reply::fail(format!("{other:?} has no frame"), true))?;
1582 let n = with_tree(|t| t.read_native(o)).and_then(|n| n.frame);
1583 (f.origin, n.map(|r| r.origin))
1584 }
1585 None => (day_spec::Point::ZERO, Some(day_spec::Point::ZERO)),
1586 };
1587 let mut fails = Vec::new();
1588 let mut check = |source: &str, f: day_spec::Rect, base: day_spec::Point| {
1589 let got = [
1590 ("width", f.size.width, width),
1591 ("height", f.size.height, height),
1592 ("x", f.origin.x - base.x, x),
1593 ("y", f.origin.y - base.y, y),
1594 ];
1595 for (name, value, want) in got {
1596 if let Some(w) = want
1597 && (value - w).abs() > tol
1598 {
1599 fails.push(format!("{source} {name} {value:.1} ≠ {w}"));
1600 }
1601 }
1602 };
1603 check("Day", day, base_day);
1604 let unread = match (native, base_native) {
1605 (Some(f), Some(base)) => {
1606 check("native", f, base);
1607 false
1608 }
1609 _ => true,
1610 };
1611 if !fails.is_empty() {
1612 return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
1613 }
1614 Ok(Reply {
1615 data: unread.then(|| serde_json::json!({ "unread": ["frame"] })),
1616 ..Reply::ok()
1617 })
1618 }
1619 Step::SamplePixel {
1620 id,
1621 x,
1622 y,
1623 color,
1624 tolerance,
1625 } => {
1626 let want = parse_hex_color(&color).ok_or_else(|| {
1627 Reply::fail(format!("sample_pixel: {color:?} is not #rrggbb"), false)
1628 })?;
1629 if day_core::capability(day_spec::Cap::Snapshot) == day_spec::Support::Unsupported {
1630 return Ok(Reply {
1631 data: Some(serde_json::json!({ "unread": ["pixel"] })),
1632 ..Reply::ok()
1633 });
1634 }
1635 day_reactive::flush_sync();
1636 if !with_tree(|t| t.ui_idle()) {
1637 return Err(Reply::fail("ui transitions still settling", true));
1638 }
1639 hosts_settled()?;
1640 let readiness = with_tree(|t| t.prepare_snapshot(None, revision))
1641 .map_err(|e| Reply::fail(format!("sample_pixel readiness: {e}"), false))?;
1642 if readiness == day_spec::capture::Readiness::Pending {
1643 return Err(Reply {
1644 capture_pending: true,
1645 ..Reply::fail("waiting for a render checkpoint", true)
1646 });
1647 }
1648 let node = find(&id)?;
1649 let frame = with_tree(|t| t.node_frame(node))
1650 .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1651 let window = with_tree(|t| t.node_frame(t.root_node()))
1652 .ok_or_else(|| Reply::fail("the window has no frame", true))?;
1653 let bytes = with_tree(|t| t.snapshot())
1654 .map_err(|e| Reply::fail(format!("sample_pixel capture: {e}"), true))?;
1655 let origin = with_tree(|t| t.snapshot_origin());
1656 let Ok(img) = png::decode(&bytes) else {
1659 return Ok(Reply {
1660 data: Some(serde_json::json!({ "unread": ["pixel"] })),
1661 ..Reply::ok()
1662 });
1663 };
1664 let (scale, left, above) = if let Some(o) = origin {
1671 (
1672 img.width as f64 / (window.size.width + 2.0 * o.x).max(1.0),
1673 o.x,
1674 o.y,
1675 )
1676 } else {
1677 let scale = img.width as f64 / window.size.width.max(1.0);
1678 let above = (img.height as f64 / scale - window.size.height).max(0.0);
1679 (scale, 0.0, above)
1680 };
1681 let px = ((left + frame.origin.x - window.origin.x + x * frame.size.width) * scale)
1682 .floor()
1683 .max(0.0) as usize;
1684 let py = ((above + frame.origin.y - window.origin.y + y * frame.size.height)
1685 * scale)
1686 .floor()
1687 .max(0.0) as usize;
1688 let got = img.pixel(px, py).ok_or_else(|| {
1689 Reply::fail(
1690 format!("{id:?}: ({px}, {py}) is outside the capture"),
1691 false,
1692 )
1693 })?;
1694 let tol = tolerance.unwrap_or(64);
1695 let near = (0..3).all(|i| got[i].abs_diff(want[i]) <= tol);
1696 if near {
1697 Ok(Reply::ok())
1698 } else {
1699 Err(Reply::fail(
1700 format!(
1701 "{id:?} at ({x}, {y}): #{:02x}{:02x}{:02x} ≠ {color}",
1702 got[0], got[1], got[2]
1703 ),
1704 true,
1705 ))
1706 }
1707 }
1708 Step::AssertNative {
1709 id,
1710 text,
1711 number,
1712 checked,
1713 enabled,
1714 visible,
1715 } => {
1716 let node = find(&id)?;
1717 let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1718 if let Some(want) = enabled
1719 && probe(&id)?.enabled != want
1720 {
1721 return Err(Reply::fail(
1722 format!("{id:?}: Day has enabled={}, expected {want}", !want),
1723 true,
1724 ));
1725 }
1726 let mut unread = Vec::new();
1727 let mut fails = Vec::new();
1728 let mut check = |field: &str,
1729 got: Option<String>,
1730 want: Option<String>,
1731 eq: bool| match (got, want) {
1732 (None, Some(_)) => unread.push(field.to_owned()),
1733 (Some(g), Some(w)) if !eq => {
1734 fails.push(format!("native {field} {g} ≠ expected {w}"));
1735 }
1736 _ => {}
1737 };
1738 let text_eq =
1739 matches!((&native.text, &text), (Some(g), Some(w)) if norm(g) == norm(w));
1740 check(
1741 "text",
1742 native.text.as_ref().map(|t| format!("{t:?}")),
1743 text.as_ref().map(|t| format!("{t:?}")),
1744 text_eq,
1745 );
1746 let number_eq = matches!((native.number, number), (Some(g), Some(w)) if (g - w).abs() <= 1e-3 * w.abs().max(1.0));
1747 check(
1748 "number",
1749 native.number.map(|n| n.to_string()),
1750 number.map(|n| n.to_string()),
1751 number_eq,
1752 );
1753 check(
1754 "checked",
1755 native.checked.map(|b| b.to_string()),
1756 checked.map(|b| b.to_string()),
1757 native.checked == checked,
1758 );
1759 check(
1760 "enabled",
1761 native.enabled.map(|b| b.to_string()),
1762 enabled.map(|b| b.to_string()),
1763 native.enabled == enabled,
1764 );
1765 check(
1766 "visible",
1767 native.visible.map(|b| b.to_string()),
1768 visible.map(|b| b.to_string()),
1769 native.visible == visible,
1770 );
1771 if !fails.is_empty() {
1772 return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
1773 }
1774 Ok(Reply {
1775 data: (!unread.is_empty()).then(|| serde_json::json!({ "unread": unread })),
1776 ..Reply::ok()
1777 })
1778 }
1779 Step::ScrollTo { id, edge, x, y } => {
1780 let node = find(&id)?;
1781 let target = match (edge.as_deref(), x, y) {
1782 (Some("top"), _, _) => day_core::ScrollTarget::Top,
1783 (Some("bottom"), _, _) => day_core::ScrollTarget::Bottom,
1784 (Some("leading"), _, _) => day_core::ScrollTarget::Leading,
1785 (Some("trailing"), _, _) => day_core::ScrollTarget::Trailing,
1786 (Some(other), _, _) => {
1787 return Err(Reply::fail(
1788 format!(
1789 "scroll_to: unknown edge {other:?} (top|bottom|leading|trailing)"
1790 ),
1791 false,
1792 ));
1793 }
1794 (None, None, None) => {
1795 let ok = with_tree(|t| t.scroll_reveal(node, false));
1797 if !ok {
1798 return Err(Reply::fail(
1799 format!("scroll_to: {id:?} has no enclosing scroll"),
1800 true,
1801 ));
1802 }
1803 day_reactive::flush_sync();
1804 return Ok(Reply::ok());
1805 }
1806 (None, x, y) => day_core::ScrollTarget::Offset(day_spec::Point::new(
1807 x.unwrap_or(0.0),
1808 y.unwrap_or(0.0),
1809 )),
1810 };
1811 let ok = with_tree(|t| t.scroll_to_target(node, &target, false));
1812 if !ok {
1813 return Err(Reply::fail(
1814 format!("scroll_to: {id:?} does not support this scroll target"),
1815 true,
1816 ));
1817 }
1818 day_reactive::flush_sync();
1819 Ok(Reply::ok())
1820 }
1821 Step::Focus { id, focused } => {
1822 let want = focused.unwrap_or(true);
1823 let node = find(&id)?;
1824 with_tree(|t| t.focus_node(node, want));
1825 day_reactive::flush_sync();
1826 if probe(&id)?.focused != want
1832 && FOCUS_WAITS.fetch_add(1, Ordering::Relaxed) < FOCUS_WAIT_POLLS
1833 {
1834 return Err(Reply::fail(
1835 format!("{id:?}: waiting for the toolkit to report focused={want}"),
1836 true,
1837 ));
1838 }
1839 FOCUS_WAITS.store(0, Ordering::Relaxed);
1840 Ok(Reply::ok())
1841 }
1842 Step::AssertFocused { id, focused } => {
1843 let want = focused.unwrap_or(true);
1844 let got = probe(&id)?.focused;
1845 if got == want {
1846 Ok(Reply::ok())
1847 } else {
1848 Err(Reply::fail(
1849 format!("{id:?}: expected focused={want}, found focused={got}"),
1850 true,
1851 ))
1852 }
1853 }
1854 Step::CloseWindow { window } => {
1855 let handle = match &window {
1856 Some(key) => day_core::window_by_key(key),
1857 None => day_core::initial_window(),
1858 };
1859 if let Some(handle) = handle {
1860 handle.close();
1861 }
1862 day_reactive::flush_sync();
1863 Ok(Reply::ok())
1864 }
1865 Step::Screenshot {
1866 window, in_process, ..
1867 } => {
1868 day_reactive::flush_sync();
1869 if !with_tree(|t| t.ui_idle()) {
1872 return Err(Reply::fail("ui transitions still settling", true));
1873 }
1874 hosts_settled()?;
1875 let root = match window.as_deref() {
1876 Some(key) => Some(
1877 day_core::windows::window_root_by_key(key)
1878 .ok_or_else(|| Reply::fail(format!("no window {key:?}"), true))?,
1879 ),
1880 None => None,
1881 };
1882 let readiness = with_tree(|t| t.prepare_snapshot(root, revision))
1883 .map_err(|e| Reply::fail(format!("screenshot readiness: {e}"), false))?;
1884 if readiness == day_spec::capture::Readiness::Pending {
1885 return Err(Reply {
1886 capture_pending: true,
1887 ..Reply::fail("waiting for screenshot render checkpoint", true)
1888 });
1889 }
1890 let capture_revision =
1891 (readiness == day_spec::capture::Readiness::Ready).then_some(revision);
1892 if !in_process {
1893 return Ok(Reply {
1894 capture_revision,
1895 ..Reply::ok()
1896 });
1897 }
1898 let png = match window.as_deref() {
1899 Some(key) => match day_core::windows::window_root_by_key(key) {
1900 Some(root) => with_tree(|t| t.snapshot_of(root)),
1901 None => return Err(Reply::fail(format!("no window {key:?}"), true)),
1904 },
1905 None => with_tree(|t| t.snapshot()),
1906 };
1907 match png {
1908 Ok(bytes) => {
1909 SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
1910 SNAPSHOT_WORKS.store(true, Ordering::Relaxed);
1911 Ok(Reply {
1912 ok: true,
1913 png_base64: Some(b64encode(&bytes)),
1914 capture_revision: Some(revision),
1915 ..Default::default()
1916 })
1917 }
1918 Err(_)
1925 if (SNAPSHOT_WORKS.load(Ordering::Relaxed)
1926 || !SNAPSHOT_NEVER.load(Ordering::Relaxed))
1927 && SNAPSHOT_MISSES.fetch_add(1, Ordering::Relaxed)
1928 < SNAPSHOT_RETRIES =>
1929 {
1930 Err(Reply::fail("the window has nothing to capture yet", true))
1931 }
1932 Err(_) => {
1933 SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
1934 if !SNAPSHOT_WORKS.load(Ordering::Relaxed) {
1935 SNAPSHOT_NEVER.store(true, Ordering::Relaxed);
1936 }
1937 Ok(Reply {
1938 ok: true,
1939 screenshot_unsupported: true,
1940 ..Default::default()
1941 })
1942 }
1943 }
1944 }
1945 Step::Pause { secs } => {
1946 let _ = secs;
1948 Ok(Reply::ok())
1949 }
1950 Step::ExpectExit { within } => {
1951 let _ = within;
1954 Ok(Reply::ok())
1955 }
1956 Step::SizeClass { width, height } => {
1957 if width == "auto" {
1958 day_core::restore_reported_size_class();
1959 day_reactive::flush_sync();
1960 return Ok(Reply::ok());
1961 }
1962 let width = parse_width_class(&width).ok_or_else(|| {
1963 Reply::fail(
1964 format!(
1965 "size_class: unknown width {width:?} \
1966 (auto|compact|medium|expanded|large|extra-large)"
1967 ),
1968 false,
1969 )
1970 })?;
1971 let height = match height.as_deref() {
1972 None => day_spec::HeightClass::Expanded,
1973 Some(h) => parse_height_class(h).ok_or_else(|| {
1974 Reply::fail(
1975 format!("size_class: unknown height {h:?} (compact|medium|expanded)"),
1976 false,
1977 )
1978 })?,
1979 };
1980 day_core::override_size_class(day_spec::SizeClass { width, height });
1981 day_reactive::flush_sync();
1984 Ok(Reply::ok())
1985 }
1986 Step::Resize {
1987 width,
1988 height,
1989 restore,
1990 } => {
1991 if !with_tree(|t| t.ui_idle()) {
1996 return Err(Reply::fail("ui transitions still settling", true));
1997 }
1998 day_core::restore_reported_size_class();
2000 day_reactive::flush_sync();
2001 let (Some(w), Some(h)) = (width, height) else {
2002 let _ = restore;
2005 return Ok(Reply::ok());
2006 };
2007 let want = day_spec::SizeClass::from_size(w, h).width;
2018 let have = day_core::size_class();
2019 if have.map(|c| c.width) == Some(want) {
2020 Ok(Reply::ok())
2021 } else {
2022 Err(Reply::fail(
2024 format!(
2025 "resize to {w}x{h} wants width {want:?}, window reports {have:?} \
2026 (a width within a few points of a breakpoint can fall the other \
2027 side of it once safe-area insets come out — aim for mid-bucket)"
2028 ),
2029 true,
2030 ))
2031 }
2032 }
2033 Step::OpenUrl { url } => {
2034 day_core::request_open_url(&url);
2035 Ok(Reply::ok())
2036 }
2037 Step::DeepLink { url } => {
2038 day_reactive::flush_sync();
2039 let route = day_spec::route_of_url(&url);
2040 if day_core::navigate(&route) {
2041 day_reactive::flush_sync();
2042 Ok(Reply::ok())
2043 } else {
2044 Err(Reply::fail(format!("no route for {url:?}"), true))
2046 }
2047 }
2048 Step::Navigate { route } => {
2049 day_reactive::flush_sync();
2050 if day_core::navigate(&route) {
2051 day_reactive::flush_sync();
2052 Ok(Reply::ok())
2053 } else {
2054 Err(Reply::fail(format!("no route {route:?}"), true))
2056 }
2057 }
2058 Step::NavBack { native } => {
2059 if native && !with_tree(|t| t.ui_idle()) {
2068 return Err(Reply::fail("ui transitions still settling", true));
2069 }
2070 let popped = if native {
2071 with_tree(|t| t.native_back())
2072 } else {
2073 day_core::nav_back()
2074 };
2075 if popped {
2076 if !native {
2077 day_reactive::flush_sync();
2078 }
2079 Ok(Reply::ok())
2080 } else if day_core::size_class().is_some_and(day_spec::SizeClass::prefers_split) {
2081 Ok(Reply::ok())
2095 } else {
2096 Err(Reply::fail("nothing to pop", true))
2097 }
2098 }
2099 Step::AssertRoute { route } => {
2100 let current = day_core::current_route();
2101 if current.as_deref() == Some(route.as_str()) {
2102 Ok(Reply::ok())
2103 } else {
2104 Err(Reply::fail(
2105 format!("expected route {route:?}, current {current:?}"),
2106 true,
2107 ))
2108 }
2109 }
2110 Step::DialogMode { mode } => {
2111 let mode = match mode {
2112 DialogMode::Native => day_core::PresentationMode::Native,
2113 DialogMode::Scripted => day_core::PresentationMode::Scripted,
2114 };
2115 day_core::set_presentation_mode(mode).map_err(|why| Reply::fail(why, false))?;
2116 Ok(Reply::ok())
2117 }
2118 Step::AssertNotPresented => {
2119 if let Some((_, spec)) = day_core::pending_presentation() {
2120 Err(Reply::fail(
2121 format!("unanswered presentation: {:?}", spec.title()),
2122 true,
2123 ))
2124 } else {
2125 Ok(Reply::ok())
2126 }
2127 }
2128 Step::AssertPresented { title } => match day_core::pending_presentation() {
2129 Some((_, spec)) => {
2130 let actual = norm(spec.title());
2131 match title {
2132 Some(want) if norm(&want) != actual => Err(Reply::fail(
2133 format!("modal title {actual:?} != expected {want:?}"),
2134 true,
2135 )),
2136 _ => Ok(Reply::ok()),
2137 }
2138 }
2139 None => Err(Reply::fail("no modal presented", true)),
2140 },
2141 Step::Respond {
2142 button,
2143 text,
2144 path,
2145 dismiss,
2146 } => {
2147 let Some((req, _)) = day_core::pending_presentation() else {
2148 return Err(Reply::fail("no modal to respond to", true));
2149 };
2150 let result = if dismiss {
2151 PresentResult::Dismissed
2152 } else if let Some(t) = text {
2153 PresentResult::Text(t)
2154 } else if let Some(p) = path {
2155 let pb = std::path::PathBuf::from(&p);
2158 let full = if pb.is_absolute() {
2159 pb
2160 } else {
2161 day_core::app_temp_dir().join(pb)
2162 };
2163 PresentResult::Files(vec![full.to_string_lossy().into_owned()])
2164 } else if let Some(i) = button {
2165 PresentResult::Button(i)
2166 } else {
2167 PresentResult::Dismissed
2168 };
2169 let _ = day_core::respond_presentation(req, result);
2170 day_reactive::flush_sync();
2171 Ok(Reply::ok())
2172 }
2173 Step::Tests => Ok(Reply {
2174 data: Some(conformance::listing().map_err(|e| Reply::fail(e, false))?),
2175 ..Reply::ok()
2176 }),
2177 Step::RunTests {
2178 filter,
2179 shots,
2180 case_timeout_secs,
2181 ..
2182 } => conformance::run_tests(&filter, shots, case_timeout_secs),
2183 Step::A11yAudit { id } => {
2184 let rows = with_tree(|t| t.a11y_nodes());
2185 let rows: Vec<_> = match &id {
2186 Some(want) => rows.into_iter().filter(|(nid, ..)| nid == want).collect(),
2187 None => rows,
2188 };
2189 if let Some(want) = &id
2190 && rows.is_empty()
2191 {
2192 return Err(Reply::fail(
2193 format!("a11y_audit: no element {want:?}"),
2194 true,
2195 ));
2196 }
2197 let mut fails = Vec::new();
2198 for (nid, _kind, expected, actual) in &rows {
2199 audit_a11y_node(nid, expected, actual, &mut fails);
2200 }
2201 if !fails.is_empty() {
2202 return Err(Reply::fail(
2203 format!("a11y_audit: {}", fails.join("; ")),
2204 false,
2205 ));
2206 }
2207 Ok(Reply::ok())
2208 }
2209 }
2210 })();
2211 let mut reply = result.unwrap_or_else(|r| r);
2212 if reply.ok
2213 && !absent_optional_action
2214 && let (Some(class), Some(id)) = (evidence_class, evidence_id)
2215 && let Ok(catalog) = id_catalog()
2216 && let Ok(d) = catalog.resolve(&id)
2217 {
2218 reply.id_evidence = Box::new([day_script_protocol::IdEvidence {
2219 family: d.family.clone(),
2220 class,
2221 }]);
2222 }
2223 reply.fast_animations = Some(day_core::testing::fast_animations());
2224 reply
2225}
2226
2227fn audit_a11y_node(
2230 nid: &str,
2231 expected: &day_spec::A11yProps,
2232 actual: &day_spec::NativeSnapshot,
2233 fails: &mut Vec<String>,
2234) {
2235 if !actual.found || actual.visible == Some(false) {
2236 return;
2237 }
2238 if actual.identifier.as_deref() != Some(nid) {
2239 fails.push(format!(
2240 "{nid}: native identifier {:?} ≠ {nid:?}",
2241 actual.identifier
2242 ));
2243 }
2244 if expected.role != day_spec::Role::None
2249 && actual.role != day_spec::Role::None
2250 && !role_eq(expected.role, actual.role)
2251 {
2252 fails.push(format!(
2253 "{nid}: role {:?} ≠ expected {:?}",
2254 actual.role, expected.role
2255 ));
2256 }
2257 if let Some(lbl) = &expected.label
2258 && actual.label.as_deref() != Some(lbl.as_str())
2259 {
2260 fails.push(format!(
2261 "{nid}: label {:?} ≠ expected {lbl:?}",
2262 actual.label
2263 ));
2264 }
2265 if let Some(val) = &expected.value
2266 && actual.value.as_deref() != Some(val.as_str())
2267 {
2268 fails.push(format!(
2269 "{nid}: value {:?} ≠ expected {val:?}",
2270 actual.value
2271 ));
2272 }
2273}
2274
2275fn role_eq(a: day_spec::Role, b: day_spec::Role) -> bool {
2278 use day_spec::Role::Heading;
2279 matches!((a, b), (Heading(_), Heading(_))) || a == b
2280}
2281
2282const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2287
2288#[must_use]
2289pub fn b64encode(data: &[u8]) -> String {
2290 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
2291 for chunk in data.chunks(3) {
2292 let b = [
2293 chunk[0],
2294 *chunk.get(1).unwrap_or(&0),
2295 *chunk.get(2).unwrap_or(&0),
2296 ];
2297 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
2298 out.push(B64[(n >> 18) as usize & 63] as char);
2299 out.push(B64[(n >> 12) as usize & 63] as char);
2300 out.push(if chunk.len() > 1 {
2301 B64[(n >> 6) as usize & 63] as char
2302 } else {
2303 '='
2304 });
2305 out.push(if chunk.len() > 2 {
2306 B64[n as usize & 63] as char
2307 } else {
2308 '='
2309 });
2310 }
2311 out
2312}
2313
2314#[must_use]
2315pub fn b64decode(s: &str) -> Vec<u8> {
2316 let val = |c: u8| B64.iter().position(|&x| x == c).unwrap_or(0) as u32;
2317 let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'\n' && c != b'\r').collect();
2318 let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
2319 for chunk in bytes.chunks(4) {
2320 if chunk.len() < 4 {
2321 break;
2322 }
2323 #[expect(
2324 clippy::naive_bytecount,
2325 reason = "the chunk is four bytes; a byte-counting dependency would buy nothing"
2326 )]
2327 let pad = chunk.iter().filter(|&&c| c == b'=').count();
2328 let n = (val(chunk[0]) << 18)
2329 | (val(chunk[1]) << 12)
2330 | (val(if chunk[2] == b'=' { b'A' } else { chunk[2] }) << 6)
2331 | val(if chunk[3] == b'=' { b'A' } else { chunk[3] });
2332 out.push((n >> 16) as u8);
2333 if pad < 2 {
2334 out.push((n >> 8) as u8);
2335 }
2336 if pad < 1 {
2337 out.push(n as u8);
2338 }
2339 }
2340 out
2341}
2342
2343#[cfg(test)]
2344mod tests {
2345 use super::*;
2346
2347 #[test]
2348 fn a11y_audit_checks_metadata_when_visible_or_visibility_is_unknown() {
2349 let expected = day_spec::A11yProps {
2351 label: Some("Fixture list".into()),
2352 ..Default::default()
2353 };
2354 let mut actual = day_spec::NativeSnapshot {
2355 found: true,
2356 identifier: Some("fixture-list".into()),
2357 visible: Some(false),
2358 ..Default::default()
2359 };
2360 let mut fails = Vec::new();
2361 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2362 assert!(
2363 fails.is_empty(),
2364 "hidden panes need not expose their labels"
2365 );
2366
2367 for visible in [Some(true), None] {
2368 actual.visible = visible;
2369 fails.clear();
2370 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2371 assert_eq!(
2372 fails.len(),
2373 1,
2374 "missing labels must still fail: {visible:?}"
2375 );
2376 assert!(fails[0].contains("label None"));
2377 }
2378
2379 actual.visible = Some(true);
2380 actual.label = expected.label.clone();
2381 fails.clear();
2382 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2383 assert!(
2384 fails.is_empty(),
2385 "the list exposes its label when shown again"
2386 );
2387
2388 actual.label = None;
2389 actual.found = false;
2390 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2391 assert!(
2392 fails.is_empty(),
2393 "unreadable accessibility nodes remain unsupported"
2394 );
2395 }
2396
2397 #[test]
2398 fn dialog_steps_hold_requests_until_an_explicit_response() {
2399 use day_spec::present::{PresentResult, PresentSpec};
2400 use std::future::Future;
2401 use std::task::{Context, Poll, Waker};
2402 assert!(serde_json::from_str::<Step>(r#"{"op":"dialog_mode","mode":"typo"}"#).is_err());
2403 let mode: Step = serde_json::from_str(r#"{"op":"dialog_mode","mode":"scripted"}"#).unwrap();
2404 assert!(exec(mode, 0).ok);
2405 assert!(exec(Step::AssertNotPresented, 0).ok);
2406 let mut future = Box::pin(day_core::present(PresentSpec::OpenFile {
2408 title: "Choose file".into(),
2409 filters: vec![],
2410 multiple: false,
2411 }));
2412 let mut cx = Context::from_waker(Waker::noop());
2413 assert!(future.as_mut().poll(&mut cx).is_pending());
2414 assert!(
2415 exec(
2416 Step::AssertPresented {
2417 title: Some("Choose file".into())
2418 },
2419 0
2420 )
2421 .ok
2422 );
2423 assert!(!exec(Step::AssertNotPresented, 0).ok);
2424 let refused = exec(
2425 Step::DialogMode {
2426 mode: DialogMode::Native,
2427 },
2428 0,
2429 );
2430 assert!(!refused.ok && !refused.retryable);
2431 assert!(
2432 exec(
2433 Step::Respond {
2434 button: None,
2435 text: None,
2436 path: None,
2437 dismiss: true
2438 },
2439 0
2440 )
2441 .ok
2442 );
2443 assert_eq!(
2444 future.as_mut().poll(&mut cx),
2445 Poll::Ready(PresentResult::Dismissed)
2446 );
2447 assert!(exec(Step::AssertNotPresented, 0).ok);
2448 assert!(
2449 exec(
2450 Step::DialogMode {
2451 mode: DialogMode::Native
2452 },
2453 0
2454 )
2455 .ok
2456 );
2457 }
2458
2459 #[test]
2460 fn optional_tap_only_skips_absent_elements_after_transitions_settle() {
2461 use day_pieces::prelude::*;
2462 let _guard = ENV_LOCK
2463 .lock()
2464 .unwrap_or_else(std::sync::PoisonError::into_inner);
2465 day_core::uninstall_tree();
2466 let enabled = Signal::new(false);
2467 let presses = Signal::new(0);
2468 let (mock, probe) = day_mock::MockToolkit::new();
2469 day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2470 button("Remove fixture")
2471 .enabled(move || enabled.get())
2472 .action(move || presses.update(|n| *n += 1))
2473 .id(day_core::id!(remove_fixture))
2474 .height(50.)
2475 .grow(Dimension::Width)
2476 .any()
2477 });
2478 let tap = |id, optional| {
2479 exec(
2480 serde_json::from_value(serde_json::json!({
2481 "op": "tap", "id": id, "if_present": optional
2482 }))
2483 .unwrap(),
2484 1,
2485 )
2486 };
2487 assert!(!tap("missing", false).ok);
2488 let absent = tap("missing", true);
2489 assert!(absent.ok);
2490 assert!(absent.id_evidence.is_empty());
2491 probe.state.borrow_mut().ui_busy = true;
2492 assert!(!tap("missing", true).ok);
2493 probe.state.borrow_mut().ui_busy = false;
2494 let disabled = tap("remove_fixture", true);
2495 assert!(!disabled.ok && disabled.retryable);
2496 assert_eq!(presses.get(), 0);
2497 enabled.set(true);
2498 id_catalog().expect("the compiled test fixture registry is valid");
2499 let present = tap("remove_fixture", true);
2500 assert!(present.ok);
2501 assert_eq!(present.id_evidence.len(), 1);
2502 assert_eq!(present.id_evidence[0].family, "remove_fixture");
2503 assert_eq!(
2504 present.id_evidence[0].class,
2505 day_script_protocol::EvidenceClass::Interaction
2506 );
2507 assert_eq!(presses.get(), 1);
2508 day_core::uninstall_tree();
2509 }
2510
2511 #[test]
2516 fn nav_back_steps_reach_the_system_back_handler() {
2517 use day_pieces::prelude::*;
2518 let _guard = ENV_LOCK
2519 .lock()
2520 .unwrap_or_else(std::sync::PoisonError::into_inner);
2521 day_core::uninstall_tree();
2522 let enabled = Signal::new(true);
2523 let backs = Signal::new(0);
2524 let (mock, probe) = day_mock::MockToolkit::new();
2525 day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2526 label("Fixture page")
2527 .on_system_back(move || enabled.get(), move || backs.update(|n| *n += 1))
2528 .any()
2529 });
2530 let back = |native: bool| exec(Step::NavBack { native }, 1);
2531 assert!(back(false).ok);
2532 assert_eq!(backs.get(), 1);
2533 assert!(back(true).ok);
2534 assert_eq!(backs.get(), 2);
2535 enabled.set(false);
2536 day_reactive::flush_sync();
2537 assert!(!probe.system_back_armed());
2538 let _ = back(false);
2540 let _ = back(true);
2541 assert_eq!(backs.get(), 2);
2542 day_core::uninstall_tree();
2543 }
2544
2545 #[test]
2546 fn tap_waits_for_navigation_and_enabled_state_before_dispatching_once() {
2547 use day_pieces::prelude::*;
2548 let _guard = ENV_LOCK
2549 .lock()
2550 .unwrap_or_else(std::sync::PoisonError::into_inner);
2551 day_core::uninstall_tree();
2552 let enabled = Signal::new(false);
2553 let presses = Signal::new(0);
2554 let (mock, probe) = day_mock::MockToolkit::new();
2555 day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2556 button("Fixture download")
2557 .enabled(move || enabled.get())
2558 .action(move || presses.update(|n| *n += 1))
2559 .id(day_core::id!(fixture_download))
2560 .height(50.)
2561 .grow(Dimension::Width)
2562 .any()
2563 });
2564 let tap = || {
2565 exec(
2566 serde_json::from_value(serde_json::json!({
2567 "op": "tap", "id": "fixture_download"
2568 }))
2569 .unwrap(),
2570 1,
2571 )
2572 };
2573 let reply = tap();
2574 assert!(!reply.ok && reply.retryable);
2575 assert!(reply.error.unwrap().contains("disabled"));
2576 assert_eq!(presses.get(), 0);
2577 enabled.set(true);
2578 probe.state.borrow_mut().ui_busy = true;
2579 assert!(!tap().ok);
2580 assert!(!exec(Step::WaitIdle, 1).ok);
2581 assert_eq!(presses.get(), 0);
2582 probe.state.borrow_mut().ui_busy = false;
2583 assert!(exec(Step::WaitIdle, 1).ok);
2584 assert!(tap().ok);
2585 assert_eq!(presses.get(), 1);
2586 day_core::uninstall_tree();
2587 }
2588
2589 #[test]
2590 fn capture_acknowledgments_are_optional_and_pending_stays_internal() {
2591 let old: Reply = serde_json::from_str(r#"{"ok":true}"#).unwrap();
2592 assert_eq!(old.capture_revision, None);
2593 assert_eq!(old.fast_animations, None);
2594 let reply = Reply {
2595 capture_revision: Some(73),
2596 fast_animations: Some(true),
2597 capture_pending: true,
2598 ..Reply::ok()
2599 };
2600 let json = serde_json::to_value(reply).unwrap();
2601 assert_eq!(json["capture_revision"], 73);
2602 assert!(json.get("capture_pending").is_none());
2603 let decoded: Reply = serde_json::from_value(json).unwrap();
2604 assert_eq!(decoded.capture_revision, Some(73));
2605 assert_eq!(decoded.fast_animations, Some(true));
2606 }
2607
2608 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2610
2611 #[test]
2615 fn the_main_thread_budget_is_generous_overridable_and_never_below_the_step() {
2616 let five = Duration::from_secs(5);
2617 let _guard = ENV_LOCK
2618 .lock()
2619 .unwrap_or_else(std::sync::PoisonError::into_inner);
2620 unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2622 assert_eq!(
2623 main_thread_budget(five),
2624 Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS)
2625 );
2626 assert_eq!(
2628 main_thread_budget(Duration::from_secs(120)),
2629 Duration::from_secs(120)
2630 );
2631 unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", "90") };
2632 assert_eq!(main_thread_budget(five), Duration::from_secs(90));
2633 for bad in ["0", "-3", "abc", ""] {
2635 unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", bad) };
2636 assert_eq!(
2637 main_thread_budget(five),
2638 Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS),
2639 "{bad:?} should fall back to the default"
2640 );
2641 }
2642 unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2643 }
2644
2645 #[test]
2649 fn assert_text_honors_its_own_timeout() {
2650 let step = |json: &str| serde_json::from_str::<Step>(json).expect("step");
2651 let slow = step(r#"{"op":"assert_text","id":"state","text":"done","timeout_secs":120}"#);
2652 assert_eq!(slow.wait_budget_secs(), 120.0);
2653 let plain = step(r#"{"op":"assert_text","id":"state","text":"done"}"#);
2654 assert_eq!(plain.wait_budget_secs(), DEFAULT_TIMEOUT_SECS);
2655 let waiting = step(r#"{"op":"wait_for","id":"state","timeout_secs":30}"#);
2656 assert_eq!(waiting.wait_budget_secs(), 30.0);
2657 }
2658
2659 #[test]
2662 fn web_eval_honors_its_own_timeout() {
2663 for (timeout, expected) in [
2664 (None, DEFAULT_TIMEOUT_SECS),
2665 (Some(30.0), 30.0),
2666 (Some(0.0), DEFAULT_TIMEOUT_SECS),
2667 (Some(-1.0), DEFAULT_TIMEOUT_SECS),
2668 ] {
2669 let step: Step = serde_json::from_value(serde_json::json!({
2670 "op": "web_eval", "id": "page", "script": "document.title",
2671 "timeout_secs": timeout,
2672 }))
2673 .expect("web_eval step");
2674 assert_eq!(step.wait_budget_secs(), expected);
2675 }
2676 }
2677
2678 #[test]
2682 fn menu_id_addresses_an_item_whose_label_moves() {
2683 use day_spec::MenuItem as MI;
2684 let model = |mark: &str| {
2685 vec![MI::Submenu {
2686 label: "View".into(),
2687 role: None,
2688 items: vec![
2689 MI::Action {
2690 id: Some("view-grid".into()),
2691 action: 42,
2692 label: format!("{mark}Grid"),
2693 shortcut: None,
2694 enabled: true,
2695 checked: Some(mark == "\u{2713} "),
2696 role: None,
2697 icon: None,
2698 },
2699 MI::Action {
2700 id: None,
2701 action: 7,
2702 label: "Grid".into(),
2703 shortcut: None,
2704 enabled: true,
2705 checked: None,
2706 role: None,
2707 icon: None,
2708 },
2709 ],
2710 }]
2711 };
2712 let by_id = |items: &[MI]| {
2713 find_menu_actions(items, "", None, Some("view-grid"), &[])
2714 .into_iter()
2715 .map(|(a, _, _)| a)
2716 .collect::<Vec<_>>()
2717 };
2718 assert_eq!(by_id(&model("\u{2713} ")), vec![42]);
2720 assert_eq!(by_id(&model(" ")), vec![42]);
2721 assert_eq!(
2724 find_menu_actions(&model(" "), "Grid", None, None, &[])
2725 .into_iter()
2726 .map(|(a, _, _)| a)
2727 .collect::<Vec<_>>(),
2728 vec![7]
2729 );
2730 assert_eq!(
2732 find_menu_actions(&model(" "), "Grid", None, Some("view-ruler"), &[]),
2733 [] as [(u64, bool, std::vec::Vec<std::string::String>); 0]
2734 );
2735 }
2736}