1use std::any::Any;
27use std::collections::HashMap;
28use std::fmt;
29use std::time::{Duration, Instant};
30
31use serde::{Deserialize, Serialize};
32
33use crate::a11y::{
34 DocumentA11yActionRequest, DocumentA11yClickTarget, DocumentA11yNodeId, DocumentA11yProjection,
35};
36use crate::{A11yCapability, DocumentCapabilities, PageCaptureOutput, PageCaptureRequest};
37
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub enum SessionError {
42 EngineNotFound(String),
43 SpawnFailed(String),
44 Unsupported(String),
45}
46
47impl fmt::Display for SessionError {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 match self {
50 Self::EngineNotFound(id) => write!(f, "session engine not registered: {id}"),
51 Self::SpawnFailed(reason) => write!(f, "session spawn failed: {reason}"),
52 Self::Unsupported(reason) => write!(f, "unsupported: {reason}"),
53 }
54 }
55}
56
57impl std::error::Error for SessionError {}
58
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
66pub struct SessionSpawnRequest {
67 pub address: String,
68 pub body: Option<String>,
71 pub content_type: Option<String>,
72 pub viewport: (u32, u32),
74 pub hidden: bool,
77}
78
79impl SessionSpawnRequest {
80 pub fn new(address: impl Into<String>) -> Self {
81 Self {
82 address: address.into(),
83 body: None,
84 content_type: None,
85 viewport: (0, 0),
86 hidden: false,
87 }
88 }
89
90 pub fn with_body(mut self, body: impl Into<String>) -> Self {
91 self.body = Some(body.into());
92 self
93 }
94
95 pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
96 self.content_type = Some(content_type.into());
97 self
98 }
99
100 pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
101 self.viewport = (width, height);
102 self
103 }
104}
105
106#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
111pub struct SessionLink {
112 pub url: String,
113 pub rect: [f32; 4],
114}
115
116#[derive(Clone, Debug, Default, PartialEq)]
124pub struct ContentReport {
125 pub title: Option<String>,
127 pub outline: Vec<OutlineEntry>,
130 pub links: Vec<String>,
132 pub headings: Vec<String>,
134 pub lineage: Option<ContentLineage>,
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct ContentLineage {
141 pub tool: String,
142 pub version: String,
143 pub selector: String,
144 pub score: Option<i32>,
145 pub block_count: usize,
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
151pub enum DocumentClipArtifactRole {
152 SourceResponse,
154 ObservedRepresentation,
157}
158
159#[derive(Clone, Debug, PartialEq, Eq)]
162pub struct DocumentClipArtifact {
163 pub role: DocumentClipArtifactRole,
164 pub media_type: String,
165 pub canonical_uri: String,
166 pub bytes: Vec<u8>,
167}
168
169#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct DocumentClip {
176 pub source_url: String,
177 pub title: Option<String>,
178 pub text: String,
179 pub selector: Option<String>,
180 pub links: Vec<String>,
181 pub artifacts: Vec<DocumentClipArtifact>,
184}
185
186#[derive(Clone, Copy, Debug, PartialEq)]
195pub struct SessionTextTarget {
196 pub anchor: [f32; 2],
197 pub focus: [f32; 2],
198}
199
200#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
202pub enum DocumentFindDirection {
203 Previous,
204 Next,
205}
206
207#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
209pub struct DocumentFindQuery {
210 pub text: String,
211 pub match_case: bool,
212}
213
214impl DocumentFindQuery {
215 pub fn new(text: impl Into<String>) -> Self {
216 Self {
217 text: text.into(),
218 match_case: false,
219 }
220 }
221}
222
223#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
225pub enum DocumentFindReveal {
226 ScrollY(f32),
229 EngineManaged,
231}
232
233#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
235pub struct DocumentFindMatch {
236 pub label: String,
238 pub role: Option<String>,
240 pub reveal: DocumentFindReveal,
241}
242
243#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
245pub struct DocumentFindState {
246 pub query: DocumentFindQuery,
247 pub count: usize,
251 pub matches: Vec<DocumentFindMatch>,
252 pub current: Option<usize>,
254 pub complete: bool,
257}
258
259impl DocumentFindState {
260 pub fn empty(query: DocumentFindQuery) -> Self {
261 Self {
262 query,
263 count: 0,
264 matches: Vec::new(),
265 current: None,
266 complete: true,
267 }
268 }
269
270 pub fn engine_managed(
274 query: DocumentFindQuery,
275 count: usize,
276 active_match: Option<usize>,
277 complete: bool,
278 ) -> Self {
279 Self {
280 query,
281 count,
282 matches: Vec::new(),
283 current: active_match.filter(|index| *index < count),
284 complete,
285 }
286 }
287
288 pub fn current_match(&self) -> Option<&DocumentFindMatch> {
289 self.current.and_then(|index| self.matches.get(index))
290 }
291}
292
293#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
301pub struct DocumentZoomState {
302 pub requested: f32,
304 pub applied: f32,
306 pub min: f32,
307 pub max: f32,
308}
309
310impl DocumentZoomState {
311 pub fn clamped(requested: f32, min: f32, max: f32) -> Self {
314 let applied = if requested.is_finite() {
317 requested.clamp(min, max)
318 } else {
319 1.0_f32.clamp(min, max)
320 };
321 Self {
322 requested,
323 applied,
324 min,
325 max,
326 }
327 }
328}
329
330#[derive(Clone, Debug, PartialEq)]
332pub struct OutlineEntry {
333 pub depth: usize,
335 pub role: &'static str,
337 pub name: String,
339}
340
341#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
344pub enum SessionClick {
345 Navigate(String),
347 Submit(String),
350 Handled,
352 Miss,
354}
355
356#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
358pub struct SessionModifiers {
359 pub shift: bool,
360 pub control: bool,
361 pub alt: bool,
362 pub meta: bool,
363}
364
365#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
367pub enum SessionPointerButton {
368 Primary,
369 Secondary,
370 Auxiliary,
371}
372
373#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
375pub enum SessionButtonState {
376 Pressed,
377 Released,
378}
379
380#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
382pub enum SessionCursor {
383 #[default]
384 Default,
385 Pointer,
386 Text,
387}
388
389#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
392pub enum SessionKey {
393 Character(String),
394 Enter,
395 Tab,
396 Backspace,
397 Delete,
398 Escape,
399 Space,
400 ArrowLeft,
401 ArrowRight,
402 ArrowUp,
403 ArrowDown,
404 Home,
405 End,
406 PageUp,
407 PageDown,
408 Unidentified,
409}
410
411#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
413pub enum SessionFocusDirection {
414 Forward,
415 Backward,
416}
417
418#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
421pub enum SessionIme {
422 Enabled,
423 Preedit {
424 text: String,
425 selection: Option<(usize, usize)>,
426 },
427 Commit(String),
428 Disabled,
429}
430
431#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
439pub enum SessionInput {
440 PointerMoved {
441 x: f32,
442 y: f32,
443 modifiers: SessionModifiers,
444 },
445 PointerButton {
446 x: f32,
447 y: f32,
448 button: SessionPointerButton,
449 state: SessionButtonState,
450 modifiers: SessionModifiers,
451 },
452 Key {
453 key: SessionKey,
454 state: SessionButtonState,
455 modifiers: SessionModifiers,
456 repeat: bool,
457 },
458 KeyboardText(String),
459 Text(String),
460 Ime(SessionIme),
461 Focus(bool),
462 FocusMove(SessionFocusDirection),
463 Cancel,
464}
465
466#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
468pub enum SessionFormMethod {
469 #[default]
470 Get,
471 Post,
472}
473
474#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
477pub struct SessionFormSubmission {
478 pub action: String,
479 pub method: SessionFormMethod,
480 pub fields: Vec<(String, String)>,
481}
482
483#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
486pub enum SessionEffect {
487 Ignored,
488 Handled,
489 Navigate(String),
490 Submit(SessionFormSubmission),
491 Cancelled,
492}
493
494impl SessionEffect {
495 pub fn is_handled(&self) -> bool {
496 !matches!(self, Self::Ignored)
497 }
498
499 pub fn allows_default_scroll(&self, editable: bool) -> bool {
501 !self.is_handled() && !editable
502 }
503}
504
505#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
508pub struct SessionInputResult {
509 pub effect: SessionEffect,
510 pub cursor: Option<SessionCursor>,
511 pub capture: Option<bool>,
513 pub editable: bool,
516}
517
518impl SessionInputResult {
519 fn new(effect: SessionEffect, editable: bool) -> Self {
520 Self {
521 effect,
522 cursor: None,
523 capture: None,
524 editable,
525 }
526 }
527}
528
529#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
531pub enum SessionNavigationCommand {
532 Address(String),
533 Reload,
534 Stop,
535 Back,
536 Forward,
537}
538
539#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
543pub enum SessionScrollKey {
544 LineUp,
545 LineDown,
546 PageUp,
547 PageDown,
548 Home,
549 End,
550}
551
552#[derive(Clone, Debug, PartialEq)]
555pub struct SessionExternalTextureDraw {
556 pub texture_key: u64,
557 pub dest_rect: [f32; 4],
558 pub opacity: f32,
559 pub scene_op_boundary: usize,
561}
562
563#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
572pub struct SessionPendingWork {
573 pub timer: Option<Duration>,
576 pub microtasks: bool,
578 pub external: bool,
580}
581
582impl SessionPendingWork {
583 pub const fn idle() -> Self {
584 Self {
585 timer: None,
586 microtasks: false,
587 external: false,
588 }
589 }
590
591 pub const fn timer(delay: Duration) -> Self {
592 Self {
593 timer: Some(delay),
594 microtasks: false,
595 external: false,
596 }
597 }
598
599 pub const fn is_idle(self) -> bool {
600 self.timer.is_none() && !self.microtasks && !self.external
601 }
602
603 pub const fn is_settled(self) -> bool {
607 !self.microtasks && !self.external
608 }
609
610 pub fn next_wake(self, now: Instant) -> Option<Instant> {
612 if self.microtasks {
613 Some(now)
614 } else {
615 self.timer.map(|delay| now + delay)
616 }
617 }
618}
619
620#[derive(Clone, Debug, PartialEq, Eq)]
634pub struct HostMutation {
635 pub target_id: String,
637 pub op: HostMutationOp,
638}
639
640impl HostMutation {
641 pub fn new(target_id: impl Into<String>, op: HostMutationOp) -> Self {
642 Self {
643 target_id: target_id.into(),
644 op,
645 }
646 }
647}
648
649#[derive(Clone, Debug, PartialEq, Eq)]
653pub enum HostMutationOp {
654 SetAttribute { name: String, value: String },
656 RemoveAttribute { name: String },
658 AppendChild {
660 tag: String,
661 class: Option<String>,
662 text: Option<String>,
663 },
664 RemoveLastChild,
667}
668
669#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
674pub struct HostMutationReport {
675 pub applied: usize,
677 pub missed: usize,
680 pub restyled_elements: usize,
682}
683
684#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
689pub struct SessionDocumentRequest {
690 pub url: String,
691 pub method: String,
692 pub headers: Vec<(String, String)>,
693 pub body: Option<Vec<u8>>,
694 pub cache: String,
695 pub redirect: String,
696 pub mode: String,
697 pub referrer: String,
699 pub referrer_policy: String,
700 pub credentials: String,
701 pub integrity: String,
702}
703#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
704pub struct SessionEncodedFormSubmission {
705 pub request: SessionDocumentRequest,
706 pub target: String,
707}
708pub struct SessionRequestSpawnResult<F> {
709 pub session: Box<dyn DocumentSession<F>>,
710 pub navigation_address: String,
711}
712
713pub fn dispatch_session_input<F, S: DocumentSession<F> + ?Sized>(
716 session: &mut S, input: SessionInput,
717) -> SessionInputResult {
718 match input {
719 SessionInput::PointerMoved { x, y, .. } => {
720 let cursor = session.cursor_at(x, y);
721 let effect = if session.pointer_move(x, y) {
722 SessionEffect::Handled
723 } else {
724 SessionEffect::Ignored
725 };
726 let mut result = SessionInputResult::new(effect, session.editable_focus());
727 result.cursor = Some(cursor);
728 result
729 },
730 SessionInput::PointerButton {
731 x,
732 y,
733 button: SessionPointerButton::Primary,
734 state,
735 ..
736 } => {
737 let cursor = session.cursor_at(x, y);
738 let click = match state {
739 SessionButtonState::Pressed => session.pointer_down(x, y),
740 SessionButtonState::Released => session.pointer_up(x, y),
741 };
742 let effect = session.effect_for_click(click);
743 let handled = effect.is_handled();
744 let mut result = SessionInputResult::new(effect, session.editable_focus());
745 result.cursor = Some(cursor);
746 result.capture = Some(matches!(state, SessionButtonState::Pressed) && handled);
747 result
748 },
749 SessionInput::PointerButton { x, y, .. } => {
750 let mut result =
751 SessionInputResult::new(SessionEffect::Ignored, session.editable_focus());
752 result.cursor = Some(session.cursor_at(x, y));
753 result
754 },
755 SessionInput::Key {
756 key,
757 state,
758 modifiers,
759 repeat,
760 } => SessionInputResult::new(
761 session.key_input(key, state, modifiers, repeat),
762 session.editable_focus(),
763 ),
764 SessionInput::KeyboardText(text) => {
765 let effect = if session.keyboard_text_input(&text) {
766 SessionEffect::Handled
767 } else {
768 SessionEffect::Ignored
769 };
770 SessionInputResult::new(effect, session.editable_focus())
771 },
772 SessionInput::Text(text) => {
773 let effect = if session.text_input(&text) {
774 SessionEffect::Handled
775 } else {
776 SessionEffect::Ignored
777 };
778 SessionInputResult::new(effect, session.editable_focus())
779 },
780 SessionInput::Ime(ime) => {
781 let effect = if session.ime_input(ime) {
782 SessionEffect::Handled
783 } else {
784 SessionEffect::Ignored
785 };
786 SessionInputResult::new(effect, session.editable_focus())
787 },
788 SessionInput::Focus(focused) => {
789 session.focus_input(focused);
790 SessionInputResult::new(SessionEffect::Handled, session.editable_focus())
791 },
792 SessionInput::FocusMove(direction) => {
793 let effect = if session.focus_move(direction) {
794 SessionEffect::Handled
795 } else {
796 SessionEffect::Ignored
797 };
798 SessionInputResult::new(effect, session.editable_focus())
799 },
800 SessionInput::Cancel => {
801 let effect = if session.cancel_input() {
802 SessionEffect::Cancelled
803 } else {
804 SessionEffect::Ignored
805 };
806 SessionInputResult::new(effect, session.editable_focus())
807 },
808 }
809 }
810
811pub trait SessionEngine<F>: Send + Sync {
812 fn engine_id(&self) -> &str;
815
816 fn spawn(
817 &self,
818 request: &SessionSpawnRequest,
819 ) -> Result<Box<dyn DocumentSession<F>>, SessionError>;
820
821 fn spawn_request(
823 &self,
824 _spawn: &SessionSpawnRequest,
825 _request: &SessionDocumentRequest,
826 ) -> Result<SessionRequestSpawnResult<F>, SessionError> {
827 Err(SessionError::Unsupported("request-aware document construction".into()))
828 }
829
830 fn a11y_capability(&self) -> A11yCapability {
834 A11yCapability::Partial
835 }
836}
837
838pub trait DocumentSession<F>: Any {
844 fn take_encoded_form_submission(&mut self) -> Option<SessionEncodedFormSubmission> { None }
846 fn current_address(&self) -> Option<String> { None }
848
849 fn document_capabilities(&self) -> DocumentCapabilities {
855 DocumentCapabilities::default()
856 }
857
858 fn frame(&mut self, width: u32, height: u32) -> F;
861
862 fn try_frame(&mut self, width: u32, height: u32) -> Result<F, String> {
865 Ok(self.frame(width, height))
866 }
867
868 fn external_texture_draws(&self) -> &[SessionExternalTextureDraw] {
870 &[]
871 }
872
873 fn scroll_by(&mut self, dx: f32, dy: f32) -> bool;
875
876 fn scroll_at(&mut self, _x: f32, _y: f32, dx: f32, dy: f32) -> bool {
879 self.scroll_by(dx, dy)
880 }
881
882 fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool;
883
884 fn scroll_to(&mut self, _y: f32) {}
888
889 fn click_at(&mut self, x: f32, y: f32) -> SessionClick;
890
891 fn pointer_down(&mut self, x: f32, y: f32) -> SessionClick {
897 self.click_at(x, y)
898 }
899
900 fn pointer_move(&mut self, _x: f32, _y: f32) -> bool {
903 false
904 }
905
906 fn pointer_up(&mut self, _x: f32, _y: f32) -> SessionClick {
912 SessionClick::Miss
913 }
914
915 fn input(&mut self, input: SessionInput) -> SessionInputResult {
920 dispatch_session_input(self, input)
921 }
922
923 fn effect_for_click(&mut self, click: SessionClick) -> SessionEffect {
924 match click {
925 SessionClick::Navigate(target) => SessionEffect::Navigate(target),
926 SessionClick::Submit(action) => SessionEffect::Submit(self.form_submission(&action)),
927 SessionClick::Handled => SessionEffect::Handled,
928 SessionClick::Miss => SessionEffect::Ignored,
929 }
930 }
931
932 fn key_input(
935 &mut self,
936 _key: SessionKey,
937 _state: SessionButtonState,
938 _modifiers: SessionModifiers,
939 _repeat: bool,
940 ) -> SessionEffect {
941 SessionEffect::Ignored
942 }
943
944 fn keyboard_text_input(&mut self, text: &str) -> bool {
947 self.text_input(text)
948 }
949
950 fn text_input(&mut self, _text: &str) -> bool {
952 false
953 }
954
955 fn ime_input(&mut self, ime: SessionIme) -> bool {
956 match ime {
957 SessionIme::Commit(text) => self.text_input(&text),
958 SessionIme::Enabled | SessionIme::Preedit { .. } | SessionIme::Disabled => false,
959 }
960 }
961
962 fn focus_input(&mut self, _focused: bool) {}
963
964 fn focus_move(&mut self, _direction: SessionFocusDirection) -> bool {
965 false
966 }
967
968 fn cancel_input(&mut self) -> bool {
969 false
970 }
971
972 fn editable_focus(&self) -> bool {
973 false
974 }
975
976 fn text_input_state(&self) -> Option<crate::SessionTextInputState> {
981 None
982 }
983
984 fn selected_text(&self) -> Option<String> {
990 None
991 }
992
993 fn cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
994 SessionCursor::Default
995 }
996
997 fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
998 SessionFormSubmission {
999 action: action.to_owned(),
1000 ..Default::default()
1001 }
1002 }
1003
1004 fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
1008 None
1009 }
1010
1011 fn document_find(
1015 &mut self,
1016 _query: &DocumentFindQuery,
1017 ) -> Result<DocumentFindState, SessionError> {
1018 Err(SessionError::Unsupported(
1019 "document find is not wired for this session".into(),
1020 ))
1021 }
1022
1023 fn document_find_step(
1025 &mut self,
1026 _direction: DocumentFindDirection,
1027 ) -> Result<DocumentFindState, SessionError> {
1028 Err(SessionError::Unsupported(
1029 "document find is not wired for this session".into(),
1030 ))
1031 }
1032
1033 fn clear_document_find(&mut self) -> Result<(), SessionError> {
1034 Ok(())
1035 }
1036
1037 fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
1046 Err(SessionError::Unsupported(
1047 "page zoom is not wired for this session".into(),
1048 ))
1049 }
1050
1051 fn capture_page(
1055 &mut self,
1056 _request: PageCaptureRequest,
1057 ) -> Result<PageCaptureOutput, SessionError> {
1058 Err(SessionError::Unsupported(
1059 "page capture is not wired for this session".into(),
1060 ))
1061 }
1062
1063 fn links(&self) -> Vec<SessionLink>;
1066
1067 fn content_height(&mut self, _width: u32, height: u32) -> u32 {
1070 height
1071 }
1072
1073 fn subresources(&self) -> Vec<String> {
1077 Vec::new()
1078 }
1079
1080 fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
1083 false
1084 }
1085
1086 fn apply_host_mutations(
1095 &mut self,
1096 _mutations: &[HostMutation],
1097 ) -> Result<HostMutationReport, SessionError> {
1098 Err(SessionError::Unsupported(
1099 "host mutation is not wired for this session".into(),
1100 ))
1101 }
1102
1103 fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
1110 Vec::new()
1111 }
1112
1113 fn pump(&mut self, _now_ms: f64) {}
1115
1116 fn collection_stats(&self) -> (usize, usize) {
1122 (0, 0)
1123 }
1124
1125 fn pending_work(&mut self) -> SessionPendingWork {
1130 SessionPendingWork::idle()
1131 }
1132
1133 fn settled(&mut self) -> bool {
1138 self.pending_work().is_settled()
1139 }
1140
1141 fn set_hidden(&mut self, _hidden: bool) {}
1143
1144 fn supports_freeze_resume(&self) -> bool {
1148 false
1149 }
1150
1151 fn freeze(&mut self) {}
1154
1155 fn resume(&mut self) {}
1157
1158 fn inspect(&self) -> Option<ContentReport> {
1165 None
1166 }
1167
1168 fn clip(&self) -> Option<DocumentClip> {
1172 None
1173 }
1174
1175 fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
1183 None
1184 }
1185
1186 fn accessibility_click_target(
1194 &self,
1195 _target: DocumentA11yNodeId,
1196 ) -> Option<DocumentA11yClickTarget> {
1197 None
1198 }
1199
1200 fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
1207 false
1208 }
1209
1210 fn as_any_ref(&self) -> &dyn Any;
1215
1216 fn as_any(&mut self) -> &mut dyn Any;
1217}
1218
1219#[derive(Default)]
1223pub struct SessionRegistry<F> {
1224 engines: HashMap<String, Box<dyn SessionEngine<F>>>,
1225}
1226
1227impl<F> SessionRegistry<F> {
1228 pub fn new() -> Self {
1229 Self {
1230 engines: HashMap::new(),
1231 }
1232 }
1233
1234 pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
1237 self.engines.insert(engine.engine_id().to_string(), engine);
1238 }
1239
1240 pub fn contains(&self, engine_id: &str) -> bool {
1241 self.engines.contains_key(engine_id)
1242 }
1243
1244 pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
1245 self.engines.get(engine_id).map(|e| e.as_ref())
1246 }
1247
1248 pub fn spawn(
1249 &self,
1250 engine_id: &str,
1251 request: &SessionSpawnRequest,
1252 ) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
1253 self.engines
1254 .get(engine_id)
1255 .ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
1256 .spawn(request)
1257 }
1258
1259 pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
1260 self.engines.keys().map(String::as_str)
1261 }
1262}
1263
1264#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1271pub struct EngineKinds {
1272 pub document: bool,
1273 pub session: bool,
1274 pub surface: bool,
1275}
1276
1277impl EngineKinds {
1278 pub fn any(&self) -> bool {
1279 self.document || self.session || self.surface
1280 }
1281}
1282
1283#[derive(Clone, Debug, Default)]
1289pub struct EngineKindIndex {
1290 kinds: HashMap<String, EngineKinds>,
1291}
1292
1293impl EngineKindIndex {
1294 pub fn build<'a>(
1295 document_ids: impl IntoIterator<Item = &'a str>,
1296 session_ids: impl IntoIterator<Item = &'a str>,
1297 surface_ids: impl IntoIterator<Item = &'a str>,
1298 ) -> Self {
1299 let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
1300 for id in document_ids {
1301 kinds.entry(id.to_string()).or_default().document = true;
1302 }
1303 for id in session_ids {
1304 kinds.entry(id.to_string()).or_default().session = true;
1305 }
1306 for id in surface_ids {
1307 kinds.entry(id.to_string()).or_default().surface = true;
1308 }
1309 Self { kinds }
1310 }
1311
1312 pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
1313 self.kinds.get(engine_id).copied().unwrap_or_default()
1314 }
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319 use super::*;
1320 use crate::PageCaptureRequestId;
1321
1322 type TextFrame = String;
1324
1325 struct EchoSession {
1326 address: String,
1327 scroll: f32,
1328 hidden: bool,
1329 }
1330
1331 impl DocumentSession<TextFrame> for EchoSession {
1332 fn frame(&mut self, width: u32, height: u32) -> TextFrame {
1333 format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
1334 }
1335 fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
1336 self.scroll += dy;
1337 dy != 0.0
1338 }
1339 fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
1340 self.scroll_by(
1341 0.0,
1342 if key == SessionScrollKey::PageDown {
1343 100.0
1344 } else {
1345 0.0
1346 },
1347 )
1348 }
1349 fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
1350 if x < 10.0 {
1351 SessionClick::Navigate("gemini://example.test/".into())
1352 } else {
1353 SessionClick::Miss
1354 }
1355 }
1356 fn links(&self) -> Vec<SessionLink> {
1357 vec![SessionLink {
1358 url: "gemini://example.test/".into(),
1359 rect: [0.0, 0.0, 10.0, 10.0],
1360 }]
1361 }
1362 fn set_hidden(&mut self, hidden: bool) {
1363 self.hidden = hidden;
1364 }
1365 fn as_any_ref(&self) -> &dyn Any {
1366 self
1367 }
1368 fn as_any(&mut self) -> &mut dyn Any {
1369 self
1370 }
1371 }
1372
1373 struct EchoSessionEngine;
1374
1375 impl SessionEngine<TextFrame> for EchoSessionEngine {
1376 fn engine_id(&self) -> &str {
1377 "echo.session"
1378 }
1379 fn spawn(
1380 &self,
1381 request: &SessionSpawnRequest,
1382 ) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
1383 if request.address.is_empty() {
1384 return Err(SessionError::SpawnFailed("empty address".into()));
1385 }
1386 Ok(Box::new(EchoSession {
1387 address: request.address.clone(),
1388 scroll: 0.0,
1389 hidden: request.hidden,
1390 }))
1391 }
1392 }
1393
1394 #[test]
1395 fn registry_spawns_and_drives_a_session() {
1396 let mut registry = SessionRegistry::new();
1397 registry.register(Box::new(EchoSessionEngine));
1398
1399 let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
1400 let mut session = registry.spawn("echo.session", &request).expect("spawns");
1401
1402 assert_eq!(
1403 session.frame(800, 600),
1404 "https://example.test @ 800x600 scroll=0"
1405 );
1406 assert!(session.scroll_by(0.0, 42.0));
1407 assert!(session.frame(800, 600).ends_with("scroll=42"));
1408 assert_eq!(
1409 session.click_at(5.0, 5.0),
1410 SessionClick::Navigate("gemini://example.test/".into())
1411 );
1412 assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
1413 assert_eq!(session.links().len(), 1);
1414 assert!(session.settled());
1416 session.pump(16.0);
1417 }
1418
1419 #[test]
1420 fn document_session_capture_defaults_to_unsupported() {
1421 let mut session = EchoSession {
1422 address: "https://example.test".into(),
1423 scroll: 0.0,
1424 hidden: false,
1425 };
1426 assert!(matches!(
1427 session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
1428 Err(SessionError::Unsupported(_))
1429 ));
1430 }
1431
1432 #[test]
1433 fn document_session_accessibility_defaults_to_an_honest_absence() {
1434 let mut session = EchoSession {
1435 address: "https://example.test".into(),
1436 scroll: 0.0,
1437 hidden: false,
1438 };
1439 let target = DocumentA11yNodeId::new(7);
1440 assert_eq!(session.accessibility_projection(), None);
1441 assert_eq!(session.accessibility_click_target(target), None);
1442 assert!(
1443 !session.dispatch_accessibility_action(&DocumentA11yActionRequest {
1444 revision: 1,
1445 target,
1446 action: crate::DocumentA11yAction::Focus,
1447 data: None,
1448 })
1449 );
1450 }
1451
1452 #[test]
1453 fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
1454 let mut registry = SessionRegistry::new();
1455 registry.register(Box::new(EchoSessionEngine));
1456 let mut session = registry
1457 .spawn(
1458 "echo.session",
1459 &SessionSpawnRequest::new("https://example.test"),
1460 )
1461 .expect("spawns");
1462
1463 let pressed = session.input(SessionInput::PointerButton {
1464 x: 5.0,
1465 y: 5.0,
1466 button: SessionPointerButton::Primary,
1467 state: SessionButtonState::Pressed,
1468 modifiers: SessionModifiers::default(),
1469 });
1470 assert_eq!(
1471 pressed.effect,
1472 SessionEffect::Navigate("gemini://example.test/".into())
1473 );
1474 assert_eq!(pressed.cursor, Some(SessionCursor::Default));
1475 assert_eq!(pressed.capture, Some(true));
1476
1477 let released = session.input(SessionInput::PointerButton {
1478 x: 5.0,
1479 y: 5.0,
1480 button: SessionPointerButton::Primary,
1481 state: SessionButtonState::Released,
1482 modifiers: SessionModifiers::default(),
1483 });
1484 assert_eq!(released.effect, SessionEffect::Ignored);
1485 assert_eq!(released.capture, Some(false));
1486 }
1487
1488 #[test]
1489 fn unknown_engine_is_a_named_error() {
1490 let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
1491 let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
1492 Ok(_) => panic!("unknown engine must not spawn"),
1493 Err(err) => err,
1494 };
1495 assert_eq!(err, SessionError::EngineNotFound("nope".into()));
1496 }
1497
1498 #[test]
1499 fn downcast_reaches_lane_extras() {
1500 let mut registry = SessionRegistry::new();
1501 registry.register(Box::new(EchoSessionEngine));
1502 let mut session = registry
1503 .spawn("echo.session", &SessionSpawnRequest::new("a"))
1504 .unwrap();
1505 session.set_hidden(true);
1506 assert!(
1507 session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
1508 "immutable hosts can reach lane extras without taking session ownership"
1509 );
1510 let echo = session
1511 .as_any()
1512 .downcast_mut::<EchoSession>()
1513 .expect("concrete lane type reachable");
1514 assert!(echo.hidden);
1515 }
1516
1517 #[test]
1518 fn kind_index_reports_flags_not_a_single_kind() {
1519 let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
1520 sessions.register(Box::new(EchoSessionEngine));
1521
1522 let index = EngineKindIndex::build(
1525 ["nematic.gemtext"],
1526 sessions.engine_ids().chain(["nematic.gemtext"]),
1527 ["scrying.web"],
1528 );
1529 assert!(index.kinds_of("echo.session").session);
1530 let both = index.kinds_of("nematic.gemtext");
1531 assert!(both.document && both.session && !both.surface);
1532 assert!(index.kinds_of("scrying.web").surface);
1533 assert!(!index.kinds_of("absent").any());
1534 }
1535
1536 #[test]
1537 fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
1538 let mut session = EchoSession {
1539 address: "gemini://example.test/".into(),
1540 scroll: 0.0,
1541 hidden: false,
1542 };
1543 assert!(matches!(
1544 session.set_page_zoom(1.25),
1545 Err(SessionError::Unsupported(_))
1546 ));
1547 }
1548
1549 #[test]
1550 fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
1551 let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
1552 assert_eq!(state.requested, 9.0);
1553 assert_eq!(state.applied, 5.0);
1554
1555 let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
1556 assert_eq!(state.requested, 0.1);
1557 assert_eq!(state.applied, 0.25);
1558
1559 assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
1560 assert_eq!(
1561 DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
1562 1.0,
1563 "a non-finite request must not reach layout as a viewport divisor"
1564 );
1565 }
1566
1567 #[test]
1568 fn pending_work_exposes_a_sleepable_timer_deadline() {
1569 let now = std::time::Instant::now();
1570 let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
1571 let deadline = work.next_wake(now).expect("timer has a wake deadline");
1572 assert!(deadline >= now + std::time::Duration::from_millis(25));
1573 assert!(!work.is_idle());
1574 assert!(
1575 work.is_settled(),
1576 "a future timer is wakeable without making a live page perpetually unsettled"
1577 );
1578 assert!(
1579 !SessionPendingWork {
1580 external: true,
1581 ..SessionPendingWork::idle()
1582 }
1583 .is_settled()
1584 );
1585 assert!(SessionPendingWork::idle().next_wake(now).is_none());
1586 assert_eq!(
1587 SessionPendingWork {
1588 microtasks: true,
1589 ..SessionPendingWork::idle()
1590 }
1591 .next_wake(now),
1592 Some(now)
1593 );
1594 }
1595
1596 fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
1598 _session.take_encoded_form_submission().map(|_| ())
1599 }
1600 fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
1601 _session.current_address()
1602 }
1603 fn t5_api_request_spawn_absent(
1604 _engine: &dyn SessionEngine<TextFrame>,
1605 _request: &SessionSpawnRequest,
1606 _bytes: &[u8],
1607 ) -> Result<(), SessionError> {
1608 let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
1609 headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
1610 mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
1611 credentials: "include".into(), integrity: String::new() };
1612 _engine.spawn_request(_request, &request).map(|_| ())
1613 }
1614 #[test]
1615 fn phase_c_t5_api_legacy_submission_literal() {
1616 let value = SessionFormSubmission {
1617 action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
1618 fields: vec![("q".into(), "café".into())],
1619 };
1620 fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
1621 retains_serde::<SessionFormSubmission>();
1622 let copied=value.clone();
1623 let SessionFormSubmission{action,method,fields}=copied;
1624 assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
1625 }
1626 #[test]
1627 fn phase_c_t5_api_legacy_result_literal() {
1628 let value = SessionInputResult { effect: SessionEffect::Handled,
1629 cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
1630 let SessionInputResult { effect, cursor, capture, editable } = value;
1631 let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
1632 SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
1633 SessionEffect::Cancelled => 4 };
1634 assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
1635 }
1636 #[test]
1637 fn key_default_scroll_respects_effect_and_effective_editable_focus() {
1638 let cases = [
1639 (SessionEffect::Ignored, false, true),
1640 (SessionEffect::Ignored, true, false),
1641 (SessionEffect::Handled, false, false),
1642 (SessionEffect::Cancelled, false, false),
1643 (SessionEffect::Navigate("https://example.test/next".into()), false, false),
1644 (SessionEffect::Submit(SessionFormSubmission::default()), false, false),
1645 ];
1646 for (effect, editable, expected) in cases {
1647 assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
1648 }
1649
1650 let result = SessionInputResult {
1654 effect: SessionEffect::Ignored,
1655 cursor: Some(SessionCursor::Text),
1656 capture: Some(false),
1657 editable: false,
1658 };
1659 assert!(result.effect.allows_default_scroll(result.editable));
1660 assert!(!result.effect.allows_default_scroll(true));
1661 assert_eq!(result.cursor, Some(SessionCursor::Text));
1662 assert_eq!(result.capture, Some(false));
1663 }
1664 #[test]
1665 fn phase_c_t5_api_legacy_spawn_unicode_body() {
1666 let request = SessionSpawnRequest { address: "https://forms.test/".into(),
1667 body: Some("café".into()), content_type: Some("text/html".into()),
1668 viewport: (320, 240), hidden: false };
1669 assert_eq!(request.body.as_deref(), Some("café"));
1670 assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
1671 }
1672 #[test]
1673 fn phase_c_t5_api_old_session_accessor_none() {
1674 let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
1675 assert!(t5_api_take_absent(&mut old).is_none());
1676 let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
1677 button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
1678 modifiers: SessionModifiers::default() });
1679 assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
1680 }
1681 #[test]
1682 fn phase_c_t5_api_old_factory_rich_decline() {
1683 let request = SessionSpawnRequest::new("https://forms.test/");
1684 assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
1685 Err(SessionError::Unsupported(_))));
1686 let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
1687 assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
1688 }
1689 #[test]
1690 fn phase_c_t5_api_old_session_current_address_none() {
1691 let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
1692 assert!(t5_api_address_absent(&old).is_none());
1693 assert_eq!(old.address, "legacy");
1694 }
1695 }