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 day_core::enqueue_event(
717 target,
718 Event::Key(day_spec::KeyEvent {
719 key,
720 modifiers: mask,
721 }),
722 );
723 day_reactive::flush_sync();
724 Ok(Reply::ok())
725 }
726 Step::Drag {
727 id,
728 from,
729 to,
730 steps,
731 modifiers,
732 } => {
733 let node = find(&id)?;
734 let (fx, fy) = (from[0], from[1]);
735 let (tx, ty) = (to[0], to[1]);
736 let n = steps.unwrap_or(4).max(1);
737 let emit_drag = |phase, x: f64, y: f64| {
738 day_core::enqueue_event(
739 rnode_to_id(node),
740 Event::Drag {
741 phase,
742 location: day_spec::Point::new(x, y),
743 translation: day_spec::Point::new(x - fx, y - fy),
744 },
745 );
746 };
747 if !modifiers.is_empty() {
751 day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
752 }
753 emit_drag(day_spec::DragPhase::Began, fx, fy);
754 day_reactive::flush_sync();
755 for i in 1..=n {
756 let f = i as f64 / n as f64;
757 emit_drag(
758 day_spec::DragPhase::Changed,
759 fx + (tx - fx) * f,
760 fy + (ty - fy) * f,
761 );
762 day_reactive::flush_sync();
763 }
764 emit_drag(day_spec::DragPhase::Ended, tx, ty);
765 day_reactive::flush_sync();
766 day_core::set_modifier_override(None);
767 Ok(Reply::ok())
768 }
769 Step::Hover { id, at, leave } => {
770 let node = find(&id)?;
771 let location = match at {
772 Some([x, y]) => day_spec::Point::new(x, y),
773 None => {
774 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
775 day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
776 }
777 };
778 let phase = if leave {
779 day_spec::DragPhase::Ended
780 } else {
781 day_spec::DragPhase::Began
782 };
783 day_core::enqueue_event(rnode_to_id(node), Event::Hover { phase, location });
784 day_reactive::flush_sync();
785 Ok(Reply::ok())
786 }
787 Step::Pan { id, by, steps } => {
788 let node = find(&id)?;
789 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
790 let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
791 let n = steps.unwrap_or(4).max(1);
792 let emit_pan = |phase, dx: f64, dy: f64| {
793 day_core::enqueue_event(
794 rnode_to_id(node),
795 Event::Pan {
796 phase,
797 delta: day_spec::Point::new(dx, dy),
798 location,
799 },
800 );
801 day_reactive::flush_sync();
802 };
803 emit_pan(day_spec::DragPhase::Began, 0.0, 0.0);
804 for _ in 0..n {
806 emit_pan(
807 day_spec::DragPhase::Changed,
808 by[0] / n as f64,
809 by[1] / n as f64,
810 );
811 }
812 emit_pan(day_spec::DragPhase::Ended, 0.0, 0.0);
813 Ok(Reply::ok())
814 }
815 Step::Pinch { id, scale, steps } => {
816 let node = find(&id)?;
817 let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
818 let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
819 let n = steps.unwrap_or(4).max(1);
820 let emit_pinch = |phase, s: f64| {
821 day_core::enqueue_event(
822 rnode_to_id(node),
823 Event::Pinch {
824 phase,
825 scale: s,
826 location,
827 },
828 );
829 day_reactive::flush_sync();
830 };
831 emit_pinch(day_spec::DragPhase::Began, 1.0);
832 for i in 1..=n {
834 emit_pinch(
835 day_spec::DragPhase::Changed,
836 1.0 + (scale - 1.0) * i as f64 / n as f64,
837 );
838 }
839 emit_pinch(day_spec::DragPhase::Ended, scale);
840 Ok(Reply::ok())
841 }
842 Step::Submit { id } => emit(&id, Event::Submitted).map(|()| Reply::ok()),
843 Step::Input {
844 id,
845 text,
846 key,
847 args,
848 } => {
849 let value = match key {
850 Some(k) => format_key(&k, args),
851 None => text.unwrap_or_default(),
852 };
853 let node = find(&id)?;
856 day_core::synthesize_text(node, value);
857 day_reactive::flush_sync();
858 Ok(Reply::ok())
859 }
860 Step::SetValue { id, value } => {
861 emit(&id, Event::ValueChanged(value))?;
865 emit(&id, Event::ValueCommitted(value))?;
866 Ok(Reply::ok())
867 }
868 Step::Toggle { id, value } => {
869 let target = match value {
870 Some(v) => v,
871 None => !probe(&id)?.flag,
872 };
873 emit(&id, Event::ToggleChanged(target))?;
874 Ok(Reply::ok())
875 }
876 Step::Activate { id, index } => {
877 emit(&id, Event::ListActivated(index))?;
878 Ok(Reply::ok())
879 }
880 Step::Select {
881 id,
882 index,
883 if_present,
884 } => {
885 if if_present {
886 day_reactive::flush_sync();
889 if !with_tree(|t| t.ui_idle()) {
890 return Err(Reply::fail("ui transitions still settling", true));
891 }
892 if with_tree(|t| t.find_by_id(&id)).is_none() {
893 return Ok(Reply::ok());
894 }
895 }
896 let node = find(&id)?;
897 let state = probe(&id)?;
898 if with_tree(|t| t.node_kind(node)) == Some(day_spec::kinds::PICKER)
899 && (index < 0 || index as usize >= state.options.len())
900 {
901 return Err(Reply::fail(
902 format!(
903 "select {id:?}: index {index} is out of range for {} options",
904 state.options.len()
905 ),
906 false,
907 ));
908 }
909 emit(&id, Event::SelectionChanged(index))?;
910 Ok(Reply::ok())
911 }
912 Step::Reorder { id, from, to } => {
913 let node = find(&id)?;
914 match day_core::list_try_reorder(node, from, to) {
915 Ok(_) => Ok(Reply::ok()),
916 Err(e) => Err(Reply::fail(
919 format!("reorder {id:?} {from}->{to}: {e}"),
920 false,
921 )),
922 }
923 }
924 Step::Undo => drive_undo(false),
925 Step::Redo => drive_undo(true),
926 Step::Expand { id, row, expanded } => {
927 let node = find(&id)?;
928 let driver = day_core::tree_driver(node).ok_or_else(|| {
929 Reply::fail(format!("expand {id:?}: no tree at this node"), false)
930 })?;
931 let token = (driver.resolve_row)(&row).ok_or_else(|| {
932 Reply::fail(format!("expand {id:?}: no row {row:?}"), true)
935 })?;
936 emit(&id, Event::TreeExpanded { token, expanded })?;
937 Ok(Reply::ok())
938 }
939 Step::TreeMove {
940 id,
941 row,
942 parent,
943 index,
944 } => {
945 let node = find(&id)?;
946 let driver = day_core::tree_driver(node).ok_or_else(|| {
947 Reply::fail(format!("tree_move {id:?}: no tree at this node"), false)
948 })?;
949 let token = (driver.resolve_row)(&row).ok_or_else(|| {
950 Reply::fail(format!("tree_move {id:?}: no row {row:?}"), true)
951 })?;
952 let parent_tok = match &parent {
953 Some(p) => Some((driver.resolve_row)(p).ok_or_else(|| {
954 Reply::fail(format!("tree_move {id:?}: no parent row {p:?}"), true)
955 })?),
956 None => None,
957 };
958 match day_core::tree_try_move(node, token, parent_tok, index) {
959 Ok(()) => Ok(Reply::ok()),
960 Err(e) => Err(Reply::fail(format!("tree_move {id:?} {row:?}: {e}"), false)),
962 }
963 }
964 Step::DeleteRow { id, row } => {
965 let node = find(&id)?;
966 match day_core::list_try_delete(node, row) {
967 Ok(()) => Ok(Reply::ok()),
968 Err(e) => Err(Reply::fail(format!("delete_row {id:?} {row}: {e}"), false)),
971 }
972 }
973 Step::SwipeRow {
974 id,
975 row,
976 edge,
977 action,
978 label,
979 key,
980 } => {
981 let node = find(&id)?;
982 let edge = match edge.as_deref() {
983 None | Some("trailing") => day_spec::SwipeEdge::Trailing,
984 Some("leading") => day_spec::SwipeEdge::Leading,
985 Some(other) => {
986 return Err(Reply::fail(
987 format!("swipe_row {id:?}: edge {other:?} (leading|trailing)"),
988 false,
989 ));
990 }
991 };
992 let expected = match (&label, &key) {
993 (Some(l), _) => Some(l.clone()),
994 (None, Some(k)) => Some(format_key(k, None)),
995 (None, None) => None,
996 };
997 match day_core::list_try_swipe(node, row, edge, action, expected.as_deref()) {
1001 Ok(_) => Ok(Reply::ok()),
1002 Err(e) => Err(Reply::fail(format!("swipe_row {id:?} {row}: {e}"), false)),
1006 }
1007 }
1008 Step::WebEval {
1009 id,
1010 script,
1011 contains,
1012 text,
1013 ..
1014 } => {
1015 use std::cell::RefCell;
1022 use std::rc::Rc;
1023 type EvalCell = Rc<RefCell<Option<Result<String, String>>>>;
1024 thread_local! {
1025 static WEB_EVALS: RefCell<
1026 std::collections::HashMap<(String, String), (u32, EvalCell)>,
1027 > = RefCell::new(std::collections::HashMap::new());
1028 }
1029 let node = find(&id)?;
1030 let key = (id.clone(), script.clone());
1031 let pending = WEB_EVALS.with(|m| m.borrow().get(&key).map(|(_, c)| c.clone()));
1032 let Some(cell) = pending else {
1033 let cell: EvalCell = Rc::new(RefCell::new(None));
1034 let done = {
1035 let cell = cell.clone();
1036 Box::new(move |r: Result<String, String>| *cell.borrow_mut() = Some(r))
1037 };
1038 if !day_core::piece_operation(node, "day.webview.eval", &script, done) {
1039 return Err(Reply::fail(
1040 format!(
1041 "web_eval {id:?}: not a web view (or no webview piece registered an evaluator)"
1042 ),
1043 false,
1044 ));
1045 }
1046 WEB_EVALS.with(|m| m.borrow_mut().insert(key, (0, cell)));
1047 return Err(Reply::fail(
1048 format!("web_eval {id:?}: awaiting the engine"),
1049 true,
1050 ));
1051 };
1052 let Some(result) = cell.borrow_mut().take() else {
1053 let stale = WEB_EVALS.with(|m| {
1057 let mut m = m.borrow_mut();
1058 match m.get_mut(&key) {
1059 Some((polls, _)) => {
1060 *polls += 1;
1061 *polls > 25
1062 }
1063 None => false,
1064 }
1065 });
1066 if stale {
1067 WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1068 }
1069 return Err(Reply::fail(
1070 format!("web_eval {id:?}: awaiting the engine"),
1071 true,
1072 ));
1073 };
1074 WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1075 match result {
1076 Err(e) => Err(Reply::fail(format!("web_eval {id:?}: {e}"), true)),
1079 Ok(json) => {
1080 let value = serde_json::from_str::<serde_json::Value>(&json)
1082 .ok()
1083 .and_then(|v| v.as_str().map(str::to_string))
1084 .unwrap_or(json);
1085 let failed = match (&contains, &text) {
1086 (Some(c), _) if !value.contains(c.as_str()) => {
1087 Some(format!("result {value:?} does not contain {c:?}"))
1088 }
1089 (_, Some(t)) if value != *t => {
1090 Some(format!("result {value:?}, expected {t:?}"))
1091 }
1092 _ => None,
1093 };
1094 match failed {
1095 Some(why) => Err(Reply::fail(format!("web_eval {id:?}: {why}"), true)),
1098 None => Ok(Reply::ok()),
1099 }
1100 }
1101 }
1102 }
1103 Step::ContextMenu {
1104 id,
1105 if_present,
1106 item_id,
1107 item,
1108 key,
1109 path,
1110 } => {
1111 if if_present {
1112 day_reactive::flush_sync();
1114 if !with_tree(|t| t.ui_idle()) {
1115 return Err(Reply::fail("ui transitions still settling", true));
1116 }
1117 if with_tree(|t| t.find_by_id(&id)).is_none() {
1118 return Ok(Reply::ok());
1119 }
1120 }
1121 let node = find(&id)?;
1122 let menu = with_tree(|t| t.context_menu_of(node)).ok_or_else(|| {
1123 Reply::fail(
1124 format!("context_menu {id:?}: the element has no menu"),
1125 true,
1126 )
1127 })?;
1128 let items = menu(day_spec::Point::ZERO);
1131 let target_label = match (&item_id, &item, &key) {
1132 (Some(_), _, _) => String::new(),
1133 (None, Some(l), _) => l.clone(),
1134 (None, None, Some(k)) => format_key(k, None),
1135 (None, None, None) => {
1136 return Err(Reply::fail(
1137 "context_menu: needs `item_id:`, `item:` or `key:`",
1138 false,
1139 ));
1140 }
1141 };
1142 let path: Vec<(String, String)> = path
1143 .unwrap_or_default()
1144 .into_iter()
1145 .map(|p| {
1146 let resolved = format_key(&p, None);
1147 (p, resolved)
1148 })
1149 .collect();
1150 let matches = find_menu_actions(
1151 &items,
1152 &target_label,
1153 key.as_deref(),
1154 item_id.as_deref(),
1155 &path,
1156 );
1157 let what = match &item_id {
1158 Some(want) => format!("id {want:?}"),
1159 None => format!("{target_label:?}"),
1160 };
1161 match matches.as_slice() {
1162 [] => Err(Reply::fail(
1163 format!("context_menu {id:?}: no item {what}"),
1164 true,
1165 )),
1166 [(action, enabled, _)] => {
1167 if *action == 0 {
1168 Err(Reply::fail(
1169 format!(
1170 "context_menu {id:?}: {what} runs a native command (no day \
1171 action)"
1172 ),
1173 false,
1174 ))
1175 } else if !enabled {
1176 Err(Reply::fail(
1177 format!("context_menu {id:?}: {what} is disabled"),
1178 false,
1179 ))
1180 } else {
1181 day_core::dispatch_menu_action(*action);
1182 day_reactive::flush_sync();
1183 Ok(Reply::ok())
1184 }
1185 }
1186 _ => Err(Reply::fail(
1187 format!("context_menu {id:?}: {what} is ambiguous; add a path"),
1188 false,
1189 )),
1190 }
1191 }
1192 Step::Menu {
1193 id,
1194 item,
1195 key,
1196 path,
1197 } => {
1198 let target_label = match (&id, &item, &key) {
1199 (Some(_), _, _) => String::new(),
1200 (None, Some(l), _) => l.clone(),
1201 (None, None, Some(k)) => format_key(k, None),
1202 (None, None, None) => {
1203 return Err(Reply::fail("menu: needs `id:`, `item:` or `key:`", false));
1204 }
1205 };
1206 let path: Vec<(String, String)> = path
1210 .unwrap_or_default()
1211 .into_iter()
1212 .map(|p| {
1213 let resolved = format_key(&p, None);
1214 (p, resolved)
1215 })
1216 .collect();
1217 let matches = find_menu_actions(
1218 &day_core::menu::app_menu_model(),
1219 &target_label,
1220 key.as_deref(),
1221 id.as_deref(),
1222 &path,
1223 );
1224 let auto_id = match (matches.is_empty(), key.as_deref()) {
1228 (true, Some("day_preferences")) => {
1229 Some(day_core::windows::preferences_action_id())
1230 }
1231 (true, Some("day_new_window")) => {
1232 Some(day_core::windows::new_window_action_id())
1233 }
1234 (true, Some("day_about")) => Some(day_core::windows::about_action_id()),
1235 (true, Some("day_check_for_updates")) => {
1236 Some(day_core::windows::check_for_updates_action_id())
1237 }
1238 _ => None,
1239 };
1240 if let Some(id) = auto_id
1241 && id != 0
1242 {
1243 day_core::dispatch_menu_action(id);
1244 day_reactive::flush_sync();
1245 return Ok(Reply::ok());
1246 }
1247 let what = match &id {
1250 Some(want) => format!("id {want:?}"),
1251 None => format!("{target_label:?}"),
1252 };
1253 match matches.as_slice() {
1254 [] => Err(Reply::fail(
1255 format!("menu: no item {what}"),
1257 true,
1258 )),
1259 [(action, enabled, _)] => {
1260 if *action == 0 {
1261 Err(Reply::fail(
1262 format!(
1263 "menu: {what} runs a native selector (no day action) — not \
1264 invokable from dayscript"
1265 ),
1266 false,
1267 ))
1268 } else if !enabled {
1269 Err(Reply::fail(format!("menu: {what} is disabled"), false))
1270 } else {
1271 day_core::dispatch_menu_action(*action);
1272 day_reactive::flush_sync();
1273 Ok(Reply::ok())
1274 }
1275 }
1276 many => Err(Reply::fail(
1277 format!(
1278 "menu: {what} is ambiguous — disambiguate with path: {:?}",
1279 many.iter()
1280 .map(|(_, _, p)| p.join(" ▸ "))
1281 .collect::<Vec<_>>()
1282 ),
1283 false,
1284 )),
1285 }
1286 }
1287 Step::Toolbar {
1288 item,
1289 text,
1290 key,
1291 args,
1292 on,
1293 index,
1294 submit,
1295 } => {
1296 let text = match key {
1299 Some(k) => Some(format_key(&k, args)),
1300 None => text,
1301 };
1302 let model = day_core::toolbar::toolbar_model();
1306 let Some(found) = model.iter().find(|i| i.id == item) else {
1307 if item == day_spec::SEARCH_ITEM_ID
1313 && let Some(host) = day_core::inline_search_host()
1314 {
1315 let Some(t) = text else {
1316 return Err(Reply::fail(
1317 "toolbar: day::search rides the navigation surface here, which takes text (or key) only",
1318 false,
1319 ));
1320 };
1321 day_core::enqueue_event(rnode_to_id(host), Event::SearchChanged(t.clone()));
1322 if submit {
1323 day_core::enqueue_event(rnode_to_id(host), Event::SearchSubmitted(t));
1324 }
1325 day_reactive::flush_sync();
1326 return Ok(Reply::ok());
1327 }
1328 return Err(Reply::fail(format!("toolbar: no item {item:?}"), true));
1330 };
1331 if !found.enabled {
1332 return Err(Reply::fail(format!("toolbar: {item:?} is disabled"), false));
1333 }
1334 if found.action == 0 {
1338 return Err(Reply::fail(
1339 format!("toolbar: {item:?} has no command"),
1340 false,
1341 ));
1342 }
1343 if let day_spec::ToolbarItemKind::Segmented { segments, .. } = &found.kind {
1350 let Some(i) = index else {
1351 return Err(Reply::fail(
1352 format!("toolbar: {item:?} is segmented — say `index: <n>`"),
1353 false,
1354 ));
1355 };
1356 if i >= segments.len() {
1357 return Err(Reply::fail(
1358 format!(
1359 "toolbar: {item:?} has {} segments, asked for {i}",
1360 segments.len()
1361 ),
1362 false,
1363 ));
1364 }
1365 day_core::toolbar::dispatch_toolbar_value(
1366 found.action,
1367 &day_spec::ToolbarValue::Selected(i),
1368 );
1369 day_reactive::flush_sync();
1370 return Ok(Reply::ok());
1371 }
1372 if matches!(found.kind, day_spec::ToolbarItemKind::Toggle { .. })
1373 && on.is_none()
1374 && text.is_none()
1375 {
1376 return Err(Reply::fail(
1377 format!("toolbar: {item:?} is a toggle — say `on: true` or `on: false`"),
1378 false,
1379 ));
1380 }
1381 if submit && text.is_none() {
1382 return Err(Reply::fail(
1383 format!("toolbar: submitting {item:?} needs `text:` (or `key:`)"),
1384 false,
1385 ));
1386 }
1387 match (text, on) {
1388 (Some(t), _) => {
1389 day_core::toolbar::synthesize_toolbar_value(
1390 found.action,
1391 &day_spec::ToolbarValue::Text(t.clone()),
1392 );
1393 if submit {
1394 day_reactive::flush_sync();
1395 day_core::toolbar::dispatch_toolbar_value(
1396 found.action,
1397 &day_spec::ToolbarValue::Submit(t),
1398 );
1399 }
1400 }
1401 (None, Some(v)) => day_core::toolbar::dispatch_toolbar_value(
1402 found.action,
1403 &day_spec::ToolbarValue::On(v),
1404 ),
1405 (None, None) => day_core::dispatch_menu_action(found.action),
1406 }
1407 day_reactive::flush_sync();
1408 Ok(Reply::ok())
1409 }
1410 Step::AssertVisible { id } => {
1411 visible(&id)?;
1412 Ok(Reply::ok())
1413 }
1414 Step::AssertHidden { id } => {
1415 let Some(node) = with_tree(|t| t.find_by_id(&id)) else {
1416 return Ok(Reply::ok());
1417 };
1418 let empty = with_tree(|t| t.node_frame(node))
1419 .is_none_or(|f| f.size.width <= 0.0 || f.size.height <= 0.0);
1420 let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1421 if empty || (native.found && native.visible == Some(false)) {
1422 Ok(Reply::ok())
1423 } else {
1424 Err(Reply::fail(format!("element {id:?} is shown"), true))
1425 }
1426 }
1427 Step::AssertMissing { id } => match with_tree(|t| t.find_by_id(&id)) {
1428 Some(_) => Err(Reply::fail(format!("element {id:?} is present"), true)),
1429 None => Ok(Reply::ok()),
1430 },
1431 Step::AssertText {
1432 id,
1433 text,
1434 key,
1435 args,
1436 ..
1437 } => {
1438 let actual = norm(&probe(&id)?.text);
1439 let expected = if let Some(k) = key {
1440 norm(&format_key(&k, args))
1441 } else {
1442 norm(&text.unwrap_or_default())
1443 };
1444 if actual == expected {
1445 Ok(Reply::ok())
1446 } else {
1447 Err(Reply::fail(
1448 format!("{id:?}: expected {expected:?}, found {actual:?}"),
1449 true,
1450 ))
1451 }
1452 }
1453 Step::AssertNoPlaceholders { allow } => {
1454 let unexpected: Vec<&str> = day_spec::placeholder::seen()
1455 .into_iter()
1456 .filter(|k| !allow.iter().any(|a| a == k))
1457 .collect();
1458 if unexpected.is_empty() {
1459 Ok(Reply::ok())
1460 } else {
1461 Err(Reply::fail(
1462 format!(
1463 "rendered a placeholder for {} — no renderer on this backend. Enable \
1464 the piece's feature for this toolkit, or add the kind to `allow:` if \
1465 the gap is intended.",
1466 unexpected.join(", ")
1467 ),
1468 true,
1469 ))
1470 }
1471 }
1472 Step::AssertValue { id, value } => {
1473 let p = probe(&id)?;
1474 let ok = match &value {
1475 serde_json::Value::Bool(b) => p.flag == *b,
1476 serde_json::Value::Number(n) => {
1477 (p.value - n.as_f64().unwrap_or(f64::NAN)).abs() < 0.5
1478 }
1479 serde_json::Value::String(s) => norm(&p.text) == norm(s),
1480 _ => false,
1481 };
1482 if ok {
1483 Ok(Reply::ok())
1484 } else {
1485 Err(Reply::fail(
1486 format!(
1487 "{id:?}: expected {value}, probe text={:?} value={} flag={}",
1488 p.text, p.value, p.flag
1489 ),
1490 true,
1491 ))
1492 }
1493 }
1494 Step::AssertAnnounced { text } => {
1495 let said = day_core::conformance::announcements();
1496 if said.iter().any(|s| norm(s) == norm(&text)) {
1497 Ok(Reply::ok())
1498 } else {
1499 Err(Reply::fail(
1500 format!("{text:?} was not announced (announced: {said:?})"),
1501 true,
1502 ))
1503 }
1504 }
1505 Step::AssertOpenedUrl { url } => {
1506 let opened = day_core::conformance::opened_urls();
1507 if opened.contains(&url) {
1508 Ok(Reply::ok())
1509 } else {
1510 Err(Reply::fail(
1511 format!("{url:?} was not opened (opened: {opened:?})"),
1512 true,
1513 ))
1514 }
1515 }
1516 Step::AssertFrame {
1517 id,
1518 width,
1519 height,
1520 x,
1521 y,
1522 relative_to,
1523 tolerance,
1524 } => {
1525 let tol = tolerance.unwrap_or(1.0);
1526 let node = find(&id)?;
1527 let day = with_tree(|t| t.node_frame(node))
1528 .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1529 let native = with_tree(|t| t.read_native(node)).and_then(|n| n.frame);
1530 let (base_day, base_native) = match &relative_to {
1531 Some(other) => {
1532 let o = find(other)?;
1533 let f = with_tree(|t| t.node_frame(o))
1534 .ok_or_else(|| Reply::fail(format!("{other:?} has no frame"), true))?;
1535 let n = with_tree(|t| t.read_native(o)).and_then(|n| n.frame);
1536 (f.origin, n.map(|r| r.origin))
1537 }
1538 None => (day_spec::Point::ZERO, Some(day_spec::Point::ZERO)),
1539 };
1540 let mut fails = Vec::new();
1541 let mut check = |source: &str, f: day_spec::Rect, base: day_spec::Point| {
1542 let got = [
1543 ("width", f.size.width, width),
1544 ("height", f.size.height, height),
1545 ("x", f.origin.x - base.x, x),
1546 ("y", f.origin.y - base.y, y),
1547 ];
1548 for (name, value, want) in got {
1549 if let Some(w) = want
1550 && (value - w).abs() > tol
1551 {
1552 fails.push(format!("{source} {name} {value:.1} ≠ {w}"));
1553 }
1554 }
1555 };
1556 check("Day", day, base_day);
1557 let unread = match (native, base_native) {
1558 (Some(f), Some(base)) => {
1559 check("native", f, base);
1560 false
1561 }
1562 _ => true,
1563 };
1564 if !fails.is_empty() {
1565 return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
1566 }
1567 Ok(Reply {
1568 data: unread.then(|| serde_json::json!({ "unread": ["frame"] })),
1569 ..Reply::ok()
1570 })
1571 }
1572 Step::SamplePixel {
1573 id,
1574 x,
1575 y,
1576 color,
1577 tolerance,
1578 } => {
1579 let want = parse_hex_color(&color).ok_or_else(|| {
1580 Reply::fail(format!("sample_pixel: {color:?} is not #rrggbb"), false)
1581 })?;
1582 if day_core::capability(day_spec::Cap::Snapshot) == day_spec::Support::Unsupported {
1583 return Ok(Reply {
1584 data: Some(serde_json::json!({ "unread": ["pixel"] })),
1585 ..Reply::ok()
1586 });
1587 }
1588 day_reactive::flush_sync();
1589 if !with_tree(|t| t.ui_idle()) {
1590 return Err(Reply::fail("ui transitions still settling", true));
1591 }
1592 hosts_settled()?;
1593 let readiness = with_tree(|t| t.prepare_snapshot(None, revision))
1594 .map_err(|e| Reply::fail(format!("sample_pixel readiness: {e}"), false))?;
1595 if readiness == day_spec::capture::Readiness::Pending {
1596 return Err(Reply {
1597 capture_pending: true,
1598 ..Reply::fail("waiting for a render checkpoint", true)
1599 });
1600 }
1601 let node = find(&id)?;
1602 let frame = with_tree(|t| t.node_frame(node))
1603 .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1604 let window = with_tree(|t| t.node_frame(t.root_node()))
1605 .ok_or_else(|| Reply::fail("the window has no frame", true))?;
1606 let bytes = with_tree(|t| t.snapshot())
1607 .map_err(|e| Reply::fail(format!("sample_pixel capture: {e}"), true))?;
1608 let origin = with_tree(|t| t.snapshot_origin());
1609 let Ok(img) = png::decode(&bytes) else {
1612 return Ok(Reply {
1613 data: Some(serde_json::json!({ "unread": ["pixel"] })),
1614 ..Reply::ok()
1615 });
1616 };
1617 let (scale, left, above) = match origin {
1624 Some(o) => (
1625 img.width as f64 / (window.size.width + 2.0 * o.x).max(1.0),
1626 o.x,
1627 o.y,
1628 ),
1629 None => {
1630 let scale = img.width as f64 / window.size.width.max(1.0);
1631 let above = (img.height as f64 / scale - window.size.height).max(0.0);
1632 (scale, 0.0, above)
1633 }
1634 };
1635 let px = ((left + frame.origin.x - window.origin.x + x * frame.size.width) * scale)
1636 .floor()
1637 .max(0.0) as usize;
1638 let py = ((above + frame.origin.y - window.origin.y + y * frame.size.height)
1639 * scale)
1640 .floor()
1641 .max(0.0) as usize;
1642 let got = img.pixel(px, py).ok_or_else(|| {
1643 Reply::fail(
1644 format!("{id:?}: ({px}, {py}) is outside the capture"),
1645 false,
1646 )
1647 })?;
1648 let tol = tolerance.unwrap_or(64);
1649 let near = (0..3).all(|i| got[i].abs_diff(want[i]) <= tol);
1650 if near {
1651 Ok(Reply::ok())
1652 } else {
1653 Err(Reply::fail(
1654 format!(
1655 "{id:?} at ({x}, {y}): #{:02x}{:02x}{:02x} ≠ {color}",
1656 got[0], got[1], got[2]
1657 ),
1658 true,
1659 ))
1660 }
1661 }
1662 Step::AssertNative {
1663 id,
1664 text,
1665 number,
1666 checked,
1667 enabled,
1668 visible,
1669 } => {
1670 let node = find(&id)?;
1671 let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1672 if let Some(want) = enabled
1673 && probe(&id)?.enabled != want
1674 {
1675 return Err(Reply::fail(
1676 format!("{id:?}: Day has enabled={}, expected {want}", !want),
1677 true,
1678 ));
1679 }
1680 let mut unread = Vec::new();
1681 let mut fails = Vec::new();
1682 let mut check = |field: &str,
1683 got: Option<String>,
1684 want: Option<String>,
1685 eq: bool| match (got, want) {
1686 (_, None) => {}
1687 (None, Some(_)) => unread.push(field.to_owned()),
1688 (Some(g), Some(w)) if !eq => {
1689 fails.push(format!("native {field} {g} ≠ expected {w}"))
1690 }
1691 _ => {}
1692 };
1693 let text_eq =
1694 matches!((&native.text, &text), (Some(g), Some(w)) if norm(g) == norm(w));
1695 check(
1696 "text",
1697 native.text.as_ref().map(|t| format!("{t:?}")),
1698 text.as_ref().map(|t| format!("{t:?}")),
1699 text_eq,
1700 );
1701 let number_eq = matches!((native.number, number), (Some(g), Some(w)) if (g - w).abs() <= 1e-3 * w.abs().max(1.0));
1702 check(
1703 "number",
1704 native.number.map(|n| n.to_string()),
1705 number.map(|n| n.to_string()),
1706 number_eq,
1707 );
1708 check(
1709 "checked",
1710 native.checked.map(|b| b.to_string()),
1711 checked.map(|b| b.to_string()),
1712 native.checked == checked,
1713 );
1714 check(
1715 "enabled",
1716 native.enabled.map(|b| b.to_string()),
1717 enabled.map(|b| b.to_string()),
1718 native.enabled == enabled,
1719 );
1720 check(
1721 "visible",
1722 native.visible.map(|b| b.to_string()),
1723 visible.map(|b| b.to_string()),
1724 native.visible == visible,
1725 );
1726 if !fails.is_empty() {
1727 return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
1728 }
1729 Ok(Reply {
1730 data: (!unread.is_empty()).then(|| serde_json::json!({ "unread": unread })),
1731 ..Reply::ok()
1732 })
1733 }
1734 Step::ScrollTo { id, edge, x, y } => {
1735 let node = find(&id)?;
1736 let target = match (edge.as_deref(), x, y) {
1737 (Some("top"), _, _) => day_core::ScrollTarget::Top,
1738 (Some("bottom"), _, _) => day_core::ScrollTarget::Bottom,
1739 (Some("leading"), _, _) => day_core::ScrollTarget::Leading,
1740 (Some("trailing"), _, _) => day_core::ScrollTarget::Trailing,
1741 (Some(other), _, _) => {
1742 return Err(Reply::fail(
1743 format!(
1744 "scroll_to: unknown edge {other:?} (top|bottom|leading|trailing)"
1745 ),
1746 false,
1747 ));
1748 }
1749 (None, None, None) => {
1750 let ok = with_tree(|t| t.scroll_reveal(node, false));
1752 if !ok {
1753 return Err(Reply::fail(
1754 format!("scroll_to: {id:?} has no enclosing scroll"),
1755 true,
1756 ));
1757 }
1758 day_reactive::flush_sync();
1759 return Ok(Reply::ok());
1760 }
1761 (None, x, y) => day_core::ScrollTarget::Offset(day_spec::Point::new(
1762 x.unwrap_or(0.0),
1763 y.unwrap_or(0.0),
1764 )),
1765 };
1766 let ok = with_tree(|t| t.scroll_to_target(node, &target, false));
1767 if !ok {
1768 return Err(Reply::fail(
1769 format!("scroll_to: {id:?} does not support this scroll target"),
1770 true,
1771 ));
1772 }
1773 day_reactive::flush_sync();
1774 Ok(Reply::ok())
1775 }
1776 Step::Focus { id, focused } => {
1777 let node = find(&id)?;
1778 with_tree(|t| t.focus_node(node, focused.unwrap_or(true)));
1779 day_reactive::flush_sync();
1780 Ok(Reply::ok())
1781 }
1782 Step::AssertFocused { id, focused } => {
1783 let want = focused.unwrap_or(true);
1784 let got = probe(&id)?.focused;
1785 if got == want {
1786 Ok(Reply::ok())
1787 } else {
1788 Err(Reply::fail(
1789 format!("{id:?}: expected focused={want}, found focused={got}"),
1790 true,
1791 ))
1792 }
1793 }
1794 Step::CloseWindow { window } => {
1795 let handle = match &window {
1796 Some(key) => day_core::window_by_key(key),
1797 None => day_core::initial_window(),
1798 };
1799 if let Some(handle) = handle {
1800 handle.close();
1801 }
1802 day_reactive::flush_sync();
1803 Ok(Reply::ok())
1804 }
1805 Step::Screenshot {
1806 window, in_process, ..
1807 } => {
1808 day_reactive::flush_sync();
1809 if !with_tree(|t| t.ui_idle()) {
1812 return Err(Reply::fail("ui transitions still settling", true));
1813 }
1814 hosts_settled()?;
1815 let root = match window.as_deref() {
1816 Some(key) => Some(
1817 day_core::windows::window_root_by_key(key)
1818 .ok_or_else(|| Reply::fail(format!("no window {key:?}"), true))?,
1819 ),
1820 None => None,
1821 };
1822 let readiness = with_tree(|t| t.prepare_snapshot(root, revision))
1823 .map_err(|e| Reply::fail(format!("screenshot readiness: {e}"), false))?;
1824 if readiness == day_spec::capture::Readiness::Pending {
1825 return Err(Reply {
1826 capture_pending: true,
1827 ..Reply::fail("waiting for screenshot render checkpoint", true)
1828 });
1829 }
1830 let capture_revision =
1831 (readiness == day_spec::capture::Readiness::Ready).then_some(revision);
1832 if !in_process {
1833 return Ok(Reply {
1834 capture_revision,
1835 ..Reply::ok()
1836 });
1837 }
1838 let png = match window.as_deref() {
1839 Some(key) => match day_core::windows::window_root_by_key(key) {
1840 Some(root) => with_tree(|t| t.snapshot_of(root)),
1841 None => return Err(Reply::fail(format!("no window {key:?}"), true)),
1844 },
1845 None => with_tree(|t| t.snapshot()),
1846 };
1847 match png {
1848 Ok(bytes) => {
1849 SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
1850 SNAPSHOT_WORKS.store(true, Ordering::Relaxed);
1851 Ok(Reply {
1852 ok: true,
1853 png_base64: Some(b64encode(&bytes)),
1854 capture_revision: Some(revision),
1855 ..Default::default()
1856 })
1857 }
1858 Err(_)
1865 if (SNAPSHOT_WORKS.load(Ordering::Relaxed)
1866 || !SNAPSHOT_NEVER.load(Ordering::Relaxed))
1867 && SNAPSHOT_MISSES.fetch_add(1, Ordering::Relaxed)
1868 < SNAPSHOT_RETRIES =>
1869 {
1870 Err(Reply::fail("the window has nothing to capture yet", true))
1871 }
1872 Err(_) => {
1873 SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
1874 if !SNAPSHOT_WORKS.load(Ordering::Relaxed) {
1875 SNAPSHOT_NEVER.store(true, Ordering::Relaxed);
1876 }
1877 Ok(Reply {
1878 ok: true,
1879 screenshot_unsupported: true,
1880 ..Default::default()
1881 })
1882 }
1883 }
1884 }
1885 Step::Pause { secs } => {
1886 let _ = secs;
1888 Ok(Reply::ok())
1889 }
1890 Step::ExpectExit { within } => {
1891 let _ = within;
1894 Ok(Reply::ok())
1895 }
1896 Step::SizeClass { width, height } => {
1897 if width == "auto" {
1898 day_core::restore_reported_size_class();
1899 day_reactive::flush_sync();
1900 return Ok(Reply::ok());
1901 }
1902 let width = parse_width_class(&width).ok_or_else(|| {
1903 Reply::fail(
1904 format!(
1905 "size_class: unknown width {width:?} \
1906 (auto|compact|medium|expanded|large|extra-large)"
1907 ),
1908 false,
1909 )
1910 })?;
1911 let height = match height.as_deref() {
1912 None => day_spec::HeightClass::Expanded,
1913 Some(h) => parse_height_class(h).ok_or_else(|| {
1914 Reply::fail(
1915 format!("size_class: unknown height {h:?} (compact|medium|expanded)"),
1916 false,
1917 )
1918 })?,
1919 };
1920 day_core::override_size_class(day_spec::SizeClass { width, height });
1921 day_reactive::flush_sync();
1924 Ok(Reply::ok())
1925 }
1926 Step::Resize {
1927 width,
1928 height,
1929 restore,
1930 } => {
1931 if !with_tree(|t| t.ui_idle()) {
1936 return Err(Reply::fail("ui transitions still settling", true));
1937 }
1938 day_core::restore_reported_size_class();
1940 day_reactive::flush_sync();
1941 let (Some(w), Some(h)) = (width, height) else {
1942 let _ = restore;
1945 return Ok(Reply::ok());
1946 };
1947 let want = day_spec::SizeClass::from_size(w, h).width;
1958 let have = day_core::size_class();
1959 if have.map(|c| c.width) == Some(want) {
1960 Ok(Reply::ok())
1961 } else {
1962 Err(Reply::fail(
1964 format!(
1965 "resize to {w}x{h} wants width {want:?}, window reports {have:?} \
1966 (a width within a few points of a breakpoint can fall the other \
1967 side of it once safe-area insets come out — aim for mid-bucket)"
1968 ),
1969 true,
1970 ))
1971 }
1972 }
1973 Step::OpenUrl { url } => {
1974 day_core::request_open_url(&url);
1975 Ok(Reply::ok())
1976 }
1977 Step::DeepLink { url } => {
1978 day_reactive::flush_sync();
1979 let route = day_spec::route_of_url(&url);
1980 if day_core::navigate(&route) {
1981 day_reactive::flush_sync();
1982 Ok(Reply::ok())
1983 } else {
1984 Err(Reply::fail(format!("no route for {url:?}"), true))
1986 }
1987 }
1988 Step::Navigate { route } => {
1989 day_reactive::flush_sync();
1990 if day_core::navigate(&route) {
1991 day_reactive::flush_sync();
1992 Ok(Reply::ok())
1993 } else {
1994 Err(Reply::fail(format!("no route {route:?}"), true))
1996 }
1997 }
1998 Step::NavBack { native } => {
1999 if native && !with_tree(|t| t.ui_idle()) {
2008 return Err(Reply::fail("ui transitions still settling", true));
2009 }
2010 let popped = if native {
2011 with_tree(|t| t.native_back())
2012 } else {
2013 day_core::nav_back()
2014 };
2015 if popped {
2016 if !native {
2017 day_reactive::flush_sync();
2018 }
2019 Ok(Reply::ok())
2020 } else if day_core::size_class().is_some_and(|c| c.prefers_split()) {
2021 Ok(Reply::ok())
2035 } else {
2036 Err(Reply::fail("nothing to pop", true))
2037 }
2038 }
2039 Step::AssertRoute { route } => {
2040 let current = day_core::current_route();
2041 if current.as_deref() == Some(route.as_str()) {
2042 Ok(Reply::ok())
2043 } else {
2044 Err(Reply::fail(
2045 format!("expected route {route:?}, current {current:?}"),
2046 true,
2047 ))
2048 }
2049 }
2050 Step::DialogMode { mode } => {
2051 let mode = match mode {
2052 DialogMode::Native => day_core::PresentationMode::Native,
2053 DialogMode::Scripted => day_core::PresentationMode::Scripted,
2054 };
2055 day_core::set_presentation_mode(mode).map_err(|why| Reply::fail(why, false))?;
2056 Ok(Reply::ok())
2057 }
2058 Step::AssertNotPresented => {
2059 if let Some((_, spec)) = day_core::pending_presentation() {
2060 Err(Reply::fail(
2061 format!("unanswered presentation: {:?}", spec.title()),
2062 true,
2063 ))
2064 } else {
2065 Ok(Reply::ok())
2066 }
2067 }
2068 Step::AssertPresented { title } => match day_core::pending_presentation() {
2069 Some((_, spec)) => {
2070 let actual = norm(spec.title());
2071 match title {
2072 Some(want) if norm(&want) != actual => Err(Reply::fail(
2073 format!("modal title {actual:?} != expected {want:?}"),
2074 true,
2075 )),
2076 _ => Ok(Reply::ok()),
2077 }
2078 }
2079 None => Err(Reply::fail("no modal presented", true)),
2080 },
2081 Step::Respond {
2082 button,
2083 text,
2084 path,
2085 dismiss,
2086 } => {
2087 let Some((req, _)) = day_core::pending_presentation() else {
2088 return Err(Reply::fail("no modal to respond to", true));
2089 };
2090 let result = if dismiss {
2091 PresentResult::Dismissed
2092 } else if let Some(t) = text {
2093 PresentResult::Text(t)
2094 } else if let Some(p) = path {
2095 let pb = std::path::PathBuf::from(&p);
2098 let full = if pb.is_absolute() {
2099 pb
2100 } else {
2101 day_core::app_temp_dir().join(pb)
2102 };
2103 PresentResult::Files(vec![full.to_string_lossy().into_owned()])
2104 } else if let Some(i) = button {
2105 PresentResult::Button(i)
2106 } else {
2107 PresentResult::Dismissed
2108 };
2109 day_core::respond_presentation(req, result);
2110 day_reactive::flush_sync();
2111 Ok(Reply::ok())
2112 }
2113 Step::Tests => Ok(Reply {
2114 data: Some(conformance::listing().map_err(|e| Reply::fail(e, false))?),
2115 ..Reply::ok()
2116 }),
2117 Step::RunTests {
2118 filter,
2119 shots,
2120 case_timeout_secs,
2121 ..
2122 } => conformance::run_tests(&filter, shots, case_timeout_secs),
2123 Step::A11yAudit { id } => {
2124 let rows = with_tree(|t| t.a11y_nodes());
2125 let rows: Vec<_> = match &id {
2126 Some(want) => rows.into_iter().filter(|(nid, ..)| nid == want).collect(),
2127 None => rows,
2128 };
2129 if let Some(want) = &id
2130 && rows.is_empty()
2131 {
2132 return Err(Reply::fail(
2133 format!("a11y_audit: no element {want:?}"),
2134 true,
2135 ));
2136 }
2137 let mut fails = Vec::new();
2138 for (nid, _kind, expected, actual) in &rows {
2139 audit_a11y_node(nid, expected, actual, &mut fails);
2140 }
2141 if !fails.is_empty() {
2142 return Err(Reply::fail(
2143 format!("a11y_audit: {}", fails.join("; ")),
2144 false,
2145 ));
2146 }
2147 Ok(Reply::ok())
2148 }
2149 }
2150 })();
2151 let mut reply = result.unwrap_or_else(|r| r);
2152 if reply.ok
2153 && !absent_optional_action
2154 && let (Some(class), Some(id)) = (evidence_class, evidence_id)
2155 && let Ok(catalog) = id_catalog()
2156 && let Ok(d) = catalog.resolve(&id)
2157 {
2158 reply.id_evidence = Box::new([day_script_protocol::IdEvidence {
2159 family: d.family.clone(),
2160 class,
2161 }]);
2162 }
2163 reply.fast_animations = Some(day_core::testing::fast_animations());
2164 reply
2165}
2166
2167fn audit_a11y_node(
2170 nid: &str,
2171 expected: &day_spec::A11yProps,
2172 actual: &day_spec::NativeSnapshot,
2173 fails: &mut Vec<String>,
2174) {
2175 if !actual.found || actual.visible == Some(false) {
2176 return;
2177 }
2178 if actual.identifier.as_deref() != Some(nid) {
2179 fails.push(format!(
2180 "{nid}: native identifier {:?} ≠ {nid:?}",
2181 actual.identifier
2182 ));
2183 }
2184 if expected.role != day_spec::Role::None
2189 && actual.role != day_spec::Role::None
2190 && !role_eq(expected.role, actual.role)
2191 {
2192 fails.push(format!(
2193 "{nid}: role {:?} ≠ expected {:?}",
2194 actual.role, expected.role
2195 ));
2196 }
2197 if let Some(lbl) = &expected.label
2198 && actual.label.as_deref() != Some(lbl.as_str())
2199 {
2200 fails.push(format!(
2201 "{nid}: label {:?} ≠ expected {lbl:?}",
2202 actual.label
2203 ));
2204 }
2205 if let Some(val) = &expected.value
2206 && actual.value.as_deref() != Some(val.as_str())
2207 {
2208 fails.push(format!(
2209 "{nid}: value {:?} ≠ expected {val:?}",
2210 actual.value
2211 ));
2212 }
2213}
2214
2215fn role_eq(a: day_spec::Role, b: day_spec::Role) -> bool {
2218 use day_spec::Role::Heading;
2219 matches!((a, b), (Heading(_), Heading(_))) || a == b
2220}
2221
2222const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2227
2228pub fn b64encode(data: &[u8]) -> String {
2229 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
2230 for chunk in data.chunks(3) {
2231 let b = [
2232 chunk[0],
2233 *chunk.get(1).unwrap_or(&0),
2234 *chunk.get(2).unwrap_or(&0),
2235 ];
2236 let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
2237 out.push(B64[(n >> 18) as usize & 63] as char);
2238 out.push(B64[(n >> 12) as usize & 63] as char);
2239 out.push(if chunk.len() > 1 {
2240 B64[(n >> 6) as usize & 63] as char
2241 } else {
2242 '='
2243 });
2244 out.push(if chunk.len() > 2 {
2245 B64[n as usize & 63] as char
2246 } else {
2247 '='
2248 });
2249 }
2250 out
2251}
2252
2253pub fn b64decode(s: &str) -> Vec<u8> {
2254 let val = |c: u8| B64.iter().position(|&x| x == c).unwrap_or(0) as u32;
2255 let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'\n' && c != b'\r').collect();
2256 let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
2257 for chunk in bytes.chunks(4) {
2258 if chunk.len() < 4 {
2259 break;
2260 }
2261 let pad = chunk.iter().filter(|&&c| c == b'=').count();
2262 let n = (val(chunk[0]) << 18)
2263 | (val(chunk[1]) << 12)
2264 | (val(if chunk[2] == b'=' { b'A' } else { chunk[2] }) << 6)
2265 | val(if chunk[3] == b'=' { b'A' } else { chunk[3] });
2266 out.push((n >> 16) as u8);
2267 if pad < 2 {
2268 out.push((n >> 8) as u8);
2269 }
2270 if pad < 1 {
2271 out.push(n as u8);
2272 }
2273 }
2274 out
2275}
2276
2277#[cfg(test)]
2278mod tests {
2279 use super::*;
2280
2281 #[test]
2282 fn a11y_audit_checks_metadata_when_visible_or_visibility_is_unknown() {
2283 let expected = day_spec::A11yProps {
2285 label: Some("Fixture list".into()),
2286 ..Default::default()
2287 };
2288 let mut actual = day_spec::NativeSnapshot {
2289 found: true,
2290 identifier: Some("fixture-list".into()),
2291 visible: Some(false),
2292 ..Default::default()
2293 };
2294 let mut fails = Vec::new();
2295 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2296 assert!(
2297 fails.is_empty(),
2298 "hidden panes need not expose their labels"
2299 );
2300
2301 for visible in [Some(true), None] {
2302 actual.visible = visible;
2303 fails.clear();
2304 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2305 assert_eq!(
2306 fails.len(),
2307 1,
2308 "missing labels must still fail: {visible:?}"
2309 );
2310 assert!(fails[0].contains("label None"));
2311 }
2312
2313 actual.visible = Some(true);
2314 actual.label = expected.label.clone();
2315 fails.clear();
2316 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2317 assert!(
2318 fails.is_empty(),
2319 "the list exposes its label when shown again"
2320 );
2321
2322 actual.label = None;
2323 actual.found = false;
2324 audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2325 assert!(
2326 fails.is_empty(),
2327 "unreadable accessibility nodes remain unsupported"
2328 );
2329 }
2330
2331 #[test]
2332 fn dialog_steps_hold_requests_until_an_explicit_response() {
2333 use day_spec::present::{PresentResult, PresentSpec};
2334 use std::future::Future;
2335 use std::task::{Context, Poll, Waker};
2336 assert!(serde_json::from_str::<Step>(r#"{"op":"dialog_mode","mode":"typo"}"#).is_err());
2337 let mode: Step = serde_json::from_str(r#"{"op":"dialog_mode","mode":"scripted"}"#).unwrap();
2338 assert!(exec(mode, 0).ok);
2339 assert!(exec(Step::AssertNotPresented, 0).ok);
2340 let mut future = Box::pin(day_core::present(PresentSpec::OpenFile {
2342 title: "Choose file".into(),
2343 filters: vec![],
2344 multiple: false,
2345 }));
2346 let mut cx = Context::from_waker(Waker::noop());
2347 assert!(future.as_mut().poll(&mut cx).is_pending());
2348 assert!(
2349 exec(
2350 Step::AssertPresented {
2351 title: Some("Choose file".into())
2352 },
2353 0
2354 )
2355 .ok
2356 );
2357 assert!(!exec(Step::AssertNotPresented, 0).ok);
2358 let refused = exec(
2359 Step::DialogMode {
2360 mode: DialogMode::Native,
2361 },
2362 0,
2363 );
2364 assert!(!refused.ok && !refused.retryable);
2365 assert!(
2366 exec(
2367 Step::Respond {
2368 button: None,
2369 text: None,
2370 path: None,
2371 dismiss: true
2372 },
2373 0
2374 )
2375 .ok
2376 );
2377 assert_eq!(
2378 future.as_mut().poll(&mut cx),
2379 Poll::Ready(PresentResult::Dismissed)
2380 );
2381 assert!(exec(Step::AssertNotPresented, 0).ok);
2382 assert!(
2383 exec(
2384 Step::DialogMode {
2385 mode: DialogMode::Native
2386 },
2387 0
2388 )
2389 .ok
2390 );
2391 }
2392
2393 #[test]
2394 fn optional_tap_only_skips_absent_elements_after_transitions_settle() {
2395 use day_pieces::prelude::*;
2396 let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2397 day_core::uninstall_tree();
2398 let enabled = Signal::new(false);
2399 let presses = Signal::new(0);
2400 let (mock, probe) = day_mock::MockToolkit::new();
2401 day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2402 button("Remove fixture")
2403 .enabled(move || enabled.get())
2404 .action(move || presses.update(|n| *n += 1))
2405 .id(day_core::id!(remove_fixture))
2406 .height(50.)
2407 .grow_w()
2408 .any()
2409 });
2410 let tap = |id, optional| {
2411 exec(
2412 serde_json::from_value(serde_json::json!({
2413 "op": "tap", "id": id, "if_present": optional
2414 }))
2415 .unwrap(),
2416 1,
2417 )
2418 };
2419 assert!(!tap("missing", false).ok);
2420 let absent = tap("missing", true);
2421 assert!(absent.ok);
2422 assert!(absent.id_evidence.is_empty());
2423 probe.state.borrow_mut().ui_busy = true;
2424 assert!(!tap("missing", true).ok);
2425 probe.state.borrow_mut().ui_busy = false;
2426 let disabled = tap("remove_fixture", true);
2427 assert!(!disabled.ok && disabled.retryable);
2428 assert_eq!(presses.get(), 0);
2429 enabled.set(true);
2430 id_catalog().expect("the compiled test fixture registry is valid");
2431 let present = tap("remove_fixture", true);
2432 assert!(present.ok);
2433 assert_eq!(present.id_evidence.len(), 1);
2434 assert_eq!(present.id_evidence[0].family, "remove_fixture");
2435 assert_eq!(
2436 present.id_evidence[0].class,
2437 day_script_protocol::EvidenceClass::Interaction
2438 );
2439 assert_eq!(presses.get(), 1);
2440 day_core::uninstall_tree();
2441 }
2442
2443 #[test]
2444 fn tap_waits_for_navigation_and_enabled_state_before_dispatching_once() {
2445 use day_pieces::prelude::*;
2446 let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2447 day_core::uninstall_tree();
2448 let enabled = Signal::new(false);
2449 let presses = Signal::new(0);
2450 let (mock, probe) = day_mock::MockToolkit::new();
2451 day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2452 button("Fixture download")
2453 .enabled(move || enabled.get())
2454 .action(move || presses.update(|n| *n += 1))
2455 .id(day_core::id!(fixture_download))
2456 .height(50.)
2457 .grow_w()
2458 .any()
2459 });
2460 let tap = || {
2461 exec(
2462 serde_json::from_value(serde_json::json!({
2463 "op": "tap", "id": "fixture_download"
2464 }))
2465 .unwrap(),
2466 1,
2467 )
2468 };
2469 let reply = tap();
2470 assert!(!reply.ok && reply.retryable);
2471 assert!(reply.error.unwrap().contains("disabled"));
2472 assert_eq!(presses.get(), 0);
2473 enabled.set(true);
2474 probe.state.borrow_mut().ui_busy = true;
2475 assert!(!tap().ok);
2476 assert!(!exec(Step::WaitIdle, 1).ok);
2477 assert_eq!(presses.get(), 0);
2478 probe.state.borrow_mut().ui_busy = false;
2479 assert!(exec(Step::WaitIdle, 1).ok);
2480 assert!(tap().ok);
2481 assert_eq!(presses.get(), 1);
2482 day_core::uninstall_tree();
2483 }
2484
2485 #[test]
2486 fn capture_acknowledgments_are_optional_and_pending_stays_internal() {
2487 let old: Reply = serde_json::from_str(r#"{"ok":true}"#).unwrap();
2488 assert_eq!(old.capture_revision, None);
2489 assert_eq!(old.fast_animations, None);
2490 let reply = Reply {
2491 capture_revision: Some(73),
2492 fast_animations: Some(true),
2493 capture_pending: true,
2494 ..Reply::ok()
2495 };
2496 let json = serde_json::to_value(reply).unwrap();
2497 assert_eq!(json["capture_revision"], 73);
2498 assert!(json.get("capture_pending").is_none());
2499 let decoded: Reply = serde_json::from_value(json).unwrap();
2500 assert_eq!(decoded.capture_revision, Some(73));
2501 assert_eq!(decoded.fast_animations, Some(true));
2502 }
2503
2504 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2506
2507 #[test]
2511 fn the_main_thread_budget_is_generous_overridable_and_never_below_the_step() {
2512 let five = Duration::from_secs(5);
2513 let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2514 unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2516 assert_eq!(
2517 main_thread_budget(five),
2518 Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS)
2519 );
2520 assert_eq!(
2522 main_thread_budget(Duration::from_secs(120)),
2523 Duration::from_secs(120)
2524 );
2525 unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", "90") };
2526 assert_eq!(main_thread_budget(five), Duration::from_secs(90));
2527 for bad in ["0", "-3", "abc", ""] {
2529 unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", bad) };
2530 assert_eq!(
2531 main_thread_budget(five),
2532 Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS),
2533 "{bad:?} should fall back to the default"
2534 );
2535 }
2536 unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2537 }
2538
2539 #[test]
2543 fn assert_text_honors_its_own_timeout() {
2544 let step = |json: &str| serde_json::from_str::<Step>(json).expect("step");
2545 let slow = step(r#"{"op":"assert_text","id":"state","text":"done","timeout_secs":120}"#);
2546 assert_eq!(slow.wait_budget_secs(), 120.0);
2547 let plain = step(r#"{"op":"assert_text","id":"state","text":"done"}"#);
2548 assert_eq!(plain.wait_budget_secs(), DEFAULT_TIMEOUT_SECS);
2549 let waiting = step(r#"{"op":"wait_for","id":"state","timeout_secs":30}"#);
2550 assert_eq!(waiting.wait_budget_secs(), 30.0);
2551 }
2552
2553 #[test]
2556 fn web_eval_honors_its_own_timeout() {
2557 for (timeout, expected) in [
2558 (None, DEFAULT_TIMEOUT_SECS),
2559 (Some(30.0), 30.0),
2560 (Some(0.0), DEFAULT_TIMEOUT_SECS),
2561 (Some(-1.0), DEFAULT_TIMEOUT_SECS),
2562 ] {
2563 let step: Step = serde_json::from_value(serde_json::json!({
2564 "op": "web_eval", "id": "page", "script": "document.title",
2565 "timeout_secs": timeout,
2566 }))
2567 .expect("web_eval step");
2568 assert_eq!(step.wait_budget_secs(), expected);
2569 }
2570 }
2571
2572 #[test]
2576 fn menu_id_addresses_an_item_whose_label_moves() {
2577 use day_spec::MenuItem as MI;
2578 let model = |mark: &str| {
2579 vec![MI::Submenu {
2580 label: "View".into(),
2581 role: None,
2582 items: vec![
2583 MI::Action {
2584 id: Some("view-grid".into()),
2585 action: 42,
2586 label: format!("{mark}Grid"),
2587 shortcut: None,
2588 enabled: true,
2589 checked: Some(mark == "\u{2713} "),
2590 role: None,
2591 icon: None,
2592 },
2593 MI::Action {
2594 id: None,
2595 action: 7,
2596 label: "Grid".into(),
2597 shortcut: None,
2598 enabled: true,
2599 checked: None,
2600 role: None,
2601 icon: None,
2602 },
2603 ],
2604 }]
2605 };
2606 let by_id = |items: &[MI]| {
2607 find_menu_actions(items, "", None, Some("view-grid"), &[])
2608 .into_iter()
2609 .map(|(a, _, _)| a)
2610 .collect::<Vec<_>>()
2611 };
2612 assert_eq!(by_id(&model("\u{2713} ")), vec![42]);
2614 assert_eq!(by_id(&model(" ")), vec![42]);
2615 assert_eq!(
2618 find_menu_actions(&model(" "), "Grid", None, None, &[])
2619 .into_iter()
2620 .map(|(a, _, _)| a)
2621 .collect::<Vec<_>>(),
2622 vec![7]
2623 );
2624 assert!(
2626 find_menu_actions(&model(" "), "Grid", None, Some("view-ruler"), &[]).is_empty()
2627 );
2628 }
2629}