use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use crate::a11y::{
DocumentA11yActionRequest, DocumentA11yClickTarget, DocumentA11yNodeId, DocumentA11yProjection,
};
use crate::{A11yCapability, DocumentCapabilities, PageCaptureOutput, PageCaptureRequest};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionError {
EngineNotFound(String),
SpawnFailed(String),
Unsupported(String),
}
impl fmt::Display for SessionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EngineNotFound(id) => write!(f, "session engine not registered: {id}"),
Self::SpawnFailed(reason) => write!(f, "session spawn failed: {reason}"),
Self::Unsupported(reason) => write!(f, "unsupported: {reason}"),
}
}
}
impl std::error::Error for SessionError {}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSpawnRequest {
pub address: String,
pub body: Option<String>,
pub content_type: Option<String>,
pub viewport: (u32, u32),
pub hidden: bool,
}
impl SessionSpawnRequest {
pub fn new(address: impl Into<String>) -> Self {
Self {
address: address.into(),
body: None,
content_type: None,
viewport: (0, 0),
hidden: false,
}
}
pub fn with_body(mut self, body: impl Into<String>) -> Self {
self.body = Some(body.into());
self
}
pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
self.viewport = (width, height);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SessionLink {
pub url: String,
pub rect: [f32; 4],
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContentReport {
pub title: Option<String>,
pub outline: Vec<OutlineEntry>,
pub links: Vec<String>,
pub headings: Vec<String>,
pub lineage: Option<ContentLineage>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContentLineage {
pub tool: String,
pub version: String,
pub selector: String,
pub score: Option<i32>,
pub block_count: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DocumentClipArtifactRole {
SourceResponse,
ObservedRepresentation,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentClipArtifact {
pub role: DocumentClipArtifactRole,
pub media_type: String,
pub canonical_uri: String,
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentClip {
pub source_url: String,
pub title: Option<String>,
pub text: String,
pub selector: Option<String>,
pub links: Vec<String>,
pub artifacts: Vec<DocumentClipArtifact>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SessionTextTarget {
pub anchor: [f32; 2],
pub focus: [f32; 2],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DocumentFindDirection {
Previous,
Next,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DocumentFindQuery {
pub text: String,
pub match_case: bool,
}
impl DocumentFindQuery {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
match_case: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum DocumentFindReveal {
ScrollY(f32),
EngineManaged,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentFindMatch {
pub label: String,
pub role: Option<String>,
pub reveal: DocumentFindReveal,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentFindState {
pub query: DocumentFindQuery,
pub count: usize,
pub matches: Vec<DocumentFindMatch>,
pub current: Option<usize>,
pub complete: bool,
}
impl DocumentFindState {
pub fn empty(query: DocumentFindQuery) -> Self {
Self {
query,
count: 0,
matches: Vec::new(),
current: None,
complete: true,
}
}
pub fn engine_managed(
query: DocumentFindQuery,
count: usize,
active_match: Option<usize>,
complete: bool,
) -> Self {
Self {
query,
count,
matches: Vec::new(),
current: active_match.filter(|index| *index < count),
complete,
}
}
pub fn current_match(&self) -> Option<&DocumentFindMatch> {
self.current.and_then(|index| self.matches.get(index))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentZoomState {
pub requested: f32,
pub applied: f32,
pub min: f32,
pub max: f32,
}
impl DocumentZoomState {
pub fn clamped(requested: f32, min: f32, max: f32) -> Self {
let applied = if requested.is_finite() {
requested.clamp(min, max)
} else {
1.0_f32.clamp(min, max)
};
Self {
requested,
applied,
min,
max,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct OutlineEntry {
pub depth: usize,
pub role: &'static str,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionClick {
Navigate(String),
Submit(String),
Handled,
Miss,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionModifiers {
pub shift: bool,
pub control: bool,
pub alt: bool,
pub meta: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionPointerButton {
Primary,
Secondary,
Auxiliary,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionButtonState {
Pressed,
Released,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionCursor {
#[default]
Default,
Pointer,
Text,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionKey {
Character(String),
Enter,
Tab,
Backspace,
Delete,
Escape,
Space,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown,
Home,
End,
PageUp,
PageDown,
Unidentified,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionFocusDirection {
Forward,
Backward,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionIme {
Enabled,
Preedit {
text: String,
selection: Option<(usize, usize)>,
},
Commit(String),
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SessionInput {
PointerMoved {
x: f32,
y: f32,
modifiers: SessionModifiers,
},
PointerButton {
x: f32,
y: f32,
button: SessionPointerButton,
state: SessionButtonState,
modifiers: SessionModifiers,
},
Key {
key: SessionKey,
state: SessionButtonState,
modifiers: SessionModifiers,
repeat: bool,
},
KeyboardText(String),
Text(String),
Ime(SessionIme),
Focus(bool),
FocusMove(SessionFocusDirection),
Cancel,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionFormMethod {
#[default]
Get,
Post,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionFormSubmission {
pub action: String,
pub method: SessionFormMethod,
pub fields: Vec<(String, String)>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionEffect {
Ignored,
Handled,
Navigate(String),
Submit(SessionFormSubmission),
Cancelled,
}
impl SessionEffect {
pub fn is_handled(&self) -> bool {
!matches!(self, Self::Ignored)
}
pub fn allows_default_scroll(&self, editable: bool) -> bool {
!self.is_handled() && !editable
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionInputResult {
pub effect: SessionEffect,
pub cursor: Option<SessionCursor>,
pub capture: Option<bool>,
pub editable: bool,
}
impl SessionInputResult {
fn new(effect: SessionEffect, editable: bool) -> Self {
Self {
effect,
cursor: None,
capture: None,
editable,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionNavigationCommand {
Address(String),
Reload,
Stop,
Back,
Forward,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionScrollKey {
LineUp,
LineDown,
PageUp,
PageDown,
Home,
End,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SessionExternalTextureDraw {
pub texture_key: u64,
pub dest_rect: [f32; 4],
pub opacity: f32,
pub scene_op_boundary: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SessionPendingWork {
pub timer: Option<Duration>,
pub microtasks: bool,
pub external: bool,
}
impl SessionPendingWork {
pub const fn idle() -> Self {
Self {
timer: None,
microtasks: false,
external: false,
}
}
pub const fn timer(delay: Duration) -> Self {
Self {
timer: Some(delay),
microtasks: false,
external: false,
}
}
pub const fn is_idle(self) -> bool {
self.timer.is_none() && !self.microtasks && !self.external
}
pub const fn is_settled(self) -> bool {
!self.microtasks && !self.external
}
pub fn next_wake(self, now: Instant) -> Option<Instant> {
if self.microtasks {
Some(now)
} else {
self.timer.map(|delay| now + delay)
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostMutation {
pub target_id: String,
pub op: HostMutationOp,
}
impl HostMutation {
pub fn new(target_id: impl Into<String>, op: HostMutationOp) -> Self {
Self {
target_id: target_id.into(),
op,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostMutationOp {
SetAttribute { name: String, value: String },
RemoveAttribute { name: String },
AppendChild {
tag: String,
class: Option<String>,
text: Option<String>,
},
RemoveLastChild,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HostMutationReport {
pub applied: usize,
pub missed: usize,
pub restyled_elements: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionDocumentRequest {
pub url: String,
pub method: String,
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
pub cache: String,
pub redirect: String,
pub mode: String,
pub referrer: String,
pub referrer_policy: String,
pub credentials: String,
pub integrity: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionEncodedFormSubmission {
pub request: SessionDocumentRequest,
pub target: String,
}
pub struct SessionRequestSpawnResult<F> {
pub session: Box<dyn DocumentSession<F>>,
pub navigation_address: String,
}
pub fn dispatch_session_input<F, S: DocumentSession<F> + ?Sized>(
session: &mut S, input: SessionInput,
) -> SessionInputResult {
match input {
SessionInput::PointerMoved { x, y, .. } => {
let cursor = session.cursor_at(x, y);
let effect = if session.pointer_move(x, y) {
SessionEffect::Handled
} else {
SessionEffect::Ignored
};
let mut result = SessionInputResult::new(effect, session.editable_focus());
result.cursor = Some(cursor);
result
},
SessionInput::PointerButton {
x,
y,
button: SessionPointerButton::Primary,
state,
..
} => {
let cursor = session.cursor_at(x, y);
let click = match state {
SessionButtonState::Pressed => session.pointer_down(x, y),
SessionButtonState::Released => session.pointer_up(x, y),
};
let effect = session.effect_for_click(click);
let handled = effect.is_handled();
let mut result = SessionInputResult::new(effect, session.editable_focus());
result.cursor = Some(cursor);
result.capture = Some(matches!(state, SessionButtonState::Pressed) && handled);
result
},
SessionInput::PointerButton { x, y, .. } => {
let mut result =
SessionInputResult::new(SessionEffect::Ignored, session.editable_focus());
result.cursor = Some(session.cursor_at(x, y));
result
},
SessionInput::Key {
key,
state,
modifiers,
repeat,
} => SessionInputResult::new(
session.key_input(key, state, modifiers, repeat),
session.editable_focus(),
),
SessionInput::KeyboardText(text) => {
let effect = if session.keyboard_text_input(&text) {
SessionEffect::Handled
} else {
SessionEffect::Ignored
};
SessionInputResult::new(effect, session.editable_focus())
},
SessionInput::Text(text) => {
let effect = if session.text_input(&text) {
SessionEffect::Handled
} else {
SessionEffect::Ignored
};
SessionInputResult::new(effect, session.editable_focus())
},
SessionInput::Ime(ime) => {
let effect = if session.ime_input(ime) {
SessionEffect::Handled
} else {
SessionEffect::Ignored
};
SessionInputResult::new(effect, session.editable_focus())
},
SessionInput::Focus(focused) => {
session.focus_input(focused);
SessionInputResult::new(SessionEffect::Handled, session.editable_focus())
},
SessionInput::FocusMove(direction) => {
let effect = if session.focus_move(direction) {
SessionEffect::Handled
} else {
SessionEffect::Ignored
};
SessionInputResult::new(effect, session.editable_focus())
},
SessionInput::Cancel => {
let effect = if session.cancel_input() {
SessionEffect::Cancelled
} else {
SessionEffect::Ignored
};
SessionInputResult::new(effect, session.editable_focus())
},
}
}
pub trait SessionEngine<F>: Send + Sync {
fn engine_id(&self) -> &str;
fn spawn(
&self,
request: &SessionSpawnRequest,
) -> Result<Box<dyn DocumentSession<F>>, SessionError>;
fn spawn_request(
&self,
_spawn: &SessionSpawnRequest,
_request: &SessionDocumentRequest,
) -> Result<SessionRequestSpawnResult<F>, SessionError> {
Err(SessionError::Unsupported("request-aware document construction".into()))
}
fn a11y_capability(&self) -> A11yCapability {
A11yCapability::Partial
}
}
pub trait DocumentSession<F>: Any {
fn take_encoded_form_submission(&mut self) -> Option<SessionEncodedFormSubmission> { None }
fn current_address(&self) -> Option<String> { None }
fn document_capabilities(&self) -> DocumentCapabilities {
DocumentCapabilities::default()
}
fn frame(&mut self, width: u32, height: u32) -> F;
fn try_frame(&mut self, width: u32, height: u32) -> Result<F, String> {
Ok(self.frame(width, height))
}
fn external_texture_draws(&self) -> &[SessionExternalTextureDraw] {
&[]
}
fn scroll_by(&mut self, dx: f32, dy: f32) -> bool;
fn scroll_at(&mut self, _x: f32, _y: f32, dx: f32, dy: f32) -> bool {
self.scroll_by(dx, dy)
}
fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool;
fn scroll_to(&mut self, _y: f32) {}
fn click_at(&mut self, x: f32, y: f32) -> SessionClick;
fn pointer_down(&mut self, x: f32, y: f32) -> SessionClick {
self.click_at(x, y)
}
fn pointer_move(&mut self, _x: f32, _y: f32) -> bool {
false
}
fn pointer_up(&mut self, _x: f32, _y: f32) -> SessionClick {
SessionClick::Miss
}
fn input(&mut self, input: SessionInput) -> SessionInputResult {
dispatch_session_input(self, input)
}
fn effect_for_click(&mut self, click: SessionClick) -> SessionEffect {
match click {
SessionClick::Navigate(target) => SessionEffect::Navigate(target),
SessionClick::Submit(action) => SessionEffect::Submit(self.form_submission(&action)),
SessionClick::Handled => SessionEffect::Handled,
SessionClick::Miss => SessionEffect::Ignored,
}
}
fn key_input(
&mut self,
_key: SessionKey,
_state: SessionButtonState,
_modifiers: SessionModifiers,
_repeat: bool,
) -> SessionEffect {
SessionEffect::Ignored
}
fn keyboard_text_input(&mut self, text: &str) -> bool {
self.text_input(text)
}
fn text_input(&mut self, _text: &str) -> bool {
false
}
fn ime_input(&mut self, ime: SessionIme) -> bool {
match ime {
SessionIme::Commit(text) => self.text_input(&text),
SessionIme::Enabled | SessionIme::Preedit { .. } | SessionIme::Disabled => false,
}
}
fn focus_input(&mut self, _focused: bool) {}
fn focus_move(&mut self, _direction: SessionFocusDirection) -> bool {
false
}
fn cancel_input(&mut self) -> bool {
false
}
fn editable_focus(&self) -> bool {
false
}
fn text_input_state(&self) -> Option<crate::SessionTextInputState> {
None
}
fn selected_text(&self) -> Option<String> {
None
}
fn cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
SessionCursor::Default
}
fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
SessionFormSubmission {
action: action.to_owned(),
..Default::default()
}
}
fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
None
}
fn document_find(
&mut self,
_query: &DocumentFindQuery,
) -> Result<DocumentFindState, SessionError> {
Err(SessionError::Unsupported(
"document find is not wired for this session".into(),
))
}
fn document_find_step(
&mut self,
_direction: DocumentFindDirection,
) -> Result<DocumentFindState, SessionError> {
Err(SessionError::Unsupported(
"document find is not wired for this session".into(),
))
}
fn clear_document_find(&mut self) -> Result<(), SessionError> {
Ok(())
}
fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
Err(SessionError::Unsupported(
"page zoom is not wired for this session".into(),
))
}
fn capture_page(
&mut self,
_request: PageCaptureRequest,
) -> Result<PageCaptureOutput, SessionError> {
Err(SessionError::Unsupported(
"page capture is not wired for this session".into(),
))
}
fn links(&self) -> Vec<SessionLink>;
fn content_height(&mut self, _width: u32, height: u32) -> u32 {
height
}
fn subresources(&self) -> Vec<String> {
Vec::new()
}
fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
false
}
fn apply_host_mutations(
&mut self,
_mutations: &[HostMutation],
) -> Result<HostMutationReport, SessionError> {
Err(SessionError::Unsupported(
"host mutation is not wired for this session".into(),
))
}
fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
Vec::new()
}
fn pump(&mut self, _now_ms: f64) {}
fn collection_stats(&self) -> (usize, usize) {
(0, 0)
}
fn pending_work(&mut self) -> SessionPendingWork {
SessionPendingWork::idle()
}
fn settled(&mut self) -> bool {
self.pending_work().is_settled()
}
fn set_hidden(&mut self, _hidden: bool) {}
fn supports_freeze_resume(&self) -> bool {
false
}
fn freeze(&mut self) {}
fn resume(&mut self) {}
fn inspect(&self) -> Option<ContentReport> {
None
}
fn clip(&self) -> Option<DocumentClip> {
None
}
fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
None
}
fn accessibility_click_target(
&self,
_target: DocumentA11yNodeId,
) -> Option<DocumentA11yClickTarget> {
None
}
fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
false
}
fn as_any_ref(&self) -> &dyn Any;
fn as_any(&mut self) -> &mut dyn Any;
}
#[derive(Default)]
pub struct SessionRegistry<F> {
engines: HashMap<String, Box<dyn SessionEngine<F>>>,
}
impl<F> SessionRegistry<F> {
pub fn new() -> Self {
Self {
engines: HashMap::new(),
}
}
pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
self.engines.insert(engine.engine_id().to_string(), engine);
}
pub fn contains(&self, engine_id: &str) -> bool {
self.engines.contains_key(engine_id)
}
pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
self.engines.get(engine_id).map(|e| e.as_ref())
}
pub fn spawn(
&self,
engine_id: &str,
request: &SessionSpawnRequest,
) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
self.engines
.get(engine_id)
.ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
.spawn(request)
}
pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
self.engines.keys().map(String::as_str)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EngineKinds {
pub document: bool,
pub session: bool,
pub surface: bool,
}
impl EngineKinds {
pub fn any(&self) -> bool {
self.document || self.session || self.surface
}
}
#[derive(Clone, Debug, Default)]
pub struct EngineKindIndex {
kinds: HashMap<String, EngineKinds>,
}
impl EngineKindIndex {
pub fn build<'a>(
document_ids: impl IntoIterator<Item = &'a str>,
session_ids: impl IntoIterator<Item = &'a str>,
surface_ids: impl IntoIterator<Item = &'a str>,
) -> Self {
let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
for id in document_ids {
kinds.entry(id.to_string()).or_default().document = true;
}
for id in session_ids {
kinds.entry(id.to_string()).or_default().session = true;
}
for id in surface_ids {
kinds.entry(id.to_string()).or_default().surface = true;
}
Self { kinds }
}
pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
self.kinds.get(engine_id).copied().unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PageCaptureRequestId;
type TextFrame = String;
struct EchoSession {
address: String,
scroll: f32,
hidden: bool,
}
impl DocumentSession<TextFrame> for EchoSession {
fn frame(&mut self, width: u32, height: u32) -> TextFrame {
format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
}
fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
self.scroll += dy;
dy != 0.0
}
fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
self.scroll_by(
0.0,
if key == SessionScrollKey::PageDown {
100.0
} else {
0.0
},
)
}
fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
if x < 10.0 {
SessionClick::Navigate("gemini://example.test/".into())
} else {
SessionClick::Miss
}
}
fn links(&self) -> Vec<SessionLink> {
vec![SessionLink {
url: "gemini://example.test/".into(),
rect: [0.0, 0.0, 10.0, 10.0],
}]
}
fn set_hidden(&mut self, hidden: bool) {
self.hidden = hidden;
}
fn as_any_ref(&self) -> &dyn Any {
self
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
struct EchoSessionEngine;
impl SessionEngine<TextFrame> for EchoSessionEngine {
fn engine_id(&self) -> &str {
"echo.session"
}
fn spawn(
&self,
request: &SessionSpawnRequest,
) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
if request.address.is_empty() {
return Err(SessionError::SpawnFailed("empty address".into()));
}
Ok(Box::new(EchoSession {
address: request.address.clone(),
scroll: 0.0,
hidden: request.hidden,
}))
}
}
#[test]
fn registry_spawns_and_drives_a_session() {
let mut registry = SessionRegistry::new();
registry.register(Box::new(EchoSessionEngine));
let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
let mut session = registry.spawn("echo.session", &request).expect("spawns");
assert_eq!(
session.frame(800, 600),
"https://example.test @ 800x600 scroll=0"
);
assert!(session.scroll_by(0.0, 42.0));
assert!(session.frame(800, 600).ends_with("scroll=42"));
assert_eq!(
session.click_at(5.0, 5.0),
SessionClick::Navigate("gemini://example.test/".into())
);
assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
assert_eq!(session.links().len(), 1);
assert!(session.settled());
session.pump(16.0);
}
#[test]
fn document_session_capture_defaults_to_unsupported() {
let mut session = EchoSession {
address: "https://example.test".into(),
scroll: 0.0,
hidden: false,
};
assert!(matches!(
session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
Err(SessionError::Unsupported(_))
));
}
#[test]
fn document_session_accessibility_defaults_to_an_honest_absence() {
let mut session = EchoSession {
address: "https://example.test".into(),
scroll: 0.0,
hidden: false,
};
let target = DocumentA11yNodeId::new(7);
assert_eq!(session.accessibility_projection(), None);
assert_eq!(session.accessibility_click_target(target), None);
assert!(
!session.dispatch_accessibility_action(&DocumentA11yActionRequest {
revision: 1,
target,
action: crate::DocumentA11yAction::Focus,
data: None,
})
);
}
#[test]
fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
let mut registry = SessionRegistry::new();
registry.register(Box::new(EchoSessionEngine));
let mut session = registry
.spawn(
"echo.session",
&SessionSpawnRequest::new("https://example.test"),
)
.expect("spawns");
let pressed = session.input(SessionInput::PointerButton {
x: 5.0,
y: 5.0,
button: SessionPointerButton::Primary,
state: SessionButtonState::Pressed,
modifiers: SessionModifiers::default(),
});
assert_eq!(
pressed.effect,
SessionEffect::Navigate("gemini://example.test/".into())
);
assert_eq!(pressed.cursor, Some(SessionCursor::Default));
assert_eq!(pressed.capture, Some(true));
let released = session.input(SessionInput::PointerButton {
x: 5.0,
y: 5.0,
button: SessionPointerButton::Primary,
state: SessionButtonState::Released,
modifiers: SessionModifiers::default(),
});
assert_eq!(released.effect, SessionEffect::Ignored);
assert_eq!(released.capture, Some(false));
}
#[test]
fn unknown_engine_is_a_named_error() {
let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
Ok(_) => panic!("unknown engine must not spawn"),
Err(err) => err,
};
assert_eq!(err, SessionError::EngineNotFound("nope".into()));
}
#[test]
fn downcast_reaches_lane_extras() {
let mut registry = SessionRegistry::new();
registry.register(Box::new(EchoSessionEngine));
let mut session = registry
.spawn("echo.session", &SessionSpawnRequest::new("a"))
.unwrap();
session.set_hidden(true);
assert!(
session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
"immutable hosts can reach lane extras without taking session ownership"
);
let echo = session
.as_any()
.downcast_mut::<EchoSession>()
.expect("concrete lane type reachable");
assert!(echo.hidden);
}
#[test]
fn kind_index_reports_flags_not_a_single_kind() {
let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
sessions.register(Box::new(EchoSessionEngine));
let index = EngineKindIndex::build(
["nematic.gemtext"],
sessions.engine_ids().chain(["nematic.gemtext"]),
["scrying.web"],
);
assert!(index.kinds_of("echo.session").session);
let both = index.kinds_of("nematic.gemtext");
assert!(both.document && both.session && !both.surface);
assert!(index.kinds_of("scrying.web").surface);
assert!(!index.kinds_of("absent").any());
}
#[test]
fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
let mut session = EchoSession {
address: "gemini://example.test/".into(),
scroll: 0.0,
hidden: false,
};
assert!(matches!(
session.set_page_zoom(1.25),
Err(SessionError::Unsupported(_))
));
}
#[test]
fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
assert_eq!(state.requested, 9.0);
assert_eq!(state.applied, 5.0);
let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
assert_eq!(state.requested, 0.1);
assert_eq!(state.applied, 0.25);
assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
assert_eq!(
DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
1.0,
"a non-finite request must not reach layout as a viewport divisor"
);
}
#[test]
fn pending_work_exposes_a_sleepable_timer_deadline() {
let now = std::time::Instant::now();
let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
let deadline = work.next_wake(now).expect("timer has a wake deadline");
assert!(deadline >= now + std::time::Duration::from_millis(25));
assert!(!work.is_idle());
assert!(
work.is_settled(),
"a future timer is wakeable without making a live page perpetually unsettled"
);
assert!(
!SessionPendingWork {
external: true,
..SessionPendingWork::idle()
}
.is_settled()
);
assert!(SessionPendingWork::idle().next_wake(now).is_none());
assert_eq!(
SessionPendingWork {
microtasks: true,
..SessionPendingWork::idle()
}
.next_wake(now),
Some(now)
);
}
fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
_session.take_encoded_form_submission().map(|_| ())
}
fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
_session.current_address()
}
fn t5_api_request_spawn_absent(
_engine: &dyn SessionEngine<TextFrame>,
_request: &SessionSpawnRequest,
_bytes: &[u8],
) -> Result<(), SessionError> {
let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
credentials: "include".into(), integrity: String::new() };
_engine.spawn_request(_request, &request).map(|_| ())
}
#[test]
fn phase_c_t5_api_legacy_submission_literal() {
let value = SessionFormSubmission {
action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
fields: vec![("q".into(), "café".into())],
};
fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
retains_serde::<SessionFormSubmission>();
let copied=value.clone();
let SessionFormSubmission{action,method,fields}=copied;
assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
}
#[test]
fn phase_c_t5_api_legacy_result_literal() {
let value = SessionInputResult { effect: SessionEffect::Handled,
cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
let SessionInputResult { effect, cursor, capture, editable } = value;
let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
SessionEffect::Cancelled => 4 };
assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
}
#[test]
fn key_default_scroll_respects_effect_and_effective_editable_focus() {
let cases = [
(SessionEffect::Ignored, false, true),
(SessionEffect::Ignored, true, false),
(SessionEffect::Handled, false, false),
(SessionEffect::Cancelled, false, false),
(SessionEffect::Navigate("https://example.test/next".into()), false, false),
(SessionEffect::Submit(SessionFormSubmission::default()), false, false),
];
for (effect, editable, expected) in cases {
assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
}
let result = SessionInputResult {
effect: SessionEffect::Ignored,
cursor: Some(SessionCursor::Text),
capture: Some(false),
editable: false,
};
assert!(result.effect.allows_default_scroll(result.editable));
assert!(!result.effect.allows_default_scroll(true));
assert_eq!(result.cursor, Some(SessionCursor::Text));
assert_eq!(result.capture, Some(false));
}
#[test]
fn phase_c_t5_api_legacy_spawn_unicode_body() {
let request = SessionSpawnRequest { address: "https://forms.test/".into(),
body: Some("café".into()), content_type: Some("text/html".into()),
viewport: (320, 240), hidden: false };
assert_eq!(request.body.as_deref(), Some("café"));
assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
}
#[test]
fn phase_c_t5_api_old_session_accessor_none() {
let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
assert!(t5_api_take_absent(&mut old).is_none());
let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
modifiers: SessionModifiers::default() });
assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
}
#[test]
fn phase_c_t5_api_old_factory_rich_decline() {
let request = SessionSpawnRequest::new("https://forms.test/");
assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
Err(SessionError::Unsupported(_))));
let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
}
#[test]
fn phase_c_t5_api_old_session_current_address_none() {
let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
assert!(t5_api_address_absent(&old).is_none());
assert_eq!(old.address, "legacy");
}
}