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