use std::sync::Arc;
use std::time::Duration;
use adk_core::{Tool, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use super::capture::{Capture, interval_frames, observation_image};
use super::{FrameSource, FrameStream};
use crate::error::Result;
use crate::media::FrameSourceId;
use crate::traits::Sampling;
struct ScreenshotTool {
tool: Arc<dyn Tool>,
ctx: Arc<dyn ToolContext>,
selector: Option<String>,
}
#[async_trait]
impl Capture for ScreenshotTool {
async fn capture(&self) -> Result<Vec<u8>> {
let args = match &self.selector {
Some(selector) => json!({ "selector": selector }),
None => Value::Object(serde_json::Map::new()),
};
let result = self.tool.execute(Arc::clone(&self.ctx), args).await?;
Ok(observation_image(&result)?.0)
}
}
pub struct BrowserSource {
id: FrameSourceId,
tool: Arc<dyn Tool>,
ctx: Arc<dyn ToolContext>,
selector: Option<String>,
interval: Duration,
}
impl std::fmt::Debug for BrowserSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrowserSource")
.field("id", &self.id)
.field("tool", &self.tool.name())
.field("selector", &self.selector)
.field("interval", &self.interval)
.finish_non_exhaustive()
}
}
impl BrowserSource {
pub fn new(id: FrameSourceId, tool: Arc<dyn Tool>, ctx: Arc<dyn ToolContext>) -> Self {
Self { id, tool, ctx, selector: None, interval: Duration::from_secs(1) }
}
pub fn with_selector(mut self, selector: impl Into<String>) -> Self {
self.selector = Some(selector.into());
self
}
pub fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
}
#[async_trait]
impl FrameSource for BrowserSource {
fn id(&self) -> &FrameSourceId {
&self.id
}
async fn frames(&self, sampling: Sampling) -> Result<FrameStream> {
let capture = Arc::new(ScreenshotTool {
tool: Arc::clone(&self.tool),
ctx: Arc::clone(&self.ctx),
selector: self.selector.clone(),
});
interval_frames(self.id.clone(), capture, self.interval, sampling)
}
}