use std::{any::Any, collections::HashMap, fmt};
use serde::{Deserialize, Serialize};
pub use accesskit::ActionRequest as SurfaceAccessibilityActionRequest;
pub use accesskit::TreeId as SurfaceAccessibilityTreeId;
pub use accesskit::TreeUpdate as SurfaceAccessibilityUpdate;
pub use crate::WebFeatureStatus;
use crate::presentation::PresentationDeclaration;
use crate::routing::EngineRouteDecision;
use crate::session_engine::{
DocumentFindDirection, DocumentFindQuery, DocumentFindState, DocumentZoomState,
};
use crate::{
A11yCapability, DocumentCapabilities, PageCaptureOutput, PageCaptureRequest,
PageCaptureRequestId,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct UserAgentRequestId(u64);
impl UserAgentRequestId {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub const fn get(self) -> u64 {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct WebRequestId(u64);
impl WebRequestId {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub const fn get(self) -> u64 {
self.0
}
}
mod permission;
pub use permission::*;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SurfaceError {
EngineNotFound(String),
SpawnFailed(String),
NavigationFailed(String),
InputFailed(String),
FrameAcquisitionFailed(String),
Busy {
operation: String,
},
Unsupported(String),
HostMigrationIndeterminate(String),
}
impl fmt::Display for SurfaceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EngineNotFound(id) => write!(f, "surface engine not registered: {id}"),
Self::SpawnFailed(reason) => write!(f, "spawn failed: {reason}"),
Self::NavigationFailed(reason) => write!(f, "navigation failed: {reason}"),
Self::InputFailed(reason) => write!(f, "input failed: {reason}"),
Self::FrameAcquisitionFailed(reason) => write!(f, "frame acquisition: {reason}"),
Self::Busy { operation } => write!(f, "busy: {operation}"),
Self::Unsupported(reason) => write!(f, "unsupported: {reason}"),
Self::HostMigrationIndeterminate(reason) => {
write!(f, "host migration indeterminate: {reason}")
},
}
}
}
impl std::error::Error for SurfaceError {}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NativeSurfaceHost {
Win32 { hwnd: std::num::NonZeroIsize },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EngineProfileBinding {
pub user_data_dir: String,
}
#[derive(Clone, Debug)]
pub struct SurfaceSpawnRequest {
pub url: String,
pub width: u32,
pub height: u32,
pub profile: EngineProfileBinding,
pub fence_handle: Option<u64>,
}
mod frame;
pub use frame::*;
mod input;
pub use input::*;
mod events;
pub use events::*;
pub trait SurfaceEngine: Send + Sync {
fn engine_id(&self) -> &str;
fn spawn(
&self,
request: &SurfaceSpawnRequest,
) -> Result<Box<dyn SurfaceProducer>, SurfaceError>;
fn a11y_capability(&self) -> A11yCapability {
A11yCapability::Opaque
}
fn declaration(&self) -> PresentationDeclaration {
PresentationDeclaration::surface(self.engine_id()).a11y(self.a11y_capability())
}
}
pub trait SurfaceProducer {
fn resize(&mut self, width: u32, height: u32) -> Result<(), SurfaceError>;
fn set_offset(&mut self, x: i32, y: i32) -> Result<(), SurfaceError>;
fn acquire_frame(&mut self) -> Result<Option<SurfaceFrame>, SurfaceError>;
fn send_mouse_input(&mut self, ev: MouseEvent) -> Result<(), SurfaceError>;
fn send_pointer_input(&mut self, ev: PointerEvent) -> Result<(), SurfaceError>;
fn send_wheel_input(&mut self, event: SurfaceWheelEvent) -> Result<(), SurfaceError> {
if event.modifiers != KeyboardModifiers::default() {
return Err(SurfaceError::Unsupported(
"modified wheel input is not wired for this surface".into(),
));
}
self.send_mouse_input(MouseEvent {
position: event.position,
button: None,
kind: MouseEventKind::ScrollPixels {
delta_x: event.delta.0,
delta_y: event.delta.1,
},
})
}
fn set_focus(&mut self, focused: bool) -> Result<(), SurfaceError> {
if focused {
self.move_focus(FocusReason::Programmatic)
} else {
Err(SurfaceError::Unsupported(
"focus loss is not wired for this surface".into(),
))
}
}
fn send_drag_input(&mut self, _ev: DragEvent) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"host-to-page drag input is not wired for this surface".into(),
))
}
fn finish_drag_source(
&mut self,
_position: PhysicalPosition,
_operation: DragOperationSet,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"page-to-host drag completion is not wired for this surface".into(),
))
}
fn send_keyboard_input(&mut self, ev: KeyboardEvent) -> Result<(), SurfaceError>;
fn move_focus(&mut self, reason: FocusReason) -> Result<(), SurfaceError>;
unsafe fn rehost(&mut self, _host: NativeSurfaceHost) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"surface producer rehosting is not wired for this surface".into(),
))
}
fn poll_cursor_shape(&mut self) -> Option<CursorShape>;
fn apply_settings(&mut self, settings: &SurfaceSettings) -> Result<(), SurfaceError>;
fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SurfaceError> {
Err(SurfaceError::Unsupported(
"page zoom is not wired for this surface".into(),
))
}
fn set_accessibility_active(
&mut self,
_active: bool,
) -> Result<Option<SurfaceAccessibilityTreeId>, SurfaceError> {
Err(SurfaceError::Unsupported(
"native accessibility activation is not wired for this surface".into(),
))
}
fn poll_accessibility_update(&mut self) -> Option<SurfaceAccessibilityUpdate> {
None
}
fn request_accessibility_resync(&mut self) -> Result<SurfaceAccessibilityTreeId, SurfaceError> {
Err(SurfaceError::Unsupported(
"native accessibility resynchronization is not wired for this surface".into(),
))
}
fn send_accessibility_action(
&mut self,
_request: SurfaceAccessibilityActionRequest,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"native accessibility action delivery is not wired for this surface".into(),
))
}
fn as_web_surface(&mut self) -> Option<&mut dyn WebSurface> {
None
}
}
pub trait WebSurface: SurfaceProducer {
fn capabilities(&self) -> WebSurfaceCapabilities {
WebSurfaceCapabilities::default()
}
fn document_capabilities(&self) -> DocumentCapabilities {
self.capabilities().document
}
fn request_page_capture(&mut self, _request: PageCaptureRequest) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"page capture is not wired for this web surface".into(),
))
}
fn navigate_to_url(&mut self, url: &str) -> Result<(), SurfaceError>;
fn navigate_to_string(&mut self, html: &str) -> Result<(), SurfaceError>;
fn reload(&mut self) -> Result<(), SurfaceError>;
fn stop(&mut self) -> Result<(), SurfaceError>;
fn go_back(&mut self) -> Result<(), SurfaceError>;
fn go_forward(&mut self) -> Result<(), SurfaceError>;
fn can_go_back(&self) -> bool;
fn can_go_forward(&self) -> bool;
fn document_find(
&mut self,
_query: &DocumentFindQuery,
_direction: DocumentFindDirection,
_find_next: bool,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"document find is not wired for this web surface".into(),
))
}
fn clear_document_find(&mut self) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"document find is not wired for this web surface".into(),
))
}
fn set_cookie(&mut self, cookie: &Cookie) -> Result<(), SurfaceError>;
fn request_cookies_for_url(
&mut self,
_id: WebRequestId,
_url: &str,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"cookie reads are not wired for this web surface".into(),
))
}
fn delete_cookie(&mut self, cookie: &Cookie) -> Result<(), SurfaceError> {
let _ = cookie;
Err(SurfaceError::Unsupported(
"cookie delete is not wired for this web surface".into(),
))
}
fn answer_permission(
&mut self,
_id: UserAgentRequestId,
_answer: PermissionAnswer,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"permission answers are not wired for this web surface".into(),
))
}
fn answer_http_authentication(
&mut self,
_id: UserAgentRequestId,
_answer: &HttpAuthenticationAnswer,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"authentication answers are not wired for this web surface".into(),
))
}
fn request_script_result(
&mut self,
_id: WebRequestId,
_script: &str,
) -> Result<(), SurfaceError> {
Err(SurfaceError::Unsupported(
"script results are not wired for this web surface".into(),
))
}
fn poll_web_event(&mut self) -> Option<WebSurfaceEvent> {
None
}
}
#[derive(Default)]
pub struct SurfaceEngineRegistry {
engines: HashMap<String, Box<dyn SurfaceEngine>>,
}
impl SurfaceEngineRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, engine: Box<dyn SurfaceEngine>) {
let id = engine.engine_id().to_string();
self.engines.insert(id, engine);
}
pub fn engine(&self, id: &str) -> Option<&dyn SurfaceEngine> {
self.engines.get(id).map(|e| e.as_ref())
}
pub fn contains(&self, id: &str) -> bool {
self.engines.contains_key(id)
}
pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
self.engines.keys().map(String::as_str)
}
pub fn spawn_shared(
&self,
decision: &EngineRouteDecision,
request: &SurfaceSpawnRequest,
scope: webcue::Scope,
viewport: webcue::Viewport,
presentation: webcue::PresentationMode,
frames: crate::cue_browser::FrameReader,
) -> webcue::Result<crate::cue_browser::BrowserSurface> {
let producer = self
.spawn(decision, request)
.map_err(|error| webcue::Error::Backend(error.to_string()))?;
crate::cue_browser::BrowserSurface::new(producer, scope, viewport, presentation, frames)
}
#[tracing::instrument(
level = "debug",
skip(self, decision, request),
fields(engine_id = %decision.engine_id, url = %request.url),
)]
pub fn spawn(
&self,
decision: &EngineRouteDecision,
request: &SurfaceSpawnRequest,
) -> Result<Box<dyn SurfaceProducer>, SurfaceError> {
let engine = self.engine(&decision.engine_id).ok_or_else(|| {
tracing::warn!(
engine_id = %decision.engine_id,
"surface engine not registered"
);
SurfaceError::EngineNotFound(decision.engine_id.clone())
})?;
engine.spawn(request)
}
}
#[cfg(test)]
mod tests;