use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::fit::ScreenshotScale;
use super::marks::{GroundedTarget, MarkSet, same_label};
use crate::digest::Digest;
use crate::geometry::BBox;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreviewedTarget {
pub screenshot: Digest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
pub points: BBox,
pub click: [f32; 2],
}
impl From<&GroundedTarget> for PreviewedTarget {
fn from(target: &GroundedTarget) -> Self {
Self {
screenshot: target.screenshot,
window: target.window.clone(),
label: target.label.clone(),
points: target.points,
click: target.click,
}
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Deviation {
Window {
expected: Option<String>,
found: Option<String>,
},
Missing {
label: Option<String>,
},
WrongTarget {
expected: BBox,
found: BBox,
label: Option<String>,
},
ArgumentsChanged {
call_id: String,
},
NotInPlan {
call_id: String,
},
}
impl fmt::Display for Deviation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Window { expected, found } => write!(
f,
"the screen shows window {} but the plan was approved for {}; the action is held again",
found.as_deref().unwrap_or("(unknown)"),
expected.as_deref().unwrap_or("(unknown)")
),
Self::Missing { label } => write!(
f,
"no {} is at the previewed point any more; the action is held again",
label.as_deref().map_or("target".to_string(), |l| format!("\"{l}\""))
),
Self::WrongTarget { expected, found, label } => write!(
f,
"the action would hit {} at ({:.0}, {:.0})-({:.0}, {:.0}) pt, not the previewed \
target at ({:.0}, {:.0})-({:.0}, {:.0}) pt; ground it again",
label.as_deref().map_or("a target".to_string(), |l| format!("\"{l}\"")),
found.x0,
found.y0,
found.x1,
found.y1,
expected.x0,
expected.y0,
expected.x1,
expected.y1
),
Self::ArgumentsChanged { call_id } => write!(
f,
"call {call_id} changed its arguments after the plan was approved; it is held again"
),
Self::NotInPlan { call_id } => {
write!(f, "call {call_id} is not in the approved plan; it is held on its own")
}
}
}
}
impl std::error::Error for Deviation {}
impl PreviewedTarget {
fn window_matches(&self, fresh: &MarkSet) -> Result<(), Deviation> {
match (&self.window, &fresh.window) {
(Some(expected), Some(found)) if expected != found => Err(Deviation::Window {
expected: Some(expected.clone()),
found: Some(found.clone()),
}),
_ => Ok(()),
}
}
pub fn check(&self, fresh: &MarkSet, mark: u32) -> Result<GroundedTarget, Deviation> {
self.window_matches(fresh)?;
let candidate =
fresh.candidate(mark).ok_or(Deviation::Missing { label: self.label.clone() })?;
let target = fresh.target_of(candidate);
if same_label(target.label.as_deref(), self.label.as_deref())
&& target.points.contains(self.click)
&& self.points.contains(target.click)
{
Ok(target)
} else {
Err(Deviation::WrongTarget {
expected: self.points,
found: target.points,
label: target.label,
})
}
}
pub fn reground(&self, fresh: &MarkSet) -> Result<GroundedTarget, Deviation> {
self.window_matches(fresh)?;
fresh
.candidates
.iter()
.filter(|c| {
self.label.is_none() || same_label(c.label.as_deref(), self.label.as_deref())
})
.filter(|c| fresh.screen.bbox_to_points(&c.region).contains(self.click))
.min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
.map(|c| fresh.target_of(c))
.ok_or(Deviation::Missing { label: self.label.clone() })
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum PlanRefusal {
TooManyActions {
max: usize,
},
OtherWindow {
plan: Option<String>,
step: Option<String>,
},
OtherScreenshot,
}
impl fmt::Display for PlanRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TooManyActions { max } => {
write!(
f,
"a screen plan holds at most {max} actions; preview the rest as a new plan"
)
}
Self::OtherWindow { plan, step } => write!(
f,
"a screen plan stays in one window: this step is in {}, the plan in {}",
step.as_deref().unwrap_or("(unknown)"),
plan.as_deref().unwrap_or("(unknown)")
),
Self::OtherScreenshot => {
write!(f, "every step of a screen plan is grounded on the plan's screenshot")
}
}
}
}
impl std::error::Error for PlanRefusal {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlanStep {
pub call_id: String,
pub action: String,
pub args: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<PreviewedTarget>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScreenPlan {
pub screenshot: Digest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<String>,
pub max_actions: usize,
pub steps: Vec<PlanStep>,
}
impl ScreenPlan {
pub const DEFAULT_MAX_ACTIONS: usize = 10;
pub fn new(marks: &MarkSet) -> Self {
Self {
screenshot: marks.screenshot,
window: marks.window.clone(),
max_actions: Self::DEFAULT_MAX_ACTIONS,
steps: Vec::new(),
}
}
#[must_use]
pub fn with_max_actions(mut self, max: usize) -> Self {
self.max_actions = max.max(1);
self
}
pub fn push(
&mut self,
call_id: impl Into<String>,
action: impl Into<String>,
args: Value,
target: Option<&GroundedTarget>,
) -> Result<(), PlanRefusal> {
if self.steps.len() >= self.max_actions {
return Err(PlanRefusal::TooManyActions { max: self.max_actions });
}
if let Some(target) = target {
if target.window != self.window {
return Err(PlanRefusal::OtherWindow {
plan: self.window.clone(),
step: target.window.clone(),
});
}
if target.screenshot != self.screenshot {
return Err(PlanRefusal::OtherScreenshot);
}
}
self.steps.push(PlanStep {
call_id: call_id.into(),
action: action.into(),
args,
target: target.map(PreviewedTarget::from),
});
Ok(())
}
pub fn from_toolset_calls(
marks: &MarkSet,
scale: &ScreenshotScale,
calls: &[(String, String, Value)],
) -> Result<Self, PlanRefusal> {
let mut plan = Self::new(marks);
for (call_id, member, args) in calls {
let target = args
.get("coordinate")
.and_then(Value::as_array)
.and_then(|pair| {
Some([pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32])
})
.and_then(|point| {
let at = scale.to_source([point[0] + 0.5, point[1] + 0.5]);
marks
.candidates
.iter()
.filter(|c| c.region.contains(at))
.min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
.map(|c| marks.target_of(c))
});
plan.push(call_id.clone(), member.clone(), args.clone(), target.as_ref())?;
}
Ok(plan)
}
pub fn digest(&self) -> Digest {
Digest::of_json(self)
}
pub fn step(&self, call_id: &str) -> Option<&PlanStep> {
self.steps.iter().find(|step| step.call_id == call_id)
}
pub fn approved_args(&self, call_id: &str) -> Option<Value> {
let step = self.step(call_id)?;
let mut args = step.args.clone();
if let Value::Object(map) = &mut args {
map.insert(
"expect_target".into(),
json!({ "plan": self.digest(), "target": step.target }),
);
}
Some(args)
}
pub fn check_call(
&self,
call_id: &str,
args: &Value,
fresh: &MarkSet,
) -> Result<Option<GroundedTarget>, Deviation> {
let step = self.step(call_id).ok_or(Deviation::NotInPlan { call_id: call_id.into() })?;
let mut bare = args.clone();
if let Value::Object(map) = &mut bare {
map.remove("expect_target");
}
if bare != step.args {
return Err(Deviation::ArgumentsChanged { call_id: call_id.into() });
}
if let (Some(expected), Some(found)) = (&self.window, &fresh.window)
&& expected != found
{
return Err(Deviation::Window {
expected: Some(expected.clone()),
found: Some(found.clone()),
});
}
step.target.as_ref().map(|target| target.reground(fresh)).transpose()
}
pub fn render(&self) -> String {
let mut out = format!(
"{} action(s) in {} on screenshot {}:",
self.steps.len(),
self.window.as_deref().unwrap_or("the current window"),
self.screenshot
);
for (i, step) in self.steps.iter().enumerate() {
out.push_str(&format!("\n{}. {}", i + 1, step.action));
if let Some(target) = &step.target {
out.push_str(&format!(
" on {} at ({:.0}, {:.0}) pt",
target.label.as_deref().map_or("a point".to_string(), |l| format!("\"{l}\"")),
target.click[0],
target.click[1]
));
} else if let Some(text) = step.args.get("text").and_then(Value::as_str) {
out.push_str(&format!(" \"{text}\""));
}
}
out
}
}