use std::sync::Arc;
use std::time::Duration;
use adk_core::{ActuationOutput, ComputerAction, ComputerActuator};
use async_trait::async_trait;
use serde_json::Value;
use super::capture::{Capture, interval_frames, observation_image};
use super::{FrameSource, FrameStream};
use crate::error::{Result, VisionError};
use crate::media::FrameSourceId;
use crate::traits::Sampling;
#[async_trait]
pub trait VisualObserver: Send + Sync {
async fn observe_visual(&self) -> adk_core::Result<Value>;
}
struct FromActuator(Arc<dyn ComputerActuator>);
#[async_trait]
impl Capture for FromActuator {
async fn capture(&self) -> Result<Vec<u8>> {
match self.0.perform(ComputerAction::Screenshot).await? {
ActuationOutput::Image(shot) => Ok(shot.data),
other => Err(VisionError::Backend {
backend: "screen".into(),
message: format!("the actuator answered a screenshot with {other:?}"),
}),
}
}
}
struct FromObserver(Arc<dyn VisualObserver>);
#[async_trait]
impl Capture for FromObserver {
async fn capture(&self) -> Result<Vec<u8>> {
let observation = self.0.observe_visual().await?;
Ok(observation_image(&observation)?.0)
}
}
pub struct ScreenSource {
id: FrameSourceId,
capture: Arc<dyn Capture>,
interval: Duration,
}
impl std::fmt::Debug for ScreenSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScreenSource")
.field("id", &self.id)
.field("interval", &self.interval)
.finish_non_exhaustive()
}
}
impl ScreenSource {
pub fn from_actuator(id: FrameSourceId, actuator: Arc<dyn ComputerActuator>) -> Self {
Self { id, capture: Arc::new(FromActuator(actuator)), interval: Duration::from_secs(1) }
}
pub fn from_observer(id: FrameSourceId, observer: Arc<dyn VisualObserver>) -> Self {
Self { id, capture: Arc::new(FromObserver(observer)), interval: Duration::from_secs(1) }
}
pub fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
}
#[async_trait]
impl FrameSource for ScreenSource {
fn id(&self) -> &FrameSourceId {
&self.id
}
async fn frames(&self, sampling: Sampling) -> Result<FrameStream> {
interval_frames(self.id.clone(), Arc::clone(&self.capture), self.interval, sampling)
}
}