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