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 cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
977 SessionCursor::Default
978 }
979
980 fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
981 SessionFormSubmission {
982 action: action.to_owned(),
983 ..Default::default()
984 }
985 }
986
987 fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
991 None
992 }
993
994 fn document_find(
998 &mut self,
999 _query: &DocumentFindQuery,
1000 ) -> Result<DocumentFindState, SessionError> {
1001 Err(SessionError::Unsupported(
1002 "document find is not wired for this session".into(),
1003 ))
1004 }
1005
1006 fn document_find_step(
1008 &mut self,
1009 _direction: DocumentFindDirection,
1010 ) -> Result<DocumentFindState, SessionError> {
1011 Err(SessionError::Unsupported(
1012 "document find is not wired for this session".into(),
1013 ))
1014 }
1015
1016 fn clear_document_find(&mut self) -> Result<(), SessionError> {
1017 Ok(())
1018 }
1019
1020 fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
1029 Err(SessionError::Unsupported(
1030 "page zoom is not wired for this session".into(),
1031 ))
1032 }
1033
1034 fn capture_page(
1038 &mut self,
1039 _request: PageCaptureRequest,
1040 ) -> Result<PageCaptureOutput, SessionError> {
1041 Err(SessionError::Unsupported(
1042 "page capture is not wired for this session".into(),
1043 ))
1044 }
1045
1046 fn links(&self) -> Vec<SessionLink>;
1049
1050 fn content_height(&mut self, _width: u32, height: u32) -> u32 {
1053 height
1054 }
1055
1056 fn subresources(&self) -> Vec<String> {
1060 Vec::new()
1061 }
1062
1063 fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
1066 false
1067 }
1068
1069 fn apply_host_mutations(
1078 &mut self,
1079 _mutations: &[HostMutation],
1080 ) -> Result<HostMutationReport, SessionError> {
1081 Err(SessionError::Unsupported(
1082 "host mutation is not wired for this session".into(),
1083 ))
1084 }
1085
1086 fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
1093 Vec::new()
1094 }
1095
1096 fn pump(&mut self, _now_ms: f64) {}
1098
1099 fn collection_stats(&self) -> (usize, usize) {
1105 (0, 0)
1106 }
1107
1108 fn pending_work(&mut self) -> SessionPendingWork {
1113 SessionPendingWork::idle()
1114 }
1115
1116 fn settled(&mut self) -> bool {
1121 self.pending_work().is_settled()
1122 }
1123
1124 fn set_hidden(&mut self, _hidden: bool) {}
1126
1127 fn supports_freeze_resume(&self) -> bool {
1131 false
1132 }
1133
1134 fn freeze(&mut self) {}
1137
1138 fn resume(&mut self) {}
1140
1141 fn inspect(&self) -> Option<ContentReport> {
1148 None
1149 }
1150
1151 fn clip(&self) -> Option<DocumentClip> {
1155 None
1156 }
1157
1158 fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
1166 None
1167 }
1168
1169 fn accessibility_click_target(
1177 &self,
1178 _target: DocumentA11yNodeId,
1179 ) -> Option<DocumentA11yClickTarget> {
1180 None
1181 }
1182
1183 fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
1190 false
1191 }
1192
1193 fn as_any_ref(&self) -> &dyn Any;
1198
1199 fn as_any(&mut self) -> &mut dyn Any;
1200}
1201
1202#[derive(Default)]
1206pub struct SessionRegistry<F> {
1207 engines: HashMap<String, Box<dyn SessionEngine<F>>>,
1208}
1209
1210impl<F> SessionRegistry<F> {
1211 pub fn new() -> Self {
1212 Self {
1213 engines: HashMap::new(),
1214 }
1215 }
1216
1217 pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
1220 self.engines.insert(engine.engine_id().to_string(), engine);
1221 }
1222
1223 pub fn contains(&self, engine_id: &str) -> bool {
1224 self.engines.contains_key(engine_id)
1225 }
1226
1227 pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
1228 self.engines.get(engine_id).map(|e| e.as_ref())
1229 }
1230
1231 pub fn spawn(
1232 &self,
1233 engine_id: &str,
1234 request: &SessionSpawnRequest,
1235 ) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
1236 self.engines
1237 .get(engine_id)
1238 .ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
1239 .spawn(request)
1240 }
1241
1242 pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
1243 self.engines.keys().map(String::as_str)
1244 }
1245}
1246
1247#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1254pub struct EngineKinds {
1255 pub document: bool,
1256 pub session: bool,
1257 pub surface: bool,
1258}
1259
1260impl EngineKinds {
1261 pub fn any(&self) -> bool {
1262 self.document || self.session || self.surface
1263 }
1264}
1265
1266#[derive(Clone, Debug, Default)]
1272pub struct EngineKindIndex {
1273 kinds: HashMap<String, EngineKinds>,
1274}
1275
1276impl EngineKindIndex {
1277 pub fn build<'a>(
1278 document_ids: impl IntoIterator<Item = &'a str>,
1279 session_ids: impl IntoIterator<Item = &'a str>,
1280 surface_ids: impl IntoIterator<Item = &'a str>,
1281 ) -> Self {
1282 let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
1283 for id in document_ids {
1284 kinds.entry(id.to_string()).or_default().document = true;
1285 }
1286 for id in session_ids {
1287 kinds.entry(id.to_string()).or_default().session = true;
1288 }
1289 for id in surface_ids {
1290 kinds.entry(id.to_string()).or_default().surface = true;
1291 }
1292 Self { kinds }
1293 }
1294
1295 pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
1296 self.kinds.get(engine_id).copied().unwrap_or_default()
1297 }
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302 use super::*;
1303 use crate::PageCaptureRequestId;
1304
1305 type TextFrame = String;
1307
1308 struct EchoSession {
1309 address: String,
1310 scroll: f32,
1311 hidden: bool,
1312 }
1313
1314 impl DocumentSession<TextFrame> for EchoSession {
1315 fn frame(&mut self, width: u32, height: u32) -> TextFrame {
1316 format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
1317 }
1318 fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
1319 self.scroll += dy;
1320 dy != 0.0
1321 }
1322 fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
1323 self.scroll_by(
1324 0.0,
1325 if key == SessionScrollKey::PageDown {
1326 100.0
1327 } else {
1328 0.0
1329 },
1330 )
1331 }
1332 fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
1333 if x < 10.0 {
1334 SessionClick::Navigate("gemini://example.test/".into())
1335 } else {
1336 SessionClick::Miss
1337 }
1338 }
1339 fn links(&self) -> Vec<SessionLink> {
1340 vec![SessionLink {
1341 url: "gemini://example.test/".into(),
1342 rect: [0.0, 0.0, 10.0, 10.0],
1343 }]
1344 }
1345 fn set_hidden(&mut self, hidden: bool) {
1346 self.hidden = hidden;
1347 }
1348 fn as_any_ref(&self) -> &dyn Any {
1349 self
1350 }
1351 fn as_any(&mut self) -> &mut dyn Any {
1352 self
1353 }
1354 }
1355
1356 struct EchoSessionEngine;
1357
1358 impl SessionEngine<TextFrame> for EchoSessionEngine {
1359 fn engine_id(&self) -> &str {
1360 "echo.session"
1361 }
1362 fn spawn(
1363 &self,
1364 request: &SessionSpawnRequest,
1365 ) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
1366 if request.address.is_empty() {
1367 return Err(SessionError::SpawnFailed("empty address".into()));
1368 }
1369 Ok(Box::new(EchoSession {
1370 address: request.address.clone(),
1371 scroll: 0.0,
1372 hidden: request.hidden,
1373 }))
1374 }
1375 }
1376
1377 #[test]
1378 fn registry_spawns_and_drives_a_session() {
1379 let mut registry = SessionRegistry::new();
1380 registry.register(Box::new(EchoSessionEngine));
1381
1382 let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
1383 let mut session = registry.spawn("echo.session", &request).expect("spawns");
1384
1385 assert_eq!(
1386 session.frame(800, 600),
1387 "https://example.test @ 800x600 scroll=0"
1388 );
1389 assert!(session.scroll_by(0.0, 42.0));
1390 assert!(session.frame(800, 600).ends_with("scroll=42"));
1391 assert_eq!(
1392 session.click_at(5.0, 5.0),
1393 SessionClick::Navigate("gemini://example.test/".into())
1394 );
1395 assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
1396 assert_eq!(session.links().len(), 1);
1397 assert!(session.settled());
1399 session.pump(16.0);
1400 }
1401
1402 #[test]
1403 fn document_session_capture_defaults_to_unsupported() {
1404 let mut session = EchoSession {
1405 address: "https://example.test".into(),
1406 scroll: 0.0,
1407 hidden: false,
1408 };
1409 assert!(matches!(
1410 session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
1411 Err(SessionError::Unsupported(_))
1412 ));
1413 }
1414
1415 #[test]
1416 fn document_session_accessibility_defaults_to_an_honest_absence() {
1417 let mut session = EchoSession {
1418 address: "https://example.test".into(),
1419 scroll: 0.0,
1420 hidden: false,
1421 };
1422 let target = DocumentA11yNodeId::new(7);
1423 assert_eq!(session.accessibility_projection(), None);
1424 assert_eq!(session.accessibility_click_target(target), None);
1425 assert!(
1426 !session.dispatch_accessibility_action(&DocumentA11yActionRequest {
1427 revision: 1,
1428 target,
1429 action: crate::DocumentA11yAction::Focus,
1430 data: None,
1431 })
1432 );
1433 }
1434
1435 #[test]
1436 fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
1437 let mut registry = SessionRegistry::new();
1438 registry.register(Box::new(EchoSessionEngine));
1439 let mut session = registry
1440 .spawn(
1441 "echo.session",
1442 &SessionSpawnRequest::new("https://example.test"),
1443 )
1444 .expect("spawns");
1445
1446 let pressed = session.input(SessionInput::PointerButton {
1447 x: 5.0,
1448 y: 5.0,
1449 button: SessionPointerButton::Primary,
1450 state: SessionButtonState::Pressed,
1451 modifiers: SessionModifiers::default(),
1452 });
1453 assert_eq!(
1454 pressed.effect,
1455 SessionEffect::Navigate("gemini://example.test/".into())
1456 );
1457 assert_eq!(pressed.cursor, Some(SessionCursor::Default));
1458 assert_eq!(pressed.capture, Some(true));
1459
1460 let released = session.input(SessionInput::PointerButton {
1461 x: 5.0,
1462 y: 5.0,
1463 button: SessionPointerButton::Primary,
1464 state: SessionButtonState::Released,
1465 modifiers: SessionModifiers::default(),
1466 });
1467 assert_eq!(released.effect, SessionEffect::Ignored);
1468 assert_eq!(released.capture, Some(false));
1469 }
1470
1471 #[test]
1472 fn unknown_engine_is_a_named_error() {
1473 let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
1474 let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
1475 Ok(_) => panic!("unknown engine must not spawn"),
1476 Err(err) => err,
1477 };
1478 assert_eq!(err, SessionError::EngineNotFound("nope".into()));
1479 }
1480
1481 #[test]
1482 fn downcast_reaches_lane_extras() {
1483 let mut registry = SessionRegistry::new();
1484 registry.register(Box::new(EchoSessionEngine));
1485 let mut session = registry
1486 .spawn("echo.session", &SessionSpawnRequest::new("a"))
1487 .unwrap();
1488 session.set_hidden(true);
1489 assert!(
1490 session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
1491 "immutable hosts can reach lane extras without taking session ownership"
1492 );
1493 let echo = session
1494 .as_any()
1495 .downcast_mut::<EchoSession>()
1496 .expect("concrete lane type reachable");
1497 assert!(echo.hidden);
1498 }
1499
1500 #[test]
1501 fn kind_index_reports_flags_not_a_single_kind() {
1502 let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
1503 sessions.register(Box::new(EchoSessionEngine));
1504
1505 let index = EngineKindIndex::build(
1508 ["nematic.gemtext"],
1509 sessions.engine_ids().chain(["nematic.gemtext"]),
1510 ["scrying.web"],
1511 );
1512 assert!(index.kinds_of("echo.session").session);
1513 let both = index.kinds_of("nematic.gemtext");
1514 assert!(both.document && both.session && !both.surface);
1515 assert!(index.kinds_of("scrying.web").surface);
1516 assert!(!index.kinds_of("absent").any());
1517 }
1518
1519 #[test]
1520 fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
1521 let mut session = EchoSession {
1522 address: "gemini://example.test/".into(),
1523 scroll: 0.0,
1524 hidden: false,
1525 };
1526 assert!(matches!(
1527 session.set_page_zoom(1.25),
1528 Err(SessionError::Unsupported(_))
1529 ));
1530 }
1531
1532 #[test]
1533 fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
1534 let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
1535 assert_eq!(state.requested, 9.0);
1536 assert_eq!(state.applied, 5.0);
1537
1538 let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
1539 assert_eq!(state.requested, 0.1);
1540 assert_eq!(state.applied, 0.25);
1541
1542 assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
1543 assert_eq!(
1544 DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
1545 1.0,
1546 "a non-finite request must not reach layout as a viewport divisor"
1547 );
1548 }
1549
1550 #[test]
1551 fn pending_work_exposes_a_sleepable_timer_deadline() {
1552 let now = std::time::Instant::now();
1553 let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
1554 let deadline = work.next_wake(now).expect("timer has a wake deadline");
1555 assert!(deadline >= now + std::time::Duration::from_millis(25));
1556 assert!(!work.is_idle());
1557 assert!(
1558 work.is_settled(),
1559 "a future timer is wakeable without making a live page perpetually unsettled"
1560 );
1561 assert!(
1562 !SessionPendingWork {
1563 external: true,
1564 ..SessionPendingWork::idle()
1565 }
1566 .is_settled()
1567 );
1568 assert!(SessionPendingWork::idle().next_wake(now).is_none());
1569 assert_eq!(
1570 SessionPendingWork {
1571 microtasks: true,
1572 ..SessionPendingWork::idle()
1573 }
1574 .next_wake(now),
1575 Some(now)
1576 );
1577 }
1578
1579 fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
1581 _session.take_encoded_form_submission().map(|_| ())
1582 }
1583 fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
1584 _session.current_address()
1585 }
1586 fn t5_api_request_spawn_absent(
1587 _engine: &dyn SessionEngine<TextFrame>,
1588 _request: &SessionSpawnRequest,
1589 _bytes: &[u8],
1590 ) -> Result<(), SessionError> {
1591 let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
1592 headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
1593 mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
1594 credentials: "include".into(), integrity: String::new() };
1595 _engine.spawn_request(_request, &request).map(|_| ())
1596 }
1597 #[test]
1598 fn phase_c_t5_api_legacy_submission_literal() {
1599 let value = SessionFormSubmission {
1600 action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
1601 fields: vec![("q".into(), "café".into())],
1602 };
1603 fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
1604 retains_serde::<SessionFormSubmission>();
1605 let copied=value.clone();
1606 let SessionFormSubmission{action,method,fields}=copied;
1607 assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
1608 }
1609 #[test]
1610 fn phase_c_t5_api_legacy_result_literal() {
1611 let value = SessionInputResult { effect: SessionEffect::Handled,
1612 cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
1613 let SessionInputResult { effect, cursor, capture, editable } = value;
1614 let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
1615 SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
1616 SessionEffect::Cancelled => 4 };
1617 assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
1618 }
1619 #[test]
1620 fn key_default_scroll_respects_effect_and_effective_editable_focus() {
1621 let cases = [
1622 (SessionEffect::Ignored, false, true),
1623 (SessionEffect::Ignored, true, false),
1624 (SessionEffect::Handled, false, false),
1625 (SessionEffect::Cancelled, false, false),
1626 (SessionEffect::Navigate("https://example.test/next".into()), false, false),
1627 (SessionEffect::Submit(SessionFormSubmission::default()), false, false),
1628 ];
1629 for (effect, editable, expected) in cases {
1630 assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
1631 }
1632
1633 let result = SessionInputResult {
1637 effect: SessionEffect::Ignored,
1638 cursor: Some(SessionCursor::Text),
1639 capture: Some(false),
1640 editable: false,
1641 };
1642 assert!(result.effect.allows_default_scroll(result.editable));
1643 assert!(!result.effect.allows_default_scroll(true));
1644 assert_eq!(result.cursor, Some(SessionCursor::Text));
1645 assert_eq!(result.capture, Some(false));
1646 }
1647 #[test]
1648 fn phase_c_t5_api_legacy_spawn_unicode_body() {
1649 let request = SessionSpawnRequest { address: "https://forms.test/".into(),
1650 body: Some("café".into()), content_type: Some("text/html".into()),
1651 viewport: (320, 240), hidden: false };
1652 assert_eq!(request.body.as_deref(), Some("café"));
1653 assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
1654 }
1655 #[test]
1656 fn phase_c_t5_api_old_session_accessor_none() {
1657 let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
1658 assert!(t5_api_take_absent(&mut old).is_none());
1659 let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
1660 button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
1661 modifiers: SessionModifiers::default() });
1662 assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
1663 }
1664 #[test]
1665 fn phase_c_t5_api_old_factory_rich_decline() {
1666 let request = SessionSpawnRequest::new("https://forms.test/");
1667 assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
1668 Err(SessionError::Unsupported(_))));
1669 let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
1670 assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
1671 }
1672 #[test]
1673 fn phase_c_t5_api_old_session_current_address_none() {
1674 let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
1675 assert!(t5_api_address_absent(&old).is_none());
1676 assert_eq!(old.address, "legacy");
1677 }
1678 }