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