1use std::collections::VecDeque;
135use std::path::PathBuf;
136use std::sync::{Arc, Condvar, Mutex, PoisonError};
137
138use core::time::Duration;
139
140use crcbl_core::input::{
141 ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
142 TouchPhase,
143};
144use crcbl_core::time::{ManualTime, TimeSource};
145use crcbl_core::{EventTime, Pool, SurfaceTarget};
146
147use crate::frame::FrameRequests;
148use crate::waker::WakeSignal;
149use crate::{
150 ClipboardContent, ClipboardOffer, ClipboardRequestId, CloseReply, CursorIcon, DisplayMode,
151 KeyCode, LogicalRect, LogicalSize, MimeType, MonitorId, MonitorInfo, PhysicalPoint,
152 PhysicalRect, PhysicalSize, PointerMode, ReceivedMime, Shell, ShellBackend, ShellCaps,
153 ShellError, ShellEvent, ShellWaker, SizeConstraints, TextPurpose, WebUrl, WindowConfiguration,
154 WindowDesc, WindowId, WindowState,
155};
156
157pub const DEFAULT_MONITOR_SIZE: PhysicalSize = PhysicalSize::new(1920, 1080);
162
163pub const DEFAULT_REFRESH_MILLIHERTZ: u32 = 60_000;
165
166pub const DEFAULT_CONFIGURE_DELAY: u32 = 1;
172
173pub const VIRTUAL_DEVICE: DeviceId = DeviceId(1);
179
180pub const DEFAULT_CLIPBOARD_DEADLINE: u32 = 4;
188
189#[derive(Clone, Debug)]
195struct PendingRead {
196 window: WindowId,
197 request: ClipboardRequestId,
198 mime: MimeType,
199 countdown: u32,
201}
202
203#[derive(Clone, Copy, Debug)]
207struct PendingConfigure {
208 size: PhysicalSize,
209 scale_factor: f64,
210 mode: DisplayMode,
211 countdown: u32,
213}
214
215struct ScheduledScript {
217 countdown: u32,
219 script: Box<dyn FnOnce(&mut HeadlessShell) + Send>,
220}
221
222impl core::fmt::Debug for ScheduledScript {
223 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224 f.debug_struct("ScheduledScript")
225 .field("countdown", &self.countdown)
226 .finish_non_exhaustive()
227 }
228}
229
230#[derive(Clone, Debug)]
232struct HeadlessWindow {
233 title: String,
234 configuration: Option<WindowConfiguration>,
236 pending: Option<PendingConfigure>,
238 requested_mode: DisplayMode,
239 requested_constraints: SizeConstraints,
240 focused: bool,
241 visible: bool,
242 pointer_mode: PointerMode,
243 cursor: Option<CursorIcon>,
244 close_pending: bool,
245 accept_drops: bool,
246 parent: Option<WindowId>,
248 popup_input: Option<crate::PopupInput>,
250 panel: Option<crate::role::KeptPanel>,
254 text_input: Option<TextPurpose>,
256 text_input_area: Option<PhysicalRect>,
258 input_region: Option<Vec<PhysicalRect>>,
260 idle_inhibit: bool,
262 #[cfg(feature = "accesskit")]
265 accessibility: Option<Vec<accesskit::TreeUpdate>>,
266}
267
268impl HeadlessWindow {
269 fn size(&self) -> Option<PhysicalSize> {
271 self.configuration.map(|config| config.size)
272 }
273
274 fn scale_factor(&self) -> f64 {
280 self.configuration
281 .map(|config| config.scale_factor)
282 .or_else(|| self.pending.map(|pending| pending.scale_factor))
283 .unwrap_or(1.0)
284 }
285
286 fn settled_mode(&self) -> DisplayMode {
295 self.configuration
296 .map(|config| config.mode)
297 .or_else(|| self.pending.map(|pending| pending.mode))
298 .unwrap_or(self.requested_mode)
299 }
300
301 fn base_size(&self) -> PhysicalSize {
303 self.size()
304 .or_else(|| self.pending.map(|pending| pending.size))
305 .unwrap_or(PhysicalSize::new(1, 1))
306 }
307
308 fn configure_at(&mut self, size: LogicalSize, countdown: u32) {
312 if let Some(pending) = self.pending.as_mut() {
313 pending.size = size.to_physical(pending.scale_factor);
314 } else if let Some(config) = self.configuration {
315 self.pending = Some(PendingConfigure {
316 size: size.to_physical(config.scale_factor),
317 scale_factor: config.scale_factor,
318 mode: config.mode,
319 countdown,
320 });
321 }
322 }
323}
324
325#[derive(Debug)]
330pub struct HeadlessShell {
331 caps: ShellCaps,
332 monitors: Vec<MonitorInfo>,
333 next_monitor_id: u32,
334 windows: Pool<HeadlessWindow>,
335 queue: VecDeque<ShellEvent>,
336 scripts: Vec<ScheduledScript>,
339 clock: ManualTime,
340 modifiers: Modifiers,
341 clipboard: Vec<(ReceivedMime, Vec<u8>)>,
342 next_request_id: u32,
343 reads: Vec<PendingRead>,
346 clipboard_readable: bool,
350 clipboard_stalled: bool,
352 clipboard_needs_interaction: bool,
354 saw_interaction: bool,
357 clipboard_deadline: u32,
360 waits: u32,
361 configure_delay: u32,
362 wake: Option<Arc<HeadlessWake>>,
364 frames: FrameRequests,
366 outputs_powered: bool,
369 opened_urls: Vec<(WindowId, WebUrl)>,
372}
373
374#[derive(Debug, Default)]
377struct HeadlessWake {
378 rung: Mutex<bool>,
379 bell: Condvar,
380}
381
382impl HeadlessWake {
383 fn wait(&self, timeout: Option<Duration>) {
386 let rung = self.rung.lock().unwrap_or_else(PoisonError::into_inner);
387 let mut rung = match timeout {
388 Some(timeout) => {
389 self.bell
390 .wait_timeout_while(rung, timeout, |rung| !*rung)
391 .unwrap_or_else(PoisonError::into_inner)
392 .0
393 }
394 None => self
395 .bell
396 .wait_while(rung, |rung| !*rung)
397 .unwrap_or_else(PoisonError::into_inner),
398 };
399 *rung = false;
400 }
401}
402
403impl WakeSignal for HeadlessWake {
404 fn wake(&self) {
405 *self.rung.lock().unwrap_or_else(PoisonError::into_inner) = true;
406 self.bell.notify_all();
407 }
408}
409
410impl Default for HeadlessShell {
411 fn default() -> Self {
412 Self::new()
413 }
414}
415
416impl HeadlessShell {
417 #[must_use]
419 pub fn new() -> Self {
420 Self {
421 caps: ShellCaps::DESKTOP,
422 monitors: vec![MonitorInfo {
423 id: MonitorId(1),
424 name: "HEADLESS-1".to_string(),
425 connector: None,
426 bounds: PhysicalRect::new(
427 0,
428 0,
429 DEFAULT_MONITOR_SIZE.width,
430 DEFAULT_MONITOR_SIZE.height,
431 ),
432 work_area: PhysicalRect::new(
433 0,
434 0,
435 DEFAULT_MONITOR_SIZE.width,
436 DEFAULT_MONITOR_SIZE.height,
437 ),
438 scale_factor: 1.0,
439 refresh_millihertz: DEFAULT_REFRESH_MILLIHERTZ,
440 is_primary: true,
441 }],
442 next_monitor_id: 2,
443 windows: Pool::new(),
444 queue: VecDeque::new(),
445 scripts: Vec::new(),
446 clock: ManualTime::new(),
447 modifiers: Modifiers::empty(),
448 clipboard: Vec::new(),
449 next_request_id: 1,
450 reads: Vec::new(),
451 clipboard_readable: true,
452 clipboard_stalled: false,
453 clipboard_needs_interaction: false,
454 saw_interaction: false,
455 clipboard_deadline: DEFAULT_CLIPBOARD_DEADLINE,
456 waits: 0,
457 configure_delay: DEFAULT_CONFIGURE_DELAY,
458 wake: None,
459 frames: FrameRequests::default(),
460 outputs_powered: true,
461 opened_urls: Vec::new(),
462 }
463 }
464
465 #[must_use]
470 pub fn with_caps(mut self, caps: ShellCaps) -> Self {
471 self.caps = caps;
472 self
473 }
474
475 #[must_use]
490 pub fn with_monitors(mut self, monitors: Vec<MonitorInfo>) -> Self {
491 assert!(!monitors.is_empty(), "a shell needs at least one monitor");
492 for (index, monitor) in monitors.iter().enumerate() {
493 assert!(
494 monitor.id.0 != u32::MAX,
495 "monitor id {} leaves no id for the next hotplug",
496 monitor.id.0
497 );
498 assert!(
499 !monitors[..index].iter().any(|seen| seen.id == monitor.id),
500 "monitor id {} appears twice",
501 monitor.id.0
502 );
503 }
504 self.next_monitor_id = monitors
505 .iter()
506 .map(|monitor| monitor.id.0 + 1)
507 .max()
508 .unwrap_or(1);
509 self.monitors = monitors;
510 self
511 }
512
513 #[must_use]
518 pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
519 assert!(scale_factor > 0.0, "scale factor must be positive");
520 self.monitors[0].scale_factor = scale_factor;
521 self
522 }
523
524 #[must_use]
529 pub const fn with_configure_delay(mut self, pumps: u32) -> Self {
530 self.configure_delay = pumps;
531 self
532 }
533
534 pub const fn set_configure_delay(&mut self, pumps: u32) {
544 self.configure_delay = pumps;
545 }
546
547 pub fn set_caps(&mut self, caps: ShellCaps) {
553 self.caps = caps;
554 }
555
556 #[must_use]
558 pub fn now(&self) -> EventTime {
559 EventTime::from_duration(self.clock.elapsed())
560 }
561
562 pub fn advance(&mut self, delta: Duration) {
568 self.clock.advance(delta);
569 }
570
571 pub fn set_time(&mut self, now: Duration) {
579 self.clock.set(now);
580 }
581
582 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
587 self.modifiers = modifiers;
588 }
589
590 #[must_use]
592 pub fn pending_events(&self) -> usize {
593 self.queue.len()
594 }
595
596 #[must_use]
602 pub const fn wait_count(&self) -> u32 {
603 self.waits
604 }
605
606 pub fn inject(&mut self, event: ShellEvent) {
614 self.queue.push_back(event);
615 }
616
617 pub fn schedule(&mut self, pumps: u32, script: impl FnOnce(&mut Self) + Send + 'static) {
636 self.scripts.push(ScheduledScript {
637 countdown: pumps,
638 script: Box::new(script),
639 });
640 }
641
642 pub fn resize(&mut self, window: WindowId, size: PhysicalSize) -> Result<(), ShellError> {
658 let state = self.window_mut(window)?;
659 let scale_factor = state.scale_factor();
660 let mode = state.settled_mode();
661 let constrained = state.requested_constraints.apply(size, scale_factor);
662 state.pending = None;
663 state.configuration = Some(WindowConfiguration {
664 size: constrained,
665 scale_factor,
666 mode,
667 });
668 self.queue.push_back(ShellEvent::Resized {
669 window,
670 size: constrained,
671 scale_factor,
672 });
673 Ok(())
674 }
675
676 pub fn change_scale_factor(
698 &mut self,
699 window: WindowId,
700 scale_factor: f64,
701 ) -> Result<(), ShellError> {
702 assert!(scale_factor > 0.0, "scale factor must be positive");
703 let state = self.window_mut(window)?;
704 let logical = state.base_size().to_logical(state.scale_factor());
705 let mode = state.settled_mode();
706 let size = state
707 .requested_constraints
708 .apply(logical.to_physical(scale_factor), scale_factor);
709 state.pending = None;
710 state.configuration = Some(WindowConfiguration {
711 size,
712 scale_factor,
713 mode,
714 });
715 self.queue.push_back(ShellEvent::ScaleFactorChanged {
716 window,
717 scale_factor,
718 size,
719 });
720 self.queue.push_back(ShellEvent::Resized {
721 window,
722 size,
723 scale_factor,
724 });
725 Ok(())
726 }
727
728 pub fn set_focus(&mut self, window: WindowId, focused: bool) -> Result<(), ShellError> {
734 self.window_mut(window)?.focused = focused;
735 self.queue.push_back(ShellEvent::Focus { window, focused });
736 Ok(())
737 }
738
739 pub fn request_close(&mut self, window: WindowId) -> Result<(), ShellError> {
748 self.window_mut(window)?.close_pending = true;
749 self.queue.push_back(ShellEvent::CloseRequested { window });
750 Ok(())
751 }
752
753 pub fn key(
766 &mut self,
767 window: WindowId,
768 key: KeyCode,
769 state: ButtonState,
770 ) -> Result<(), ShellError> {
771 self.key_with(window, key, state, false)
772 }
773
774 pub fn key_press(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
780 self.key(window, key, ButtonState::Pressed)
781 }
782
783 pub fn key_release(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
789 self.key(window, key, ButtonState::Released)
790 }
791
792 pub fn key_repeat(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
799 self.key_with(window, key, ButtonState::Pressed, true)
800 }
801
802 fn key_with(
803 &mut self,
804 window: WindowId,
805 key: KeyCode,
806 state: ButtonState,
807 repeat: bool,
808 ) -> Result<(), ShellError> {
809 let popup_input = self.window(window)?.popup_input;
810 self.saw_interaction = true;
811 let event = ShellEvent::Key {
812 window,
813 device: VIRTUAL_DEVICE,
814 time: self.now(),
815 scancode: synthetic_scancode(key),
816 key_code: Some(key),
817 keysym: synthetic_keysym(key),
818 shortcut_keysym: synthetic_keysym(key),
820 state,
821 repeat,
822 modifiers: self.modifiers,
823 };
824 let dismissed = crate::role::escape_dismisses(popup_input, &event);
825 self.queue.push_back(event);
826 if dismissed && !self.window(window)?.close_pending {
828 self.request_close(window)?;
829 }
830 Ok(())
831 }
832
833 pub fn move_pointer(
844 &mut self,
845 window: WindowId,
846 position: PhysicalPoint,
847 raw_delta: (f64, f64),
848 ) -> Result<(), ShellError> {
849 let locked = self.window(window)?.pointer_mode == PointerMode::Locked;
850 let raw = if self.caps.contains(ShellCaps::RAW_POINTER_MOTION) {
851 Some(raw_delta)
852 } else {
853 None
854 };
855 self.saw_interaction = true;
856 let event = ShellEvent::PointerMotion {
857 window,
858 device: VIRTUAL_DEVICE,
859 time: self.now(),
860 abs: if locked { None } else { Some(position) },
861 raw_delta: raw,
862 };
863 self.queue.push_back(event);
864 Ok(())
865 }
866
867 pub fn set_pointer_focus(
873 &mut self,
874 window: WindowId,
875 entered: bool,
876 position: Option<PhysicalPoint>,
877 ) -> Result<(), ShellError> {
878 self.check_window(window)?;
879 let event = ShellEvent::PointerFocus {
880 window,
881 device: VIRTUAL_DEVICE,
882 time: self.now(),
883 entered,
884 position: if entered { position } else { None },
885 };
886 self.queue.push_back(event);
887 Ok(())
888 }
889
890 pub fn button(
896 &mut self,
897 window: WindowId,
898 button: PointerButton,
899 state: ButtonState,
900 position: Option<PhysicalPoint>,
901 ) -> Result<(), ShellError> {
902 self.check_window(window)?;
903 self.saw_interaction = true;
904 let event = ShellEvent::Button {
905 window,
906 device: VIRTUAL_DEVICE,
907 time: self.now(),
908 button,
909 state,
910 position,
911 modifiers: self.modifiers,
912 };
913 self.queue.push_back(event);
914 Ok(())
915 }
916
917 pub fn scroll(
923 &mut self,
924 window: WindowId,
925 delta: ScrollDelta,
926 position: Option<PhysicalPoint>,
927 ) -> Result<(), ShellError> {
928 self.check_window(window)?;
929 self.saw_interaction = true;
930 let event = ShellEvent::Wheel {
931 window,
932 device: VIRTUAL_DEVICE,
933 time: self.now(),
934 delta,
935 position,
936 modifiers: self.modifiers,
937 };
938 self.queue.push_back(event);
939 Ok(())
940 }
941
942 pub fn touch(
970 &mut self,
971 window: WindowId,
972 contact: ContactId,
973 phase: TouchPhase,
974 position: PhysicalPoint,
975 ) -> Result<(), ShellError> {
976 self.check_window(window)?;
977 if !self.caps.contains(ShellCaps::TOUCH) {
978 return Err(self.unsupported("touch"));
979 }
980 self.saw_interaction = true;
981 let event = ShellEvent::Touch {
982 window,
983 device: VIRTUAL_DEVICE,
984 time: self.now(),
985 contact,
986 phase,
987 position,
988 };
989 self.queue.push_back(event);
990 Ok(())
991 }
992
993 pub fn commit_text(&mut self, window: WindowId, text: &str) -> Result<(), ShellError> {
1004 assert!(!text.is_empty(), "a text commit is never empty");
1005 self.check_window(window)?;
1006 let event = ShellEvent::TextCommit {
1007 window,
1008 time: self.now(),
1009 text: text.to_string(),
1010 };
1011 self.queue.push_back(event);
1012 Ok(())
1013 }
1014
1015 pub fn preedit_text(
1028 &mut self,
1029 window: WindowId,
1030 text: &str,
1031 cursor: Option<usize>,
1032 ) -> Result<(), ShellError> {
1033 assert!(
1034 cursor.is_none_or(|cursor| !text.is_empty() && text.is_char_boundary(cursor)),
1035 "a pre-edit's cursor is a char boundary of a non-empty text"
1036 );
1037 self.check_window(window)?;
1038 let event = ShellEvent::TextPreedit {
1039 window,
1040 time: self.now(),
1041 text: text.to_string(),
1042 cursor,
1043 };
1044 self.queue.push_back(event);
1045 Ok(())
1046 }
1047
1048 pub fn drop_file(
1056 &mut self,
1057 window: WindowId,
1058 path: impl Into<PathBuf>,
1059 position: Option<PhysicalPoint>,
1060 ) -> Result<(), ShellError> {
1061 if !self.caps.contains(ShellCaps::DRAG_DROP) {
1062 return Err(self.unsupported("drag and drop"));
1063 }
1064 if !self.window(window)?.accept_drops {
1065 return Err(ShellError::Unsupported {
1066 backend: ShellBackend::Headless,
1067 what: "drops on a window created without accept_drops",
1068 });
1069 }
1070 let event = ShellEvent::DroppedFile {
1071 window,
1072 time: self.now(),
1073 path: path.into(),
1074 position,
1075 };
1076 self.queue.push_back(event);
1077 Ok(())
1078 }
1079
1080 pub fn plug_monitor(&mut self, mut info: MonitorInfo) -> MonitorId {
1087 let id = MonitorId(self.next_monitor_id);
1088 self.next_monitor_id += 1;
1089 info.id = id;
1090 self.monitors.push(info);
1091 self.queue.push_back(ShellEvent::MonitorsChanged);
1092 id
1093 }
1094
1095 pub fn unplug_monitor(&mut self, id: MonitorId) -> Result<(), ShellError> {
1109 let index = self
1110 .monitors
1111 .iter()
1112 .position(|monitor| monitor.id == id)
1113 .ok_or(ShellError::NoSuchMonitor(id.0))?;
1114 assert!(
1115 self.monitors.len() > 1,
1116 "a shell needs at least one monitor"
1117 );
1118 let previous = self.monitors.clone();
1119 self.monitors.remove(index);
1120 crate::monitor::queue_removed(&previous, &self.monitors, &mut self.queue);
1121 let panels: Vec<WindowId> = self
1122 .windows
1123 .iter()
1124 .filter(|(_, state)| {
1125 state.panel.as_ref().and_then(|panel| panel.desc().monitor) == Some(id)
1126 && !state.close_pending
1127 })
1128 .map(|(window, _)| window.cast())
1129 .collect();
1130 for panel in panels {
1131 self.request_close(panel)?;
1132 }
1133 self.queue.push_back(ShellEvent::MonitorsChanged);
1134 Ok(())
1135 }
1136
1137 pub fn title(&self, window: WindowId) -> Result<&str, ShellError> {
1148 Ok(self.window(window)?.title.as_str())
1149 }
1150
1151 pub fn cursor(&self, window: WindowId) -> Result<Option<CursorIcon>, ShellError> {
1159 Ok(self.window(window)?.cursor)
1160 }
1161
1162 pub fn text_input(&self, window: WindowId) -> Result<Option<TextPurpose>, ShellError> {
1171 Ok(self.window(window)?.text_input)
1172 }
1173
1174 pub fn text_input_area(&self, window: WindowId) -> Result<Option<PhysicalRect>, ShellError> {
1184 Ok(self.window(window)?.text_input_area)
1185 }
1186
1187 pub fn panel(&self, window: WindowId) -> Result<Option<crate::PanelDesc<'_>>, ShellError> {
1196 Ok(self
1197 .window(window)?
1198 .panel
1199 .as_ref()
1200 .map(crate::role::KeptPanel::desc))
1201 }
1202
1203 pub fn input_region(&self, window: WindowId) -> Result<Option<&[PhysicalRect]>, ShellError> {
1214 Ok(self.window(window)?.input_region.as_deref())
1215 }
1216
1217 pub fn frame_requested(&self, window: WindowId) -> Result<bool, ShellError> {
1227 self.window(window)?;
1228 Ok(self.frames.contains(window))
1229 }
1230
1231 pub fn idle_inhibited(&self, window: WindowId) -> Result<bool, ShellError> {
1242 Ok(self.window(window)?.idle_inhibit)
1243 }
1244
1245 #[must_use]
1253 pub fn opened_urls(&self) -> &[(WindowId, WebUrl)] {
1254 &self.opened_urls
1255 }
1256
1257 pub fn set_outputs_powered(&mut self, powered: bool) {
1273 self.outputs_powered = powered;
1274 }
1275
1276 #[cfg(feature = "accesskit")]
1285 pub fn activate_accessibility(&mut self, window: WindowId) -> Result<(), ShellError> {
1286 let state = &mut self.window_mut(window)?.accessibility;
1287 if state.is_none() {
1288 *state = Some(Vec::new());
1289 self.queue
1290 .push_back(ShellEvent::AccessibilityActivated { window });
1291 }
1292 Ok(())
1293 }
1294
1295 #[cfg(feature = "accesskit")]
1305 pub fn deactivate_accessibility(&mut self, window: WindowId) -> Result<(), ShellError> {
1306 if self.window_mut(window)?.accessibility.take().is_some() {
1307 self.queue
1308 .push_back(ShellEvent::AccessibilityDeactivated { window });
1309 }
1310 Ok(())
1311 }
1312
1313 #[cfg(feature = "accesskit")]
1327 pub fn request_accessibility_action(
1328 &mut self,
1329 window: WindowId,
1330 request: accesskit::ActionRequest,
1331 ) -> Result<(), ShellError> {
1332 assert!(
1333 self.window(window)?.accessibility.is_some(),
1334 "no assistive technology is reading the window"
1335 );
1336 self.queue
1337 .push_back(ShellEvent::AccessibilityAction { window, request });
1338 Ok(())
1339 }
1340
1341 #[cfg(feature = "accesskit")]
1350 pub fn accessibility_updates(
1351 &self,
1352 window: WindowId,
1353 ) -> Result<Option<&[accesskit::TreeUpdate]>, ShellError> {
1354 Ok(self.window(window)?.accessibility.as_deref())
1355 }
1356
1357 #[must_use]
1361 pub fn clipboard_bytes(&self, mime: MimeType) -> Option<&[u8]> {
1362 self.clipboard
1363 .iter()
1364 .find(|(offered, _)| offered.matches(mime))
1365 .map(|(_, bytes)| bytes.as_slice())
1366 }
1367
1368 pub fn set_clipboard_readable(&mut self, readable: bool) {
1385 self.clipboard_readable = readable;
1386 }
1387
1388 pub fn set_clipboard_stalled(&mut self, stalled: bool) {
1397 self.clipboard_stalled = stalled;
1398 }
1399
1400 pub fn require_user_interaction(&mut self, required: bool) {
1427 self.clipboard_needs_interaction = required;
1428 }
1429
1430 pub fn clear_user_interaction(&mut self) {
1435 self.saw_interaction = false;
1436 }
1437
1438 pub fn clipboard_deadline(&mut self, pumps: u32) {
1444 self.clipboard_deadline = pumps;
1445 }
1446
1447 #[must_use]
1452 pub fn held_clipboard_reads(&self) -> usize {
1453 self.reads.len()
1454 }
1455
1456 pub fn set_foreign_clipboard(&mut self, offers: Vec<(ReceivedMime, Vec<u8>)>) {
1464 self.clipboard = offers;
1465 }
1466
1467 fn answerable(&self) -> bool {
1473 self.clipboard_readable && !self.clipboard_stalled
1474 }
1475
1476 fn answer(&self, window: WindowId, request: ClipboardRequestId, mime: MimeType) -> ShellEvent {
1478 let found = self
1483 .clipboard
1484 .iter()
1485 .find(|(offered, _)| offered.matches(mime));
1486 let (mime, content) = match found {
1487 Some((offered, bytes)) => (offered.clone(), ClipboardContent::Bytes(bytes.clone())),
1488 None => (ReceivedMime::from(mime), ClipboardContent::Empty),
1491 };
1492 ShellEvent::ClipboardData {
1493 window,
1494 request,
1495 mime,
1496 content,
1497 }
1498 }
1499
1500 fn resolve_reads(&mut self) {
1507 if self.reads.is_empty() {
1508 return;
1509 }
1510 let answerable = self.answerable();
1511 let mut held = Vec::with_capacity(self.reads.len());
1512 for mut read in core::mem::take(&mut self.reads) {
1513 if self.window(read.window).is_err() {
1517 continue;
1518 }
1519 if answerable {
1520 let answer = self.answer(read.window, read.request, read.mime);
1521 self.queue.push_back(answer);
1522 continue;
1523 }
1524 if read.countdown > 0 {
1525 read.countdown -= 1;
1526 held.push(read);
1527 continue;
1528 }
1529 self.queue.push_back(ShellEvent::ClipboardData {
1532 window: read.window,
1533 request: read.request,
1534 mime: ReceivedMime::from(read.mime),
1535 content: ClipboardContent::Unavailable,
1536 });
1537 }
1538 self.reads = held;
1539 }
1540
1541 fn deliver_due_configures(&mut self) {
1548 let mut due: Vec<(WindowId, PendingConfigure, Option<f64>)> = Vec::new();
1552 for (handle, state) in self.windows.iter_mut() {
1553 let Some(pending) = state.pending.as_mut() else {
1554 continue;
1555 };
1556 if pending.countdown > 0 {
1557 pending.countdown -= 1;
1558 continue;
1559 }
1560 let pending = state.pending.take().expect("checked just above");
1561 let previous_scale = state.configuration.map(|config| config.scale_factor);
1562 state.configuration = Some(WindowConfiguration {
1563 size: pending.size,
1564 scale_factor: pending.scale_factor,
1565 mode: pending.mode,
1566 });
1567 due.push((handle.cast(), pending, previous_scale));
1568 }
1569
1570 for (window, pending, previous_scale) in due {
1571 if previous_scale.is_some_and(|previous| previous != pending.scale_factor) {
1575 self.queue.push_back(ShellEvent::ScaleFactorChanged {
1576 window,
1577 scale_factor: pending.scale_factor,
1578 size: pending.size,
1579 });
1580 }
1581 self.queue.push_back(ShellEvent::Resized {
1582 window,
1583 size: pending.size,
1584 scale_factor: pending.scale_factor,
1585 });
1586 }
1587 }
1588
1589 fn run_due_scripts(&mut self) {
1591 if self.scripts.is_empty() {
1592 return;
1593 }
1594 let mut due = Vec::new();
1595 for mut scheduled in core::mem::take(&mut self.scripts) {
1596 if scheduled.countdown > 0 {
1597 scheduled.countdown -= 1;
1598 self.scripts.push(scheduled);
1599 } else {
1600 due.push(scheduled.script);
1601 }
1602 }
1603 for script in due {
1604 script(self);
1605 }
1606 }
1607
1608 fn window(&self, window: WindowId) -> Result<&HeadlessWindow, ShellError> {
1609 self.windows
1610 .get(window.cast())
1611 .ok_or_else(|| ShellError::invalid_window(window))
1612 }
1613
1614 fn window_mut(&mut self, window: WindowId) -> Result<&mut HeadlessWindow, ShellError> {
1615 self.windows
1616 .get_mut(window.cast())
1617 .ok_or_else(|| ShellError::invalid_window(window))
1618 }
1619
1620 fn check_window(&self, window: WindowId) -> Result<(), ShellError> {
1621 self.window(window).map(|_| ())
1622 }
1623
1624 fn unsupported(&self, what: &'static str) -> ShellError {
1625 ShellError::Unsupported {
1626 backend: ShellBackend::Headless,
1627 what,
1628 }
1629 }
1630}
1631
1632fn synthetic_scancode(key: KeyCode) -> Scancode {
1636 let index = KeyCode::ALL
1637 .iter()
1638 .position(|candidate| *candidate == key)
1639 .unwrap_or(0);
1640 Scancode(index as u32 + 8)
1643}
1644
1645fn synthetic_keysym(key: KeyCode) -> Keysym {
1647 let name = key.as_str();
1648 if let Some(letter) = name.strip_prefix("Key") {
1649 return Keysym::from_char(letter.to_ascii_lowercase().chars().next().unwrap_or('?'));
1651 }
1652 if let Some(digit) = name.strip_prefix("Digit") {
1653 return Keysym::from_char(digit.chars().next().unwrap_or('?'));
1654 }
1655 match key {
1656 KeyCode::Space => Keysym::from_char(' '),
1657 KeyCode::Minus => Keysym::from_char('-'),
1658 KeyCode::Equal => Keysym::from_char('='),
1659 KeyCode::Comma => Keysym::from_char(','),
1660 KeyCode::Period => Keysym::from_char('.'),
1661 KeyCode::Slash => Keysym::from_char('/'),
1662 KeyCode::Semicolon => Keysym::from_char(';'),
1663 KeyCode::Quote => Keysym::from_char('\''),
1664 KeyCode::Backslash => Keysym::from_char('\\'),
1665 KeyCode::BracketLeft => Keysym::from_char('['),
1666 KeyCode::BracketRight => Keysym::from_char(']'),
1667 KeyCode::Backquote => Keysym::from_char('`'),
1668 _ => crate::keysym::named_keysym(key).unwrap_or(Keysym::NONE),
1672 }
1673}
1674
1675impl Shell for HeadlessShell {
1676 fn backend(&self) -> ShellBackend {
1677 ShellBackend::Headless
1678 }
1679
1680 fn caps(&self) -> ShellCaps {
1681 self.caps
1682 }
1683
1684 fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError> {
1685 crate::role::check(desc, self.caps(), self.backend(), |monitor| {
1686 self.monitor(monitor).is_some()
1687 })?;
1688 if !self.windows.is_empty() && !self.caps.contains(ShellCaps::MULTI_WINDOW) {
1689 return Err(self.unsupported("a second window"));
1690 }
1691 if let DisplayMode::Borderless {
1692 monitor: Some(monitor),
1693 } = desc.mode
1694 && self.monitor(monitor).is_none()
1695 {
1696 return Err(ShellError::NoSuchMonitor(monitor.0));
1697 }
1698
1699 let (size, scale_factor) = match desc.mode {
1711 DisplayMode::Windowed => {
1712 let scale_factor = self.monitors[0].scale_factor;
1713 (
1714 desc.constraints
1715 .apply(desc.size.to_physical(scale_factor), scale_factor),
1716 scale_factor,
1717 )
1718 }
1719 DisplayMode::Borderless { monitor } => {
1720 let monitor = monitor
1721 .and_then(|id| self.monitor(id))
1722 .unwrap_or(&self.monitors[0]);
1723 (monitor.size(), monitor.scale_factor)
1724 }
1725 };
1726
1727 let (parent, popup_input, panel) = match desc.role {
1728 crate::WindowRole::Popup(popup) => {
1729 self.window(popup.parent)?;
1730 (Some(popup.parent), Some(popup.input), None)
1731 }
1732 crate::WindowRole::Panel(panel) => {
1733 (None, None, Some(crate::role::KeptPanel::new(&panel)))
1734 }
1735 crate::WindowRole::Toplevel => (None, None, None),
1736 };
1737 let countdown = self.configure_delay;
1738 let window: WindowId = self
1739 .windows
1740 .insert(HeadlessWindow {
1741 title: desc.title.to_string(),
1742 configuration: None,
1745 pending: Some(PendingConfigure {
1746 size,
1747 scale_factor,
1748 mode: desc.mode,
1749 countdown,
1750 }),
1751 requested_mode: desc.mode,
1752 requested_constraints: desc.constraints,
1753 focused: false,
1754 visible: desc.visible,
1755 pointer_mode: PointerMode::Free,
1756 cursor: Some(CursorIcon::Default),
1757 close_pending: false,
1758 accept_drops: desc.accept_drops,
1759 parent,
1760 popup_input,
1761 panel,
1762 text_input: None,
1763 text_input_area: None,
1764 input_region: None,
1765 idle_inhibit: false,
1766 #[cfg(feature = "accesskit")]
1767 accessibility: None,
1768 })
1769 .cast();
1770 Ok(window)
1771 }
1772
1773 fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError> {
1777 self.window(window)?;
1778 let popups: Vec<WindowId> = self
1779 .windows
1780 .iter()
1781 .filter(|(_, state)| state.parent == Some(window))
1782 .map(|(id, _)| id.cast())
1783 .collect();
1784 for popup in popups {
1785 self.destroy_window(popup)?;
1786 }
1787 self.windows
1788 .remove(window.cast())
1789 .ok_or_else(|| ShellError::invalid_window(window))?;
1790 self.queue.push_back(ShellEvent::WindowDestroyed { window });
1791 Ok(())
1792 }
1793
1794 fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError> {
1795 let state = self.window(window)?;
1796 Ok(WindowState {
1797 configuration: state.configuration,
1798 requested_mode: state.requested_mode,
1799 requested_constraints: state.requested_constraints,
1800 focused: state.focused,
1801 visible: state.visible,
1802 pointer_mode: state.pointer_mode,
1803 close_pending: state.close_pending,
1804 })
1805 }
1806
1807 fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError> {
1808 self.window_mut(window)?.title = title.to_string();
1809 Ok(())
1810 }
1811
1812 fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError> {
1813 self.window_mut(window)?.visible = visible;
1814 Ok(())
1815 }
1816
1817 fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError> {
1818 let target = match mode {
1819 DisplayMode::Windowed => None,
1820 DisplayMode::Borderless { monitor } => {
1821 let monitor = match monitor {
1822 Some(id) => self
1823 .monitor(id)
1824 .ok_or(ShellError::NoSuchMonitor(id.0))?
1825 .clone(),
1826 None => self.monitors[0].clone(),
1827 };
1828 Some(monitor)
1829 }
1830 };
1831 let countdown = self.configure_delay;
1832
1833 let state = self.window_mut(window)?;
1834 state.requested_mode = mode;
1840 let (size, scale_factor) = match &target {
1841 Some(monitor) => (monitor.size(), monitor.scale_factor),
1842 None => (state.base_size(), state.scale_factor()),
1846 };
1847 state.pending = Some(PendingConfigure {
1848 size,
1849 scale_factor,
1850 mode,
1851 countdown,
1852 });
1853 Ok(())
1854 }
1855
1856 fn set_constraints(
1857 &mut self,
1858 window: WindowId,
1859 constraints: SizeConstraints,
1860 ) -> Result<(), ShellError> {
1861 let countdown = self.configure_delay;
1862 let state = self.window_mut(window)?;
1863 state.requested_constraints = constraints;
1864
1865 if let Some(pending) = state.pending.as_mut() {
1872 pending.size = constraints.apply(pending.size, pending.scale_factor);
1873 return Ok(());
1874 }
1875
1876 if let Some(config) = state.configuration {
1880 let constrained = constraints.apply(config.size, config.scale_factor);
1881 if constrained != config.size {
1882 state.pending = Some(PendingConfigure {
1883 size: constrained,
1884 scale_factor: config.scale_factor,
1885 mode: config.mode,
1886 countdown,
1887 });
1888 }
1889 }
1890 Ok(())
1891 }
1892
1893 fn reposition_popup(
1897 &mut self,
1898 popup: WindowId,
1899 anchor: LogicalRect,
1900 size: LogicalSize,
1901 ) -> Result<(), ShellError> {
1902 let _ = anchor;
1903 let countdown = self.configure_delay;
1904 let state = self.window_mut(popup)?;
1905 if state.parent.is_none() {
1906 return Err(crate::role::not_a_popup(popup));
1907 }
1908 state.configure_at(size, countdown);
1909 Ok(())
1910 }
1911
1912 fn set_panel(
1916 &mut self,
1917 window: WindowId,
1918 size: LogicalSize,
1919 panel: &crate::PanelDesc<'_>,
1920 ) -> Result<(), ShellError> {
1921 let was = self.window(window)?.panel.as_ref().map(|kept| kept.desc());
1922 crate::role::check_set_panel(window, was, panel, self.caps, self.backend(), |monitor| {
1923 self.monitor(monitor).is_some()
1924 })?;
1925 let countdown = self.configure_delay;
1926 let state = self.window_mut(window)?;
1927 state.panel = Some(crate::role::KeptPanel::new(panel));
1928 state.configure_at(size, countdown);
1929 Ok(())
1930 }
1931
1932 fn monitors(&self) -> &[MonitorInfo] {
1933 &self.monitors
1934 }
1935
1936 fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent)) {
1937 self.keep_alive();
1938 if self.outputs_powered {
1939 let windows = &self.windows;
1940 self.queue.extend(
1941 self.frames
1942 .take_due(|window| windows.contains(window.cast())),
1943 );
1944 }
1945 for _ in 0..self.queue.len() {
1950 let Some(event) = self.queue.pop_front() else {
1951 break;
1952 };
1953 sink(event);
1954 }
1955 }
1956
1957 fn keep_alive(&mut self) {
1966 self.deliver_due_configures();
1967 self.resolve_reads();
1968 self.run_due_scripts();
1969 }
1970
1971 fn wait_events(&mut self, timeout: Option<Duration>) {
1992 self.waits += 1;
1993 if !self.caps.contains(ShellCaps::EVENT_WAIT)
1994 || !self.queue.is_empty()
1995 || !self.scripts.is_empty()
1996 || (self.outputs_powered && self.frames.is_pending())
1997 {
1998 return;
1999 }
2000 match (&self.wake, timeout) {
2001 (Some(wake), timeout) => wake.wait(timeout),
2002 (None, Some(timeout)) => std::thread::sleep(timeout),
2003 (None, None) => {}
2004 }
2005 }
2006
2007 fn waker(&mut self) -> Option<ShellWaker> {
2010 let wake = self.wake.get_or_insert_with(Arc::default);
2011 Some(ShellWaker::new(Arc::clone(wake) as Arc<dyn WakeSignal>))
2012 }
2013
2014 fn align_event_clock(&mut self, elapsed: Duration) {
2021 self.set_time(elapsed);
2022 }
2023
2024 fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError> {
2025 self.window(window)?;
2031 Ok(SurfaceTarget::Offscreen)
2032 }
2033
2034 fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError> {
2035 if !self.caps.contains(mode.required_cap()) {
2036 return Err(self.unsupported(mode.as_str()));
2037 }
2038 self.window_mut(window)?.pointer_mode = mode;
2039 Ok(())
2040 }
2041
2042 fn set_text_input(
2046 &mut self,
2047 window: WindowId,
2048 field: Option<TextPurpose>,
2049 ) -> Result<(), ShellError> {
2050 self.window_mut(window)?.text_input = field;
2051 Ok(())
2052 }
2053
2054 fn set_text_input_area(
2058 &mut self,
2059 window: WindowId,
2060 area: Option<PhysicalRect>,
2061 ) -> Result<(), ShellError> {
2062 self.window_mut(window)?.text_input_area = area;
2063 Ok(())
2064 }
2065
2066 fn set_input_region(
2071 &mut self,
2072 window: WindowId,
2073 region: Option<&[PhysicalRect]>,
2074 ) -> Result<(), ShellError> {
2075 self.window_mut(window)?.input_region = region.map(<[PhysicalRect]>::to_vec);
2076 Ok(())
2077 }
2078
2079 fn set_idle_inhibit(&mut self, window: WindowId, inhibit: bool) -> Result<(), ShellError> {
2084 if !self.caps.contains(ShellCaps::IDLE_INHIBIT) {
2085 return Err(self.unsupported("idle inhibit"));
2086 }
2087 self.window_mut(window)?.idle_inhibit = inhibit;
2088 Ok(())
2089 }
2090
2091 fn open_url(&mut self, window: WindowId, url: &WebUrl) -> Result<(), ShellError> {
2096 if !self.caps.contains(ShellCaps::OPEN_URL) {
2097 return Err(self.unsupported("opening a URL"));
2098 }
2099 self.check_window(window)?;
2100 self.opened_urls.push((window, url.clone()));
2101 Ok(())
2102 }
2103
2104 fn request_frame(&mut self, window: WindowId) -> Result<(), ShellError> {
2109 self.window(window)?;
2110 self.frames.request(window);
2111 Ok(())
2112 }
2113
2114 #[cfg(feature = "accesskit")]
2115 fn update_accessibility(
2116 &mut self,
2117 window: WindowId,
2118 update: accesskit::TreeUpdate,
2119 ) -> Result<(), ShellError> {
2120 if let Some(updates) = &mut self.window_mut(window)?.accessibility {
2121 updates.push(update);
2122 }
2123 Ok(())
2124 }
2125
2126 fn set_cursor(
2127 &mut self,
2128 window: WindowId,
2129 cursor: Option<CursorIcon>,
2130 ) -> Result<(), ShellError> {
2131 self.window_mut(window)?.cursor = cursor;
2132 Ok(())
2133 }
2134
2135 fn warp_pointer(
2136 &mut self,
2137 window: WindowId,
2138 position: PhysicalPoint,
2139 ) -> Result<(), ShellError> {
2140 if !self.caps.contains(ShellCaps::POINTER_WARP) {
2141 return Err(self.unsupported("pointer warp"));
2142 }
2143 self.check_window(window)?;
2144 let event = ShellEvent::PointerMotion {
2147 window,
2148 device: VIRTUAL_DEVICE,
2149 time: self.now(),
2150 abs: Some(position),
2151 raw_delta: None,
2152 };
2153 self.queue.push_back(event);
2154 Ok(())
2155 }
2156
2157 fn reply_close_request(
2158 &mut self,
2159 window: WindowId,
2160 reply: CloseReply,
2161 ) -> Result<(), ShellError> {
2162 let state = self.window_mut(window)?;
2163 if !state.close_pending {
2164 return Err(ShellError::NoPendingCloseRequest { window });
2165 }
2166 state.close_pending = false;
2167 match reply {
2168 CloseReply::Close => self.destroy_window(window),
2169 CloseReply::Keep => Ok(()),
2170 }
2171 }
2172
2173 fn clipboard_offer(
2184 &mut self,
2185 window: WindowId,
2186 offers: &[ClipboardOffer<'_>],
2187 ) -> Result<(), ShellError> {
2188 if !self.caps.contains(ShellCaps::CLIPBOARD) {
2189 return Err(self.unsupported("clipboard"));
2190 }
2191 self.check_window(window)?;
2192 if self.clipboard_needs_interaction && !self.saw_interaction {
2193 return Err(ShellError::NeedsUserInteraction {
2194 backend: ShellBackend::Headless,
2195 what: "claiming the clipboard",
2196 });
2197 }
2198 self.clipboard = offers
2199 .iter()
2200 .map(|offer| (ReceivedMime::from(offer.mime), offer.bytes.to_vec()))
2201 .collect();
2202 Ok(())
2203 }
2204
2205 fn clipboard_request(
2219 &mut self,
2220 window: WindowId,
2221 mime: MimeType,
2222 ) -> Result<ClipboardRequestId, ShellError> {
2223 if !self.caps.contains(ShellCaps::CLIPBOARD) {
2224 return Err(self.unsupported("clipboard"));
2225 }
2226 self.check_window(window)?;
2227 let request = ClipboardRequestId(self.next_request_id);
2228 self.next_request_id += 1;
2229 if self.answerable() {
2230 let answer = self.answer(window, request, mime);
2231 self.queue.push_back(answer);
2235 } else {
2236 self.reads.push(PendingRead {
2237 window,
2238 request,
2239 mime,
2240 countdown: self.clipboard_deadline,
2241 });
2242 }
2243 Ok(request)
2244 }
2245
2246 fn clipboard_readable(&self, window: WindowId) -> bool {
2252 self.caps.contains(ShellCaps::CLIPBOARD) && self.window(window).is_ok() && self.answerable()
2253 }
2254}
2255
2256#[cfg(test)]
2257mod tests {
2258 use super::*;
2259 use crate::{AspectRatio, LogicalSize};
2260
2261 fn shell_with_window() -> (HeadlessShell, WindowId) {
2263 let mut shell = HeadlessShell::new();
2264 let window = shell
2265 .create_window(&WindowDesc::default())
2266 .expect("headless window creation never fails");
2267 (shell, window)
2268 }
2269
2270 fn shell_with_configured_window() -> (HeadlessShell, WindowId) {
2272 let (mut shell, window) = shell_with_window();
2273 settle(&mut shell);
2274 assert!(shell.window_state(window).expect("state").is_configured());
2275 (shell, window)
2276 }
2277
2278 fn settle(shell: &mut HeadlessShell) {
2280 for _ in 0..8 {
2281 let mut seen = 0;
2282 shell.pump(&mut |_| seen += 1);
2283 if seen == 0 && shell.windows.iter().all(|(_, w)| w.pending.is_none()) {
2284 return;
2285 }
2286 }
2287 panic!("the shell never settled");
2288 }
2289
2290 fn drain(shell: &mut HeadlessShell) -> Vec<ShellEvent> {
2291 let mut events = Vec::new();
2292 shell.pump(&mut |event| events.push(event));
2293 events
2294 }
2295
2296 fn names(events: &[ShellEvent]) -> Vec<&'static str> {
2297 events.iter().map(ShellEvent::name).collect()
2298 }
2299
2300 fn create_swapchain(state: &WindowState) -> Result<PhysicalSize, &'static str> {
2303 let size = state.size().ok_or("window is not configured yet")?;
2304 if size.is_empty() {
2305 return Err("zero-extent swapchain");
2306 }
2307 Ok(size)
2308 }
2309
2310 #[test]
2315 fn a_backend_without_activation_answers_none() {
2316 let (mut shell, window) = shell_with_window();
2317 assert_eq!(shell.activation_token(window).expect("a live window"), None);
2318 shell.destroy_window(window).expect("destroy");
2319 assert!(matches!(
2320 shell.activation_token(window),
2321 Err(ShellError::InvalidWindow { .. })
2322 ));
2323 }
2324
2325 #[cfg(feature = "accesskit")]
2330 #[test]
2331 fn a_tree_reaches_the_reader_only_while_it_reads() {
2332 use accesskit::{Action, ActionRequest, Node, NodeId, Role, TreeId, TreeInfo, TreeUpdate};
2333
2334 let (mut shell, window) = shell_with_configured_window();
2335 let update = |label: &str| TreeUpdate {
2336 nodes: vec![(NodeId(1), {
2337 let mut node = Node::new(Role::Window);
2338 node.set_label(label);
2339 node
2340 })],
2341 tree: Some(TreeInfo::new(NodeId(1))),
2342 tree_id: TreeId::ROOT,
2343 focus: NodeId(1),
2344 };
2345
2346 shell
2347 .update_accessibility(window, update("unread"))
2348 .expect("update");
2349 assert_eq!(shell.accessibility_updates(window).expect("updates"), None);
2350
2351 shell.activate_accessibility(window).expect("activate");
2352 shell
2353 .activate_accessibility(window)
2354 .expect("activate twice");
2355 shell
2356 .update_accessibility(window, update("read"))
2357 .expect("update");
2358 let click = ActionRequest {
2359 action: Action::Click,
2360 target_tree: TreeId::ROOT,
2361 target_node: NodeId(1),
2362 data: None,
2363 };
2364 shell
2365 .request_accessibility_action(window, click.clone())
2366 .expect("action");
2367 assert_eq!(
2368 shell.accessibility_updates(window).expect("updates"),
2369 Some(&[update("read")][..])
2370 );
2371 let events = drain(&mut shell);
2372 assert_eq!(
2373 names(&events),
2374 ["AccessibilityActivated", "AccessibilityAction"]
2375 );
2376 assert_eq!(
2377 events[1],
2378 ShellEvent::AccessibilityAction {
2379 window,
2380 request: click
2381 }
2382 );
2383
2384 shell.deactivate_accessibility(window).expect("deactivate");
2385 shell
2386 .deactivate_accessibility(window)
2387 .expect("deactivate twice");
2388 shell
2389 .update_accessibility(window, update("gone"))
2390 .expect("update");
2391 assert_eq!(shell.accessibility_updates(window).expect("updates"), None);
2392 assert_eq!(names(&drain(&mut shell)), ["AccessibilityDeactivated"]);
2393 }
2394
2395 #[test]
2398 fn a_new_window_has_no_size_until_a_later_pump() {
2399 let (mut shell, window) = shell_with_window();
2400
2401 let state = shell.window_state(window).expect("state");
2404 assert!(!state.is_configured());
2405 assert_eq!(state.size(), None);
2406 assert_eq!(state.scale_factor(), None);
2407 assert_eq!(state.effective_mode(), None);
2408 assert_eq!(state.requested_mode, DisplayMode::Windowed);
2409
2410 assert_eq!(drain(&mut shell), Vec::new());
2412 assert!(!shell.window_state(window).expect("state").is_configured());
2413
2414 let events = drain(&mut shell);
2416 assert_eq!(
2417 events,
2418 vec![ShellEvent::Resized {
2419 window,
2420 size: PhysicalSize::new(1280, 720),
2421 scale_factor: 1.0,
2422 }]
2423 );
2424 let state = shell.window_state(window).expect("state");
2425 assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2426 assert_eq!(state.scale_factor(), Some(1.0));
2427 assert_eq!(state.effective_mode(), Some(DisplayMode::Windowed));
2428 assert!(state.mode_request_honoured());
2429 }
2430
2431 #[test]
2435 fn keep_alive_takes_a_turn_and_keeps_everything_for_the_next_pump() {
2436 let (mut shell, window) = shell_with_window();
2437 shell.inject(ShellEvent::CloseRequested { window });
2438
2439 for _ in 0..=DEFAULT_CONFIGURE_DELAY {
2441 shell.keep_alive();
2442 }
2443 assert!(
2444 shell.window_state(window).expect("state").is_configured(),
2445 "every turn the configure waits for was taken by keep_alive"
2446 );
2447
2448 assert_eq!(
2449 drain(&mut shell),
2450 vec![
2451 ShellEvent::CloseRequested { window },
2452 ShellEvent::Resized {
2453 window,
2454 size: PhysicalSize::new(1280, 720),
2455 scale_factor: 1.0,
2456 },
2457 ],
2458 "nothing keep_alive saw was delivered or dropped"
2459 );
2460 assert_eq!(drain(&mut shell), Vec::new(), "and each arrived once");
2461 }
2462
2463 #[test]
2464 fn a_consumer_that_skips_the_wait_gets_a_clean_error_not_a_wrong_extent() {
2465 let (mut shell, window) = shell_with_window();
2466
2467 assert_eq!(
2469 create_swapchain(&shell.window_state(window).expect("state")),
2470 Err("window is not configured yet")
2471 );
2472
2473 let target = shell.surface_target(window).expect("the handle exists");
2479 assert_eq!(target, SurfaceTarget::Offscreen);
2480
2481 let size = loop {
2483 shell.pump(&mut |_| {});
2484 if let Ok(size) = create_swapchain(&shell.window_state(window).expect("state")) {
2485 break size;
2486 }
2487 };
2488 assert_eq!(size, PhysicalSize::new(1280, 720));
2489 assert_eq!(
2492 shell.surface_target(window).expect("target"),
2493 target,
2494 "the target is invariant under a configure"
2495 );
2496 }
2497
2498 #[test]
2499 fn the_configure_delay_is_a_knob() {
2500 let mut shell = HeadlessShell::new().with_configure_delay(3);
2501 let window = shell.create_window(&WindowDesc::default()).expect("window");
2502 for pump in 0..3 {
2503 assert_eq!(drain(&mut shell), Vec::new(), "pump {pump}");
2504 assert!(!shell.window_state(window).expect("state").is_configured());
2505 }
2506 assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2507 assert!(shell.window_state(window).expect("state").is_configured());
2508
2509 let mut shell = HeadlessShell::new().with_configure_delay(0);
2512 let window = shell.create_window(&WindowDesc::default()).expect("window");
2513 assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2514 assert!(shell.window_state(window).expect("state").is_configured());
2515
2516 shell.set_configure_delay(2);
2517 shell
2518 .set_mode(window, DisplayMode::Borderless { monitor: None })
2519 .expect("request");
2520 assert_eq!(drain(&mut shell), Vec::new());
2521 assert_eq!(drain(&mut shell), Vec::new());
2522 assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2523 }
2524
2525 #[test]
2526 fn set_mode_is_a_request_whose_effect_arrives_later() {
2527 let (mut shell, window) = shell_with_configured_window();
2528 shell
2529 .set_mode(window, DisplayMode::Borderless { monitor: None })
2530 .expect("request");
2531
2532 let state = shell.window_state(window).expect("state");
2534 assert_eq!(
2535 state.requested_mode,
2536 DisplayMode::Borderless { monitor: None }
2537 );
2538 assert_eq!(
2539 state.effective_mode(),
2540 Some(DisplayMode::Windowed),
2541 "still windowed until the window system says otherwise"
2542 );
2543 assert!(
2544 !state.mode_request_honoured(),
2545 "a UI toggle reading the request instead of the effect would lie here"
2546 );
2547 assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2548
2549 settle(&mut shell);
2550 let state = shell.window_state(window).expect("state");
2551 assert_eq!(
2552 state.effective_mode(),
2553 Some(DisplayMode::Borderless { monitor: None })
2554 );
2555 assert!(state.mode_request_honoured());
2556 assert_eq!(state.size(), Some(PhysicalSize::new(1920, 1080)));
2557 }
2558
2559 #[test]
2560 fn a_refused_mode_is_expressible_through_injection() {
2561 let (mut shell, window) = shell_with_configured_window();
2564 shell
2565 .set_mode(window, DisplayMode::Borderless { monitor: None })
2566 .expect("request");
2567 shell
2569 .resize(window, PhysicalSize::new(1280, 720))
2570 .expect("answer");
2571 let state = shell.window_state(window).expect("state");
2572 assert_eq!(state.effective_mode(), Some(DisplayMode::Windowed));
2573 assert!(!state.mode_request_honoured());
2574 }
2575
2576 #[test]
2582 fn a_reconfigured_panel_is_configured_at_its_new_size() {
2583 let mut shell = HeadlessShell::new();
2584 let monitor = shell.monitors()[0].id;
2585 let bar = crate::PanelDesc {
2586 namespace: "bar",
2587 monitor: Some(monitor),
2588 anchor: crate::PanelAnchor::TOP | crate::PanelAnchor::LEFT | crate::PanelAnchor::RIGHT,
2589 reserve: crate::Reserve::OwnExtent,
2590 ..crate::PanelDesc::default()
2591 };
2592 let window = shell
2593 .create_window(&WindowDesc {
2594 size: LogicalSize::new(400.0, 30.0),
2595 role: crate::WindowRole::Panel(bar),
2596 ..WindowDesc::default()
2597 })
2598 .expect("a panel");
2599 settle(&mut shell);
2600 let scale = shell
2601 .window_state(window)
2602 .expect("live")
2603 .scale_factor()
2604 .expect("configured");
2605
2606 let taller = crate::PanelDesc {
2607 layer: crate::PanelLayer::Overlay,
2608 margins: crate::Margins {
2609 top: 4.0,
2610 ..crate::Margins::default()
2611 },
2612 keyboard: crate::PanelKeyboard::OnDemand,
2613 ..bar
2614 };
2615 let size = LogicalSize::new(400.0, 50.0);
2616 shell.set_panel(window, size, &taller).expect("set_panel");
2617 assert_eq!(shell.panel(window).expect("live"), Some(taller));
2618 assert_eq!(
2619 shell.window_state(window).expect("live").size(),
2620 Some(LogicalSize::new(400.0, 30.0).to_physical(scale)),
2621 "a request: nothing changes before the window system answers"
2622 );
2623 let mut resized = Vec::new();
2624 for _ in 0..8 {
2625 resized.extend(
2626 drain(&mut shell)
2627 .into_iter()
2628 .filter_map(|event| match event {
2629 ShellEvent::Resized {
2630 window: of, size, ..
2631 } if of == window => Some(size),
2632 _ => None,
2633 }),
2634 );
2635 }
2636 assert_eq!(resized, [size.to_physical(scale)]);
2637
2638 let refused = |shell: &mut HeadlessShell, panel: &crate::PanelDesc<'_>| match shell
2639 .set_panel(window, LogicalSize::new(1.0, 1.0), panel)
2640 {
2641 Err(ShellError::InvalidDescriptor(message)) => message,
2642 other => panic!("expected InvalidDescriptor, got {other:?}"),
2643 };
2644 let renamed = crate::PanelDesc {
2645 namespace: "dock",
2646 ..taller
2647 };
2648 assert!(refused(&mut shell, &renamed).contains("namespace"));
2649 let anywhere = crate::PanelDesc {
2650 monitor: None,
2651 ..taller
2652 };
2653 assert!(refused(&mut shell, &anywhere).contains("monitor"));
2654 let toplevel = shell
2655 .create_window(&WindowDesc::default())
2656 .expect("a toplevel");
2657 assert!(matches!(
2658 shell.set_panel(toplevel, size, &taller),
2659 Err(ShellError::InvalidDescriptor(message)) if message.contains("not a panel")
2660 ));
2661 let cornered = crate::PanelDesc {
2662 anchor: crate::PanelAnchor::TOP | crate::PanelAnchor::LEFT,
2663 ..taller
2664 };
2665 assert!(matches!(
2666 shell.set_panel(window, size, &cornered),
2667 Err(ShellError::Unsupported { .. })
2668 ));
2669 assert_eq!(
2670 shell.panel(window).expect("live"),
2671 Some(taller),
2672 "a refused descriptor is not recorded"
2673 );
2674 assert_eq!(shell.panel(toplevel).expect("live"), None);
2675
2676 shell.destroy_window(window).expect("destroy");
2677 assert!(matches!(
2678 shell.set_panel(window, size, &taller),
2679 Err(ShellError::InvalidWindow { .. })
2680 ));
2681 }
2682
2683 #[test]
2686 fn a_repositioned_popup_is_configured_at_its_new_size() {
2687 let (mut shell, window) = shell_with_configured_window();
2688 let anchor = crate::LogicalRect::new(
2689 crate::LogicalPoint::new(10.0, 10.0),
2690 LogicalSize::new(100.0, 20.0),
2691 );
2692 let popup = shell
2693 .create_window(&WindowDesc {
2694 size: LogicalSize::new(200.0, 150.0),
2695 role: crate::WindowRole::Popup(crate::PopupDesc {
2696 parent: window,
2697 anchor,
2698 placement: crate::PopupPlacement::Below,
2699 input: crate::PopupInput::Pointer,
2700 }),
2701 ..WindowDesc::default()
2702 })
2703 .expect("a popup");
2704 settle(&mut shell);
2705 let scale = shell
2706 .window_state(popup)
2707 .expect("live")
2708 .scale_factor()
2709 .expect("configured");
2710
2711 let moved = LogicalSize::new(240.0, 90.0);
2712 shell
2713 .reposition_popup(popup, anchor, moved)
2714 .expect("reposition");
2715 settle(&mut shell);
2716 assert_eq!(
2717 shell.window_state(popup).expect("live").size(),
2718 Some(moved.to_physical(scale))
2719 );
2720 assert!(matches!(
2721 shell.reposition_popup(window, anchor, moved),
2722 Err(ShellError::InvalidDescriptor(_))
2723 ));
2724 }
2725
2726 #[test]
2730 fn escape_on_a_grabbing_popup_is_delivered_then_asks_it_to_close() {
2731 let (mut shell, window) = shell_with_configured_window();
2732 let popup_of = |shell: &mut HeadlessShell, input| {
2733 shell
2734 .create_window(&WindowDesc {
2735 role: crate::WindowRole::Popup(crate::PopupDesc {
2736 parent: window,
2737 anchor: crate::LogicalRect::default(),
2738 placement: crate::PopupPlacement::Below,
2739 input,
2740 }),
2741 ..WindowDesc::default()
2742 })
2743 .expect("a popup")
2744 };
2745 let menu = popup_of(&mut shell, crate::PopupInput::Grab);
2746 let tooltip = popup_of(&mut shell, crate::PopupInput::Pointer);
2747 settle(&mut shell);
2748 let is_close = |event: &ShellEvent| matches!(event, ShellEvent::CloseRequested { .. });
2749
2750 shell.key_press(menu, KeyCode::Escape).expect("press");
2751 let events = drain(&mut shell);
2752 assert!(
2753 matches!(
2754 events.as_slice(),
2755 [
2756 ShellEvent::Key {
2757 key_code: Some(KeyCode::Escape),
2758 ..
2759 },
2760 ShellEvent::CloseRequested { window: closed },
2761 ] if *closed == menu
2762 ),
2763 "the key, then the request: {events:?}"
2764 );
2765 shell.key_press(menu, KeyCode::Escape).expect("press");
2767 shell.key_repeat(menu, KeyCode::Escape).expect("repeat");
2768 assert!(!drain(&mut shell).iter().any(is_close));
2769
2770 shell
2772 .reply_close_request(menu, CloseReply::Keep)
2773 .expect("keep");
2774 shell.key_release(menu, KeyCode::Escape).expect("release");
2775 shell.key_press(menu, KeyCode::Enter).expect("press");
2776 assert!(!drain(&mut shell).iter().any(is_close), "not these");
2777 shell.key_press(menu, KeyCode::Escape).expect("press");
2778 assert!(drain(&mut shell).iter().any(is_close));
2779
2780 shell.key_press(tooltip, KeyCode::Escape).expect("press");
2781 shell.key_press(window, KeyCode::Escape).expect("press");
2782 assert!(!drain(&mut shell).iter().any(is_close));
2783 }
2784
2785 #[test]
2786 fn set_constraints_is_a_request_too() {
2787 let (mut shell, window) = shell_with_configured_window();
2788 let constraints = SizeConstraints::min(LogicalSize::new(1600.0, 900.0));
2789 shell.set_constraints(window, constraints).expect("request");
2790
2791 let state = shell.window_state(window).expect("state");
2792 assert_eq!(state.requested_constraints, constraints);
2793 assert_eq!(
2794 state.size(),
2795 Some(PhysicalSize::new(1280, 720)),
2796 "the size only changes when the window system says so"
2797 );
2798
2799 settle(&mut shell);
2800 assert_eq!(
2801 shell.window_state(window).expect("state").size(),
2802 Some(PhysicalSize::new(1600, 900))
2803 );
2804 }
2805
2806 #[test]
2807 fn constraints_do_not_cancel_a_mode_request_that_has_not_landed() {
2808 let (mut shell, window) = shell_with_configured_window();
2813 shell
2814 .set_mode(window, DisplayMode::Borderless { monitor: None })
2815 .expect("mode request");
2816 shell
2817 .set_constraints(window, SizeConstraints::min(LogicalSize::new(320.0, 180.0)))
2818 .expect("constraint request");
2819 settle(&mut shell);
2820
2821 let state = shell.window_state(window).expect("state");
2822 assert_eq!(
2823 state.effective_mode(),
2824 Some(DisplayMode::Borderless { monitor: None })
2825 );
2826 assert!(state.mode_request_honoured());
2827 }
2828
2829 #[test]
2830 fn a_borderless_window_reports_its_own_monitors_scale() {
2831 let mut shell = HeadlessShell::new();
2836 let hidpi = shell.plug_monitor(MonitorInfo {
2837 id: MonitorId(0),
2838 name: "HEADLESS-2".to_string(),
2839 connector: None,
2840 bounds: PhysicalRect::new(1920, 0, 2560, 1440),
2841 work_area: PhysicalRect::new(1920, 0, 2560, 1440),
2842 scale_factor: 2.0,
2843 refresh_millihertz: 143_998,
2844 is_primary: false,
2845 });
2846 let window = shell
2847 .create_window(&WindowDesc {
2848 mode: DisplayMode::Borderless {
2849 monitor: Some(hidpi),
2850 },
2851 ..WindowDesc::default()
2852 })
2853 .expect("window");
2854 settle(&mut shell);
2855
2856 let state = shell.window_state(window).expect("state");
2857 assert_eq!(state.size(), Some(PhysicalSize::new(2560, 1440)));
2858 assert_eq!(
2859 state.scale_factor(),
2860 Some(2.0),
2861 "the scale is the borderless monitor's, not the primary's"
2862 );
2863 let other = shell
2866 .create_window(&WindowDesc::default())
2867 .expect("second window");
2868 settle(&mut shell);
2869 shell
2870 .set_mode(
2871 other,
2872 DisplayMode::Borderless {
2873 monitor: Some(hidpi),
2874 },
2875 )
2876 .expect("request");
2877 settle(&mut shell);
2878 assert_eq!(
2879 shell.window_state(other).expect("state").scale_factor(),
2880 shell.window_state(window).expect("state").scale_factor()
2881 );
2882 }
2883
2884 #[test]
2885 fn constraints_set_before_the_first_configure_fold_into_it() {
2886 let mut shell = HeadlessShell::new();
2887 let window = shell.create_window(&WindowDesc::default()).expect("window");
2888 shell
2889 .set_constraints(
2890 window,
2891 SizeConstraints::NONE.with_aspect(AspectRatio::SQUARE),
2892 )
2893 .expect("request");
2894 settle(&mut shell);
2895 assert_eq!(
2898 shell.window_state(window).expect("state").size(),
2899 Some(PhysicalSize::new(720, 720))
2900 );
2901 }
2902
2903 #[test]
2904 fn creation_uses_the_requested_size_and_the_monitors_scale() {
2905 let mut shell = HeadlessShell::new();
2906 let window = shell
2907 .create_window(&WindowDesc {
2908 size: LogicalSize::new(800.0, 600.0),
2909 ..WindowDesc::default()
2910 })
2911 .expect("window");
2912 settle(&mut shell);
2913 assert_eq!(
2914 shell.window_state(window).expect("state").size(),
2915 Some(PhysicalSize::new(800, 600))
2916 );
2917
2918 let mut shell = HeadlessShell::new().with_scale_factor(2.0);
2919 let window = shell
2920 .create_window(&WindowDesc {
2921 size: LogicalSize::new(640.0, 360.0),
2922 ..WindowDesc::default()
2923 })
2924 .expect("window");
2925 settle(&mut shell);
2926 let state = shell.window_state(window).expect("state");
2927 assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2928 assert_eq!(state.scale_factor(), Some(2.0));
2929 }
2930
2931 #[test]
2934 fn scale_changes_preserve_logical_size_and_report_both_facts() {
2935 let (mut shell, window) = shell_with_configured_window();
2936 shell
2937 .change_scale_factor(window, 1.5)
2938 .expect("scale change");
2939 let events = drain(&mut shell);
2940 assert_eq!(
2941 events,
2942 vec![
2943 ShellEvent::ScaleFactorChanged {
2944 window,
2945 scale_factor: 1.5,
2946 size: PhysicalSize::new(1920, 1080),
2947 },
2948 ShellEvent::Resized {
2951 window,
2952 size: PhysicalSize::new(1920, 1080),
2953 scale_factor: 1.5,
2954 },
2955 ]
2956 );
2957 assert_eq!(
2961 shell.window_state(window).expect("state").size(),
2962 Some(PhysicalSize::new(1920, 1080))
2963 );
2964 }
2965
2966 #[test]
2967 fn a_scale_change_scheduled_by_a_mode_switch_arrives_before_the_resize() {
2968 let mut shell = HeadlessShell::new();
2969 let hidpi = shell.plug_monitor(MonitorInfo {
2970 id: MonitorId(0),
2971 name: "HEADLESS-2".to_string(),
2972 connector: None,
2973 bounds: PhysicalRect::new(1920, 0, 2560, 1440),
2974 work_area: PhysicalRect::new(1920, 0, 2560, 1440),
2975 scale_factor: 2.0,
2976 refresh_millihertz: 143_998,
2977 is_primary: false,
2978 });
2979 assert_eq!(hidpi, MonitorId(2), "ids are never reused");
2980 let window = shell.create_window(&WindowDesc::default()).expect("window");
2981 settle(&mut shell);
2982
2983 shell
2984 .set_mode(
2985 window,
2986 DisplayMode::Borderless {
2987 monitor: Some(hidpi),
2988 },
2989 )
2990 .expect("request");
2991 assert_eq!(drain(&mut shell), Vec::new(), "still only a request");
2992 let events = drain(&mut shell);
2993 assert_eq!(names(&events), ["ScaleFactorChanged", "Resized"]);
2994
2995 let state = shell.window_state(window).expect("state");
2996 assert_eq!(state.size(), Some(PhysicalSize::new(2560, 1440)));
2997 assert_eq!(state.scale_factor(), Some(2.0));
2998 assert!(state.effective_mode().expect("configured").is_borderless());
2999 assert_eq!(
3004 shell.surface_target(window).expect("target"),
3005 SurfaceTarget::Offscreen
3006 );
3007
3008 assert!(matches!(
3009 shell.set_mode(
3010 window,
3011 DisplayMode::Borderless {
3012 monitor: Some(MonitorId(99)),
3013 },
3014 ),
3015 Err(ShellError::NoSuchMonitor(99))
3016 ));
3017 }
3018
3019 #[test]
3020 fn resizes_honour_constraints_and_inject_bypasses_them() {
3021 let (mut shell, window) = shell_with_configured_window();
3022 shell
3023 .set_constraints(
3024 window,
3025 SizeConstraints::min(LogicalSize::new(640.0, 360.0))
3026 .with_aspect(AspectRatio::WIDESCREEN),
3027 )
3028 .expect("request");
3029 settle(&mut shell);
3030
3031 shell
3032 .resize(window, PhysicalSize::new(1000, 1000))
3033 .expect("resize");
3034 assert_eq!(
3035 drain(&mut shell),
3036 vec![ShellEvent::Resized {
3037 window,
3038 size: PhysicalSize::new(1000, 562),
3039 scale_factor: 1.0,
3040 }]
3041 );
3042
3043 shell.inject(ShellEvent::Resized {
3046 window,
3047 size: PhysicalSize::new(300, 900),
3048 scale_factor: 1.0,
3049 });
3050 assert_eq!(
3051 drain(&mut shell)[0],
3052 ShellEvent::Resized {
3053 window,
3054 size: PhysicalSize::new(300, 900),
3055 scale_factor: 1.0,
3056 }
3057 );
3058 }
3059
3060 #[test]
3061 fn a_compositor_configure_supersedes_a_pending_one() {
3062 let (mut shell, window) = shell_with_configured_window();
3063 shell
3064 .set_mode(window, DisplayMode::Borderless { monitor: None })
3065 .expect("request");
3066 shell
3068 .resize(window, PhysicalSize::new(640, 480))
3069 .expect("answer");
3070 assert_eq!(names(&drain(&mut shell)), ["Resized"]);
3071 assert_eq!(
3072 shell.window_state(window).expect("state").size(),
3073 Some(PhysicalSize::new(640, 480))
3074 );
3075 assert_eq!(drain(&mut shell), Vec::new());
3077 }
3078
3079 #[test]
3082 fn timestamps_come_from_the_shells_clock_not_from_the_pump() {
3083 let (mut shell, window) = shell_with_configured_window();
3084 shell.set_time(Duration::from_secs(2));
3085 shell.key_press(window, KeyCode::Space).expect("press");
3086 shell.advance(Duration::from_millis(180));
3087 shell.key_release(window, KeyCode::Space).expect("release");
3088
3089 let events = drain(&mut shell);
3090 let held = events[1]
3091 .time()
3092 .expect("input")
3093 .saturating_since(events[0].time().expect("input"));
3094 assert_eq!(held, Duration::from_millis(180));
3095 assert_eq!(events[0].time(), Some(EventTime::from_millis(2_000)));
3096 }
3097
3098 #[test]
3101 fn a_scheduled_script_injects_at_its_pump_with_that_pumps_time() {
3102 let (mut shell, window) = shell_with_configured_window();
3103 shell.schedule(2, move |shell| {
3104 shell.key_press(window, KeyCode::Space).expect("press");
3105 });
3106
3107 for pump in 0..2 {
3108 shell.advance(Duration::from_millis(16));
3109 assert_eq!(drain(&mut shell), Vec::new(), "pump {pump} came early");
3110 }
3111 shell.set_time(Duration::from_secs(3));
3112 let events = drain(&mut shell);
3113 assert_eq!(names(&events), ["Key"]);
3114 assert_eq!(events[0].time(), Some(EventTime::from_millis(3_000)));
3115 assert_eq!(drain(&mut shell), Vec::new(), "and it ran once");
3116 }
3117
3118 #[test]
3121 fn scheduled_scripts_run_in_order_and_a_nested_one_waits_a_pump() {
3122 let (mut shell, window) = shell_with_configured_window();
3123 shell.schedule(0, move |shell| {
3124 shell.key_press(window, KeyCode::KeyA).expect("press");
3125 shell.schedule(0, move |shell| {
3126 shell.key_press(window, KeyCode::KeyC).expect("press");
3127 });
3128 });
3129 shell.schedule(0, move |shell| {
3130 shell.key_press(window, KeyCode::KeyB).expect("press");
3131 });
3132
3133 let keys = |events: Vec<ShellEvent>| -> Vec<Option<KeyCode>> {
3134 events
3135 .into_iter()
3136 .map(|event| match event {
3137 ShellEvent::Key { key_code, .. } => key_code,
3138 other => panic!("not a key: {other:?}"),
3139 })
3140 .collect()
3141 };
3142 assert_eq!(
3143 keys(drain(&mut shell)),
3144 [Some(KeyCode::KeyA), Some(KeyCode::KeyB)]
3145 );
3146 assert_eq!(keys(drain(&mut shell)), [Some(KeyCode::KeyC)]);
3147 }
3148
3149 #[test]
3152 fn keep_alive_runs_a_due_script_and_keeps_its_events() {
3153 let (mut shell, window) = shell_with_configured_window();
3154 shell.schedule(1, move |shell| {
3155 shell.key_press(window, KeyCode::Enter).expect("press");
3156 });
3157 shell.keep_alive();
3158 shell.keep_alive();
3159 assert_eq!(shell.pending_events(), 1, "the script ran in keep_alive");
3160 assert_eq!(names(&drain(&mut shell)), ["Key"]);
3161 }
3162
3163 #[test]
3167 fn a_wait_does_not_sleep_while_a_script_is_scheduled() {
3168 let (mut shell, window) = shell_with_configured_window();
3169 shell.schedule(1, move |shell| {
3170 shell.key_press(window, KeyCode::Space).expect("press");
3171 });
3172 let start = std::time::Instant::now();
3173 shell.wait_events(Some(LONG_WAIT));
3174 assert!(
3175 start.elapsed() < LONG_WAIT / 2,
3176 "the wait slept {:?}",
3177 start.elapsed()
3178 );
3179 }
3180
3181 #[test]
3182 fn synthesized_key_fields_are_stable_and_plausible() {
3183 let (mut shell, window) = shell_with_configured_window();
3184 shell.set_modifiers(Modifiers::CTRL);
3185 shell.key_press(window, KeyCode::KeyS).expect("press");
3186 let events = drain(&mut shell);
3187 let ShellEvent::Key {
3188 scancode,
3189 key_code,
3190 keysym,
3191 modifiers,
3192 repeat,
3193 device,
3194 ..
3195 } = events[0].clone()
3196 else {
3197 panic!("wrong variant");
3198 };
3199 assert_eq!(key_code, Some(KeyCode::KeyS));
3200 assert_eq!(keysym, Keysym::from_char('s'));
3201 assert_eq!(modifiers, Modifiers::CTRL);
3202 assert!(!repeat);
3203 assert_eq!(device, VIRTUAL_DEVICE);
3204 assert!(scancode.0 >= 8, "evdev-shaped scancodes start at 8");
3205 assert_eq!(synthetic_keysym(KeyCode::Digit7), Keysym::from_char('7'));
3206 assert_eq!(synthetic_keysym(KeyCode::F5), Keysym(0xFFC2));
3207 assert_eq!(synthetic_keysym(KeyCode::Enter), Keysym(0xFF0D));
3208 assert_eq!(synthetic_keysym(KeyCode::Escape), Keysym(0xFF1B));
3209 assert_eq!(synthetic_keysym(KeyCode::ArrowLeft), Keysym(0xFF51));
3210 assert_eq!(synthetic_keysym(KeyCode::Slash), Keysym::from_char('/'));
3211
3212 shell.key_repeat(window, KeyCode::KeyS).expect("repeat");
3213 let events = drain(&mut shell);
3214 let ShellEvent::Key { repeat, .. } = events[0] else {
3215 panic!("wrong variant");
3216 };
3217 assert!(repeat);
3218 }
3219
3220 #[test]
3221 fn a_locked_pointer_reports_no_absolute_position() {
3222 let (mut shell, window) = shell_with_configured_window();
3223 shell
3224 .set_pointer_mode(window, PointerMode::Locked)
3225 .expect("lock");
3226 shell
3227 .move_pointer(window, PhysicalPoint::new(10.0, 10.0), (3.0, -4.0))
3228 .expect("motion");
3229 let events = drain(&mut shell);
3230 let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3231 panic!("wrong variant");
3232 };
3233 assert_eq!(abs, None);
3234 assert_eq!(raw_delta, Some((3.0, -4.0)));
3235 }
3236
3237 #[test]
3238 fn a_backend_without_raw_motion_reports_none() {
3239 let mut shell = HeadlessShell::new()
3240 .with_caps(ShellCaps::DESKTOP - ShellCaps::RAW_POINTER_MOTION)
3241 .with_configure_delay(0);
3242 let window = shell.create_window(&WindowDesc::default()).expect("window");
3243 drain(&mut shell);
3244 shell
3245 .move_pointer(window, PhysicalPoint::new(1.0, 2.0), (5.0, 5.0))
3246 .expect("motion");
3247 let events = drain(&mut shell);
3248 let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3249 panic!("wrong variant");
3250 };
3251 assert_eq!(abs, Some(PhysicalPoint::new(1.0, 2.0)));
3252 assert_eq!(raw_delta, None, "no relative-motion source");
3253 assert!(!shell.caps().has_mouselook());
3254 }
3255
3256 #[test]
3257 fn pointer_focus_and_scroll_and_text_are_injectable() {
3258 let (mut shell, window) = shell_with_configured_window();
3259 shell
3260 .set_pointer_focus(window, true, Some(PhysicalPoint::new(1.0, 1.0)))
3261 .expect("enter");
3262 shell
3263 .scroll(window, ScrollDelta::Lines { x: 0.0, y: -1.0 }, None)
3264 .expect("scroll");
3265 shell
3266 .button(
3267 window,
3268 PointerButton::Left,
3269 ButtonState::Pressed,
3270 Some(PhysicalPoint::new(1.0, 1.0)),
3271 )
3272 .expect("click");
3273 shell.commit_text(window, "ありがとう").expect("text");
3274 shell
3275 .set_pointer_focus(window, false, Some(PhysicalPoint::new(1.0, 1.0)))
3276 .expect("leave");
3277
3278 let events = drain(&mut shell);
3279 assert_eq!(
3280 names(&events),
3281 [
3282 "PointerFocus",
3283 "Wheel",
3284 "Button",
3285 "TextCommit",
3286 "PointerFocus"
3287 ]
3288 );
3289 let ShellEvent::PointerFocus {
3290 entered, position, ..
3291 } = &events[4]
3292 else {
3293 panic!("wrong variant");
3294 };
3295 assert!(!entered);
3296 assert_eq!(*position, None, "a leave has no position");
3297 assert!(events.iter().all(ShellEvent::is_input));
3298 }
3299
3300 #[test]
3307 fn contacts_are_injectable_and_a_touchless_shell_refuses_them() {
3308 let (mut shell, window) = shell_with_configured_window();
3309 assert!(shell.caps().contains(ShellCaps::TOUCH));
3310 for (contact, phase, x) in [
3311 (1, TouchPhase::Began, 10.0),
3312 (2, TouchPhase::Began, 200.0),
3313 (2, TouchPhase::Moved, 220.0),
3314 (1, TouchPhase::Ended, 10.0),
3315 (2, TouchPhase::Cancelled, 220.0),
3316 ] {
3317 shell
3318 .touch(
3319 window,
3320 ContactId(contact),
3321 phase,
3322 PhysicalPoint::new(x, 5.0),
3323 )
3324 .expect("a contact");
3325 }
3326 let events = drain(&mut shell);
3327 assert_eq!(names(&events), ["Touch"; 5]);
3328 let seen: Vec<(ContactId, TouchPhase, f64)> = events
3329 .iter()
3330 .map(|event| {
3331 let ShellEvent::Touch {
3332 contact,
3333 phase,
3334 position,
3335 ..
3336 } = event
3337 else {
3338 panic!("wrong variant");
3339 };
3340 (*contact, *phase, position.x)
3341 })
3342 .collect();
3343 assert_eq!(
3344 seen,
3345 vec![
3346 (ContactId(1), TouchPhase::Began, 10.0),
3347 (ContactId(2), TouchPhase::Began, 200.0),
3348 (ContactId(2), TouchPhase::Moved, 220.0),
3349 (ContactId(1), TouchPhase::Ended, 10.0),
3350 (ContactId(2), TouchPhase::Cancelled, 220.0),
3351 ]
3352 );
3353 assert!(events.iter().all(ShellEvent::is_input));
3354
3355 let mut touchless = HeadlessShell::new()
3356 .with_caps(ShellCaps::DESKTOP - ShellCaps::TOUCH)
3357 .with_configure_delay(0);
3358 let window = touchless
3359 .create_window(&WindowDesc::default())
3360 .expect("window");
3361 drain(&mut touchless);
3362 assert!(matches!(
3363 touchless.touch(
3364 window,
3365 ContactId(1),
3366 TouchPhase::Began,
3367 PhysicalPoint::ORIGIN
3368 ),
3369 Err(ShellError::Unsupported { .. })
3370 ));
3371 assert!(drain(&mut touchless).is_empty(), "and queued nothing");
3372 }
3373
3374 #[test]
3375 fn warping_produces_motion_like_every_platform_that_has_it() {
3376 let (mut shell, window) = shell_with_configured_window();
3377 shell
3378 .warp_pointer(window, PhysicalPoint::new(320.0, 180.0))
3379 .expect("warp");
3380 let events = drain(&mut shell);
3381 let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3382 panic!("wrong variant");
3383 };
3384 assert_eq!(abs, Some(PhysicalPoint::new(320.0, 180.0)));
3385 assert_eq!(raw_delta, None, "a warp is not physical motion");
3386 }
3387
3388 #[test]
3391 fn capabilities_gate_the_operations_that_need_them() {
3392 let mut shell = HeadlessShell::new().with_caps(ShellCaps::empty());
3393 let window = shell.create_window(&WindowDesc::default()).expect("window");
3394
3395 assert!(matches!(
3396 shell.warp_pointer(window, PhysicalPoint::ORIGIN),
3397 Err(ShellError::Unsupported { .. })
3398 ));
3399 assert!(matches!(
3400 shell.set_pointer_mode(window, PointerMode::Locked),
3401 Err(ShellError::Unsupported { .. })
3402 ));
3403 assert!(matches!(
3404 shell.clipboard_request(window, MimeType::TextUtf8),
3405 Err(ShellError::Unsupported { .. })
3406 ));
3407 shell
3409 .set_pointer_mode(window, PointerMode::Free)
3410 .expect("Free is always available");
3411 assert!(matches!(
3413 shell.create_window(&WindowDesc::default()),
3414 Err(ShellError::Unsupported { .. })
3415 ));
3416 }
3417
3418 #[test]
3419 fn stale_handles_fail_cleanly_on_every_accessor() {
3420 let (mut shell, window) = shell_with_configured_window();
3421 shell.destroy_window(window).expect("destroy");
3422 assert_eq!(
3423 drain(&mut shell),
3424 vec![ShellEvent::WindowDestroyed { window }]
3425 );
3426
3427 assert!(matches!(
3428 shell.window_state(window),
3429 Err(ShellError::InvalidWindow { .. })
3430 ));
3431 assert!(matches!(
3432 shell.surface_target(window),
3433 Err(ShellError::InvalidWindow { .. })
3434 ));
3435 assert!(matches!(
3436 shell.resize(window, PhysicalSize::new(1, 1)),
3437 Err(ShellError::InvalidWindow { .. })
3438 ));
3439 assert!(matches!(
3440 shell.set_title(window, "gone"),
3441 Err(ShellError::InvalidWindow { .. })
3442 ));
3443 assert!(matches!(
3444 shell.destroy_window(window),
3445 Err(ShellError::InvalidWindow { .. })
3446 ));
3447 assert!(matches!(
3448 shell.key_press(window, KeyCode::KeyA),
3449 Err(ShellError::InvalidWindow { .. })
3450 ));
3451 }
3452
3453 #[test]
3454 fn destroying_a_window_cancels_its_pending_configure() {
3455 let (mut shell, window) = shell_with_window();
3458 shell.destroy_window(window).expect("destroy");
3459 assert_eq!(names(&drain(&mut shell)), ["WindowDestroyed"]);
3460 assert_eq!(drain(&mut shell), Vec::new());
3461 assert_eq!(drain(&mut shell), Vec::new());
3462 }
3463
3464 #[test]
3465 fn close_requests_are_questions() {
3466 let (mut shell, window) = shell_with_configured_window();
3467 assert!(matches!(
3468 shell.reply_close_request(window, CloseReply::Close),
3469 Err(ShellError::NoPendingCloseRequest { .. })
3470 ));
3471
3472 shell.request_close(window).expect("request");
3473 assert!(shell.window_state(window).expect("state").close_pending);
3474 shell
3475 .reply_close_request(window, CloseReply::Keep)
3476 .expect("keep");
3477 assert!(!shell.window_state(window).expect("state").close_pending);
3478 assert!(shell.window_state(window).is_ok(), "still open");
3479
3480 shell.request_close(window).expect("request again");
3481 shell
3482 .reply_close_request(window, CloseReply::Close)
3483 .expect("close");
3484 assert!(matches!(
3485 shell.window_state(window),
3486 Err(ShellError::InvalidWindow { .. })
3487 ));
3488 }
3489
3490 #[test]
3491 fn monitor_hotplug_reports_a_change_and_keeps_ids_unique() {
3492 let mut shell = HeadlessShell::new();
3493 let extra = shell.plug_monitor(MonitorInfo {
3494 id: MonitorId(0),
3495 name: "HEADLESS-2".to_string(),
3496 connector: None,
3497 bounds: PhysicalRect::new(1920, 0, 1920, 1080),
3498 work_area: PhysicalRect::new(1920, 0, 1920, 1080),
3499 scale_factor: 1.0,
3500 refresh_millihertz: 60_000,
3501 is_primary: false,
3502 });
3503 assert_eq!(shell.monitors().len(), 2);
3504 assert_eq!(drain(&mut shell), vec![ShellEvent::MonitorsChanged]);
3505
3506 shell.unplug_monitor(extra).expect("unplug");
3507 assert_eq!(shell.monitors().len(), 1);
3508 assert_eq!(
3509 drain(&mut shell),
3510 vec![
3511 ShellEvent::MonitorRemoved { monitor: extra },
3512 ShellEvent::MonitorsChanged
3513 ]
3514 );
3515 assert!(matches!(
3516 shell.unplug_monitor(extra),
3517 Err(ShellError::NoSuchMonitor(_))
3518 ));
3519 assert_eq!(
3520 shell.monitor(MonitorId(1)).map(|m| m.name.as_str()),
3521 Some("HEADLESS-1")
3522 );
3523 assert!(shell.monitor(extra).is_none());
3524 }
3525
3526 #[test]
3527 fn unplugging_a_monitor_asks_its_panels_and_only_its_panels_to_close() {
3528 let mut shell = HeadlessShell::new();
3529 let second = shell.plug_monitor(MonitorInfo {
3530 id: MonitorId(0),
3531 name: "HEADLESS-2".to_string(),
3532 connector: None,
3533 bounds: PhysicalRect::new(1920, 0, 1920, 1080),
3534 work_area: PhysicalRect::new(1920, 0, 1920, 1080),
3535 scale_factor: 1.0,
3536 refresh_millihertz: 60_000,
3537 is_primary: false,
3538 });
3539 let first = shell.monitors()[0].id;
3540 let panel_on = |shell: &mut HeadlessShell, monitor| {
3541 shell
3542 .create_window(&WindowDesc {
3543 role: crate::WindowRole::Panel(crate::PanelDesc {
3544 monitor,
3545 ..crate::PanelDesc::default()
3546 }),
3547 ..WindowDesc::default()
3548 })
3549 .expect("panel")
3550 };
3551 let doomed = panel_on(&mut shell, Some(second));
3552 let already_asked = panel_on(&mut shell, Some(second));
3553 let elsewhere = panel_on(&mut shell, Some(first));
3554 let anywhere = panel_on(&mut shell, None);
3555 let toplevel = shell.create_window(&WindowDesc::default()).expect("window");
3556 shell.request_close(already_asked).expect("close");
3557 settle(&mut shell);
3558 drain(&mut shell);
3559
3560 shell.unplug_monitor(second).expect("unplug");
3561 assert_eq!(
3562 drain(&mut shell),
3563 vec![
3564 ShellEvent::MonitorRemoved { monitor: second },
3565 ShellEvent::CloseRequested { window: doomed },
3566 ShellEvent::MonitorsChanged,
3567 ]
3568 );
3569 for window in [elsewhere, anywhere, toplevel] {
3570 assert!(!shell.window_state(window).expect("open").close_pending);
3571 }
3572 }
3573
3574 #[test]
3575 fn drops_require_both_the_capability_and_the_opt_in() {
3576 let mut shell = HeadlessShell::new();
3577 let plain = shell.create_window(&WindowDesc::default()).expect("window");
3578 assert!(matches!(
3579 shell.drop_file(plain, "/tmp/a.gltf", None),
3580 Err(ShellError::Unsupported { .. })
3581 ));
3582
3583 let dropper = shell
3584 .create_window(&WindowDesc {
3585 accept_drops: true,
3586 ..WindowDesc::default()
3587 })
3588 .expect("window");
3589 settle(&mut shell);
3590 shell
3591 .drop_file(dropper, "/tmp/a.gltf", Some(PhysicalPoint::new(4.0, 5.0)))
3592 .expect("drop");
3593 assert_eq!(names(&drain(&mut shell))[0], "DroppedFile");
3594 }
3595
3596 #[test]
3597 fn a_sink_that_queues_more_events_does_not_spin_the_pump() {
3598 let (mut shell, window) = shell_with_configured_window();
3599 shell.inject(ShellEvent::MonitorsChanged);
3600 let mut extra = Vec::new();
3601 shell.pump(&mut |event| extra.push(event));
3602 assert_eq!(extra.len(), 1);
3603 shell.inject(ShellEvent::CloseRequested { window });
3604 assert_eq!(shell.pending_events(), 1);
3605 }
3606
3607 #[test]
3608 fn accessors_that_no_real_backend_can_provide_are_headless_only() {
3609 let (mut shell, window) = shell_with_configured_window();
3610 shell.set_title(window, "renamed").expect("title");
3611 assert_eq!(shell.title(window).expect("title"), "renamed");
3612 shell.set_cursor(window, None).expect("hide");
3613 assert_eq!(shell.cursor(window).expect("cursor"), None);
3614 shell
3615 .set_cursor(window, Some(CursorIcon::Crosshair))
3616 .expect("shape");
3617 assert_eq!(
3618 shell.cursor(window).expect("cursor"),
3619 Some(CursorIcon::Crosshair)
3620 );
3621 shell.set_visible(window, false).expect("hide window");
3622 assert!(!shell.window_state(window).expect("state").visible);
3623 }
3624
3625 #[test]
3626 fn an_input_region_is_recorded_replaced_and_given_back() {
3627 let (mut shell, window) = shell_with_configured_window();
3628 assert_eq!(shell.input_region(window).expect("region"), None);
3629 let panel = PhysicalRect::new(0, 0, 400, 300).rounded(12);
3630 shell
3631 .set_input_region(window, Some(&panel))
3632 .expect("a region");
3633 assert_eq!(
3634 shell.input_region(window).expect("region"),
3635 Some(panel.as_slice())
3636 );
3637 shell.set_input_region(window, Some(&[])).expect("nothing");
3638 assert_eq!(shell.input_region(window).expect("region"), Some(&[][..]));
3639 shell.set_input_region(window, None).expect("whole window");
3640 assert_eq!(shell.input_region(window).expect("region"), None);
3641 shell.destroy_window(window).expect("destroy");
3642 assert!(matches!(
3643 shell.set_input_region(window, None),
3644 Err(ShellError::InvalidWindow { .. })
3645 ));
3646 assert!(shell.input_region(window).is_err());
3647 }
3648
3649 #[test]
3650 fn an_idle_inhibit_is_recorded_and_ends_with_its_window() {
3651 let (mut shell, window) = shell_with_configured_window();
3652 assert!(!shell.idle_inhibited(window).expect("live"));
3653 shell.set_idle_inhibit(window, true).expect("inhibit");
3654 shell.set_idle_inhibit(window, true).expect("asking twice");
3655 assert!(shell.idle_inhibited(window).expect("live"));
3656 shell.set_idle_inhibit(window, false).expect("stop");
3657 assert!(!shell.idle_inhibited(window).expect("live"));
3658 shell.set_idle_inhibit(window, true).expect("inhibit again");
3659 shell.destroy_window(window).expect("destroy");
3660 assert!(matches!(
3661 shell.set_idle_inhibit(window, false),
3662 Err(ShellError::InvalidWindow { .. })
3663 ));
3664 assert!(shell.idle_inhibited(window).is_err());
3665 }
3666
3667 #[test]
3668 fn an_idle_inhibit_is_refused_without_the_capability() {
3669 let mut shell =
3670 HeadlessShell::new().with_caps(ShellCaps::DESKTOP - ShellCaps::IDLE_INHIBIT);
3671 let window = shell.create_window(&WindowDesc::default()).expect("window");
3672 assert!(matches!(
3673 shell.set_idle_inhibit(window, true),
3674 Err(ShellError::Unsupported {
3675 backend: ShellBackend::Headless,
3676 ..
3677 })
3678 ));
3679 assert!(!shell.idle_inhibited(window).expect("live"));
3680 }
3681
3682 fn url(text: &str) -> WebUrl {
3683 WebUrl::parse(text).expect("a web URL")
3684 }
3685
3686 #[test]
3687 fn an_opened_url_is_recorded_in_order() {
3688 let (mut shell, window) = shell_with_configured_window();
3689 let other = shell.create_window(&WindowDesc::default()).expect("window");
3690 assert!(shell.opened_urls().is_empty());
3691 let store = url("https://store.example/app/1");
3692 let privacy = url("HTTPS://EXAMPLE.COM/privacy");
3693 shell.open_url(window, &store).expect("store page");
3694 shell.open_url(other, &privacy).expect("privacy policy");
3695 shell
3696 .open_url(window, &store)
3697 .expect("asking twice opens twice");
3698 assert_eq!(
3699 shell.opened_urls(),
3700 [
3701 (window, store.clone()),
3702 (other, privacy),
3703 (window, store.clone())
3704 ]
3705 );
3706 shell.destroy_window(window).expect("destroy");
3707 assert!(matches!(
3708 shell.open_url(window, &store),
3709 Err(ShellError::InvalidWindow { .. })
3710 ));
3711 assert_eq!(
3712 shell.opened_urls().len(),
3713 3,
3714 "the history outlives the window"
3715 );
3716 }
3717
3718 #[test]
3719 fn opening_a_url_is_refused_without_the_capability() {
3720 let mut shell = HeadlessShell::new().with_caps(ShellCaps::DESKTOP - ShellCaps::OPEN_URL);
3721 let window = shell.create_window(&WindowDesc::default()).expect("window");
3722 assert!(matches!(
3723 shell.open_url(window, &url("https://example.com/")),
3724 Err(ShellError::Unsupported {
3725 backend: ShellBackend::Headless,
3726 ..
3727 })
3728 ));
3729 assert!(shell.opened_urls().is_empty());
3730 }
3731
3732 fn frames_for(events: &[ShellEvent], window: WindowId) -> usize {
3733 events
3734 .iter()
3735 .filter(|event| matches!(event, ShellEvent::FrameReady { window: w } if *w == window))
3736 .count()
3737 }
3738
3739 #[test]
3740 fn requests_for_a_frame_share_one_answer_at_the_next_pump() {
3741 let (mut shell, window) = shell_with_configured_window();
3742 assert!(!shell.frame_requested(window).expect("live"));
3743 shell.request_frame(window).expect("a frame");
3744 shell.request_frame(window).expect("the same frame");
3745 assert!(shell.frame_requested(window).expect("live"));
3746 let events = drain(&mut shell);
3747 assert_eq!(frames_for(&events, window), 1, "{:?}", names(&events));
3748 assert!(!shell.frame_requested(window).expect("live"));
3749 assert_eq!(
3750 frames_for(&drain(&mut shell), window),
3751 0,
3752 "nothing asked again"
3753 );
3754 shell.request_frame(window).expect("the next frame");
3755 assert_eq!(frames_for(&drain(&mut shell), window), 1);
3756 }
3757
3758 #[test]
3759 fn a_window_destroyed_with_a_frame_requested_is_not_answered() {
3760 let (mut shell, doomed) = shell_with_configured_window();
3761 let kept = shell
3762 .create_window(&WindowDesc::default())
3763 .expect("a second window");
3764 settle(&mut shell);
3765 shell.request_frame(doomed).expect("a frame");
3766 shell.request_frame(kept).expect("a frame");
3767 shell.destroy_window(doomed).expect("destroy");
3768 let events = drain(&mut shell);
3769 assert_eq!(frames_for(&events, doomed), 0, "{:?}", names(&events));
3770 assert_eq!(frames_for(&events, kept), 1, "the other window still asked");
3771 assert!(matches!(
3772 shell.request_frame(doomed),
3773 Err(ShellError::InvalidWindow { .. })
3774 ));
3775 assert!(shell.frame_requested(doomed).is_err());
3776 }
3777
3778 #[test]
3779 fn a_wait_does_not_sleep_through_a_frame_that_is_due() {
3780 let (mut shell, window) = shell_with_configured_window();
3781 shell.request_frame(window).expect("a frame");
3782 let start = std::time::Instant::now();
3783 shell.wait_events(Some(LONG_WAIT));
3784 assert!(
3785 start.elapsed() < LONG_WAIT / 2,
3786 "slept {:?} with a frame due",
3787 start.elapsed()
3788 );
3789 assert_eq!(frames_for(&drain(&mut shell), window), 1);
3790 }
3791
3792 #[test]
3793 fn an_output_that_is_off_holds_frame_requests_until_it_is_on() {
3794 let (mut shell, window) = shell_with_configured_window();
3795 shell.set_outputs_powered(false);
3796 shell.request_frame(window).expect("a frame");
3797 assert_eq!(frames_for(&drain(&mut shell), window), 0, "held");
3798 assert!(shell.frame_requested(window).expect("live"), "still owed");
3799
3800 let wait = Duration::from_millis(20);
3801 let start = std::time::Instant::now();
3802 shell.wait_events(Some(wait));
3803 assert!(
3804 start.elapsed() >= wait,
3805 "a held request cut the wait short after {:?}",
3806 start.elapsed()
3807 );
3808
3809 shell.set_outputs_powered(true);
3810 assert_eq!(
3811 frames_for(&drain(&mut shell), window),
3812 1,
3813 "answered once on"
3814 );
3815 assert!(!shell.frame_requested(window).expect("live"));
3816 }
3817
3818 #[test]
3819 fn waiting_is_observable_and_focus_transitions_are_events() {
3820 let (mut shell, window) = shell_with_configured_window();
3821 assert_eq!(shell.wait_count(), 0);
3822 shell.wait_events(Some(Duration::from_millis(5)));
3823 shell.wait_events(None);
3824 assert_eq!(shell.wait_count(), 2);
3825
3826 shell.set_focus(window, true).expect("focus");
3827 assert!(shell.window_state(window).expect("state").focused);
3828 shell.set_focus(window, false).expect("unfocus");
3829 assert_eq!(names(&drain(&mut shell)), ["Focus", "Focus"]);
3830 }
3831
3832 const LONG_WAIT: Duration = Duration::from_secs(60);
3837 const RING_AFTER: Duration = Duration::from_millis(50);
3839
3840 fn ring_later(waker: ShellWaker) -> std::thread::JoinHandle<()> {
3842 std::thread::spawn(move || {
3843 std::thread::sleep(RING_AFTER);
3844 waker.wake();
3845 })
3846 }
3847
3848 #[test]
3849 fn a_wake_from_another_thread_ends_a_long_wait() {
3850 let mut shell = HeadlessShell::new();
3851 let ringer = ring_later(shell.waker().expect("headless has a waker"));
3852 let start = std::time::Instant::now();
3853 shell.wait_events(Some(LONG_WAIT));
3854 let slept = start.elapsed();
3855 ringer.join().expect("the ringer");
3856 assert!(slept < LONG_WAIT / 2, "the wait ran {slept:?}");
3857 }
3858
3859 #[test]
3860 fn a_wake_before_the_wait_ends_it_at_once_and_wakes_coalesce() {
3861 let mut shell = HeadlessShell::new();
3862 let waker = shell.waker().expect("headless has a waker");
3863 for _ in 0..3 {
3864 waker.wake();
3865 }
3866 let start = std::time::Instant::now();
3867 shell.wait_events(Some(LONG_WAIT));
3868 assert!(
3869 start.elapsed() < LONG_WAIT / 2,
3870 "a rung bell must end the wait"
3871 );
3872
3873 let timeout = Duration::from_millis(100);
3875 let start = std::time::Instant::now();
3876 shell.wait_events(Some(timeout));
3877 assert!(
3878 start.elapsed() >= timeout / 2,
3879 "the bell was cleared, so this wait must sleep, but it took {:?}",
3880 start.elapsed()
3881 );
3882 }
3883
3884 #[test]
3885 fn with_a_waker_out_an_untimed_wait_sleeps_until_it_rings() {
3886 let mut shell = HeadlessShell::new();
3887 let ringer = ring_later(shell.waker().expect("headless has a waker"));
3888 let start = std::time::Instant::now();
3889 shell.wait_events(None);
3890 let slept = start.elapsed();
3891 ringer.join().expect("the ringer");
3892 assert!(
3893 slept >= RING_AFTER / 2,
3894 "an untimed wait returned after {slept:?}, before anything rang"
3895 );
3896 }
3897
3898 #[test]
3901 fn the_clipboard_round_trips_through_an_event() {
3902 let (mut shell, window) = shell_with_configured_window();
3903 shell
3904 .clipboard_offer(
3905 window,
3906 &[
3907 ClipboardOffer::text("node"),
3908 ClipboardOffer::ron("(kind:\"node\")"),
3909 ],
3910 )
3911 .expect("offer");
3912 assert_eq!(
3913 shell.clipboard_bytes(MimeType::TextUtf8),
3914 Some(&b"node"[..])
3915 );
3916
3917 let request = shell
3918 .clipboard_request(window, MimeType::CrcblRon)
3919 .expect("request");
3920 assert_eq!(
3921 drain(&mut shell)[0],
3922 ShellEvent::ClipboardData {
3923 window,
3924 request,
3925 mime: ReceivedMime::from(MimeType::CrcblRon),
3926 content: ClipboardContent::Bytes(b"(kind:\"node\")".to_vec()),
3927 }
3928 );
3929
3930 let request = shell
3933 .clipboard_request(window, MimeType::UriList)
3934 .expect("request");
3935 assert_eq!(
3936 drain(&mut shell)[0],
3937 ShellEvent::ClipboardData {
3938 window,
3939 request,
3940 mime: ReceivedMime::from(MimeType::UriList),
3941 content: ClipboardContent::Empty,
3942 }
3943 );
3944
3945 shell
3948 .clipboard_offer(window, &[ClipboardOffer::text("")])
3949 .expect("offer");
3950 let request = shell
3951 .clipboard_request(window, MimeType::TextUtf8)
3952 .expect("request");
3953 assert_eq!(
3954 drain(&mut shell)[0],
3955 ShellEvent::ClipboardData {
3956 window,
3957 request,
3958 mime: ReceivedMime::from(MimeType::TextUtf8),
3959 content: ClipboardContent::Bytes(Vec::new()),
3960 }
3961 );
3962 }
3963
3964 #[test]
3965 fn a_read_taken_while_the_clipboard_is_unreadable_is_held_not_answered_empty() {
3966 let (mut shell, window) = shell_with_configured_window();
3972 shell
3973 .clipboard_offer(window, &[ClipboardOffer::text("published")])
3974 .expect("offer");
3975 shell.set_clipboard_readable(false);
3976 assert!(!shell.clipboard_readable(window));
3977
3978 let request = shell
3979 .clipboard_request(window, MimeType::TextUtf8)
3980 .expect("a read is accepted even when it cannot be answered yet");
3981 assert_eq!(shell.held_clipboard_reads(), 1);
3982 assert!(
3983 drain(&mut shell).is_empty(),
3984 "a held read produces no event at all — least of all an empty one"
3985 );
3986
3987 shell.set_clipboard_readable(true);
3989 let events = drain(&mut shell);
3990 assert_eq!(events.len(), 1);
3991 assert_eq!(
3992 events[0],
3993 ShellEvent::ClipboardData {
3994 window,
3995 request,
3996 mime: ReceivedMime::from(MimeType::TextUtf8),
3997 content: ClipboardContent::Bytes(b"published".to_vec()),
3998 }
3999 );
4000 assert_eq!(shell.held_clipboard_reads(), 0);
4001 }
4002
4003 #[test]
4004 fn a_read_that_never_becomes_answerable_ends_as_unavailable() {
4005 let (mut shell, window) = shell_with_configured_window();
4009 shell
4010 .clipboard_offer(window, &[ClipboardOffer::text("unreachable")])
4011 .expect("offer");
4012 shell.set_clipboard_readable(false);
4013 shell.clipboard_deadline(2);
4014
4015 let request = shell
4016 .clipboard_request(window, MimeType::TextUtf8)
4017 .expect("request");
4018 assert!(drain(&mut shell).is_empty(), "pump 1: still held");
4019 assert!(drain(&mut shell).is_empty(), "pump 2: still held");
4020 let events = drain(&mut shell);
4021 assert_eq!(
4022 events[0],
4023 ShellEvent::ClipboardData {
4024 window,
4025 request,
4026 mime: ReceivedMime::from(MimeType::TextUtf8),
4027 content: ClipboardContent::Unavailable,
4030 }
4031 );
4032 assert_eq!(shell.held_clipboard_reads(), 0);
4033 }
4034
4035 #[test]
4036 fn a_peer_that_holds_the_clipboard_and_never_delivers_is_unavailable() {
4037 let (mut shell, window) = shell_with_configured_window();
4041 shell.set_foreign_clipboard(vec![(
4042 ReceivedMime::new("text/plain"),
4043 b"never sent".to_vec(),
4044 )]);
4045 shell.set_clipboard_stalled(true);
4046 shell.clipboard_deadline(1);
4047 assert!(
4048 !shell.clipboard_readable(window),
4049 "a clipboard whose owner will not answer is not readable"
4050 );
4051
4052 let request = shell
4053 .clipboard_request(window, MimeType::TextUtf8)
4054 .expect("request");
4055 assert!(drain(&mut shell).is_empty());
4056 let events = drain(&mut shell);
4057 let ShellEvent::ClipboardData {
4058 request: answered,
4059 content,
4060 ..
4061 } = &events[0]
4062 else {
4063 panic!("wrong variant");
4064 };
4065 assert_eq!(*answered, request);
4066 assert_eq!(*content, ClipboardContent::Unavailable);
4067
4068 shell.set_clipboard_stalled(false);
4070 let request = shell
4071 .clipboard_request(window, MimeType::TextUtf8)
4072 .expect("request");
4073 assert_eq!(
4074 drain(&mut shell)[0],
4075 ShellEvent::ClipboardData {
4076 window,
4077 request,
4078 mime: ReceivedMime::new("text/plain"),
4079 content: ClipboardContent::Bytes(b"never sent".to_vec()),
4080 }
4081 );
4082 }
4083
4084 #[test]
4085 fn claiming_the_clipboard_can_require_a_user_interaction() {
4086 let (mut shell, window) = shell_with_configured_window();
4090 shell.require_user_interaction(true);
4091
4092 let refused = shell.clipboard_offer(window, &[ClipboardOffer::text("stolen")]);
4093 assert!(
4094 matches!(
4095 refused,
4096 Err(ShellError::NeedsUserInteraction {
4097 backend: ShellBackend::Headless,
4098 ..
4099 })
4100 ),
4101 "{refused:?}"
4102 );
4103 assert!(
4104 shell.clipboard_bytes(MimeType::TextUtf8).is_none(),
4105 "a refused claim must not have taken the clipboard anyway"
4106 );
4107
4108 shell.key_press(window, KeyCode::KeyC).expect("key");
4111 shell
4112 .clipboard_offer(window, &[ClipboardOffer::text("copied")])
4113 .expect("with a serial in hand, the claim goes through");
4114 assert_eq!(
4115 shell.clipboard_bytes(MimeType::TextUtf8),
4116 Some(&b"copied"[..])
4117 );
4118
4119 shell.clear_user_interaction();
4121 assert!(matches!(
4122 shell.clipboard_offer(window, &[ClipboardOffer::text("later")]),
4123 Err(ShellError::NeedsUserInteraction { .. })
4124 ));
4125 }
4126
4127 #[test]
4128 fn a_held_read_for_a_destroyed_window_is_dropped_rather_than_answered() {
4129 let (mut shell, window) = shell_with_configured_window();
4132 shell.set_clipboard_readable(false);
4133 let _request = shell
4134 .clipboard_request(window, MimeType::TextUtf8)
4135 .expect("request");
4136 assert_eq!(shell.held_clipboard_reads(), 1);
4137
4138 shell.destroy_window(window).expect("destroy");
4139 let events = drain(&mut shell);
4140 assert_eq!(shell.held_clipboard_reads(), 0);
4141 assert!(
4142 !events
4143 .iter()
4144 .any(|event| matches!(event, ShellEvent::ClipboardData { .. })),
4145 "no clipboard answer may name a destroyed window: {events:?}"
4146 );
4147 }
4148
4149 #[test]
4150 fn a_paste_from_a_foreign_application_keeps_the_foreign_spelling() {
4151 let (mut shell, window) = shell_with_configured_window();
4152 shell.set_foreign_clipboard(vec![
4153 (ReceivedMime::new("text/plain"), b"from gedit".to_vec()),
4156 (
4157 ReceivedMime::new("application/vnd.some-editor.scene+json"),
4158 b"{}".to_vec(),
4159 ),
4160 ]);
4161
4162 let request = shell
4164 .clipboard_request(window, MimeType::TextUtf8)
4165 .expect("request");
4166 let events = drain(&mut shell);
4167 let ShellEvent::ClipboardData {
4168 request: answered,
4169 mime,
4170 content,
4171 ..
4172 } = &events[0]
4173 else {
4174 panic!("wrong variant");
4175 };
4176 assert_eq!(*answered, request);
4177 assert_eq!(content.bytes(), Some(&b"from gedit"[..]));
4178 assert_eq!(mime.as_str(), "text/plain");
4180 assert!(mime.matches(MimeType::TextUtf8));
4181 assert_ne!(*mime, ReceivedMime::from(MimeType::TextUtf8));
4182
4183 assert_eq!(
4186 shell.clipboard_bytes(MimeType::Other("application/vnd.some-editor.scene+json")),
4187 Some(&b"{}"[..])
4188 );
4189 }
4190
4191 #[test]
4194 #[should_panic(expected = "a shell needs at least one monitor")]
4195 fn a_shell_with_no_monitors_is_rejected() {
4196 let _ = HeadlessShell::new().with_monitors(Vec::new());
4197 }
4198
4199 #[test]
4200 #[should_panic(expected = "a text commit is never empty")]
4201 fn an_empty_text_commit_is_rejected() {
4202 let (mut shell, window) = shell_with_configured_window();
4203 let _ = shell.commit_text(window, "");
4204 }
4205}