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