use crate::error::{BrowserError, Result};
use crate::page::ObservedNode;
use crate::policy::ActionKind;
use serde::Serialize;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
pub const DEFAULT_ACTION_LOOP_LIMIT: u32 = 5;
#[derive(Clone, Debug, PartialEq)]
pub enum RefAction {
Click,
DoubleClick,
Hover,
Fill {
text: String,
clear: bool,
},
SelectOption {
value: String,
},
}
impl RefAction {
pub(crate) fn admission(&self) -> (ActionKind, Option<String>) {
match self {
RefAction::Click => (ActionKind::Click, None),
RefAction::DoubleClick => (ActionKind::DoubleClick, None),
RefAction::Hover => (ActionKind::Hover, None),
RefAction::Fill { text, clear } => (
ActionKind::Fill,
Some(format!("chars={} clear={clear}", text.chars().count())),
),
RefAction::SelectOption { value } => {
(ActionKind::Select, Some(format!("value={value}")))
}
}
}
pub(crate) fn watch_key(&self, node_ref: &str) -> String {
let what = match self {
RefAction::Click => "click".to_string(),
RefAction::DoubleClick => "double_click".to_string(),
RefAction::Hover => "hover".to_string(),
RefAction::Fill { text, clear } => format!("fill:{clear}:{}", hash_of(text)),
RefAction::SelectOption { value } => format!("select:{}", hash_of(value)),
};
format!("{node_ref}|{what}")
}
}
fn hash_of(text: &str) -> u64 {
let mut h = DefaultHasher::new();
text.hash(&mut h);
h.finish()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct NodeState {
pub role: String,
pub name: String,
pub visible: bool,
pub disabled: bool,
}
impl NodeState {
pub(crate) fn of(node: &ObservedNode) -> NodeState {
NodeState {
role: node.role.clone(),
name: node.name.clone(),
visible: node.visible,
disabled: node.disabled,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct NodeChange {
pub node_ref: String,
pub selector: String,
pub before: NodeState,
pub after: NodeState,
}
#[derive(Clone, Debug, Serialize)]
pub struct ObservationDiff {
pub epoch_before: u64,
pub epoch_after: u64,
pub url_before: String,
pub url_after: String,
pub document_replaced: bool,
pub added: Vec<ObservedNode>,
pub removed: Vec<String>,
pub changed: Vec<NodeChange>,
}
impl ObservationDiff {
pub fn is_empty(&self) -> bool {
!self.document_replaced
&& self.url_before == self.url_after
&& self.added.is_empty()
&& self.removed.is_empty()
&& self.changed.is_empty()
}
}
#[derive(Clone, Debug, Serialize)]
pub struct ActResult {
pub page_id: String,
pub node_ref: String,
pub epoch: u64,
pub diff: ObservationDiff,
pub repeats: u32,
}
#[derive(Debug)]
pub(crate) struct ActionWatch {
limit: u32,
last: Option<String>,
repeats: u32,
stopped: bool,
}
impl Default for ActionWatch {
fn default() -> Self {
ActionWatch {
limit: DEFAULT_ACTION_LOOP_LIMIT,
last: None,
repeats: 0,
stopped: false,
}
}
}
impl ActionWatch {
pub(crate) fn set_limit(&mut self, limit: u32) -> Result<()> {
if limit == 0 {
return Err(BrowserError::Invalid(
"the action-loop limit must be at least 1".into(),
));
}
self.limit = limit;
Ok(())
}
pub(crate) fn reset(&mut self) {
self.last = None;
self.repeats = 0;
self.stopped = false;
}
pub(crate) fn before(&mut self, key: &str) -> Result<()> {
if self.stopped {
return Err(BrowserError::ActionLoop(format!(
"the run was stopped after {} identical actions with no effect",
self.limit
)));
}
if self.last.as_deref() == Some(key) && self.repeats >= self.limit {
self.stopped = true;
return Err(BrowserError::ActionLoop(format!(
"the same action on the same element ran {} times with no effect",
self.repeats
)));
}
Ok(())
}
pub(crate) fn after(&mut self, key: String, no_effect: bool) -> u32 {
if !no_effect {
self.last = None;
self.repeats = 0;
} else if self.last.as_deref() == Some(key.as_str()) {
self.repeats = self.repeats.saturating_add(1);
} else {
self.last = Some(key);
self.repeats = 1;
}
self.repeats
}
}