use crate::anchor::Anchor;
use crate::geom::{DisplayId, LogicalPoint, LogicalRect};
use crate::ids::AnnotationId;
use crate::position::Position;
use crate::validate::{Validate, ValidationError};
use serde::{Deserialize, Serialize};
fn is_false(b: &bool) -> bool {
!*b
}
fn validate_ttl(ttl_ms: Option<u64>) -> Result<(), ValidationError> {
match ttl_ms {
Some(0) => Err(ValidationError::ZeroTtl),
_ => Ok(()),
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientMessage {
SessionStart(SessionStart),
Point(Point),
Highlight(Highlight),
Textbox(Textbox),
Draw(Draw),
Arrow(Arrow),
Clear(Clear),
Focus(Focus),
AwaitWindow(AwaitWindow),
SessionEnd,
}
impl Validate for ClientMessage {
fn validate(&self) -> Result<(), ValidationError> {
match self {
Self::SessionStart(m) => m.validate(),
Self::Point(m) => m.validate(),
Self::Highlight(m) => m.validate(),
Self::Textbox(m) => m.validate(),
Self::Draw(m) => m.validate(),
Self::Arrow(m) => m.validate(),
Self::Clear(m) => m.validate(),
Self::Focus(m) => m.validate(),
Self::AwaitWindow(m) => m.validate(),
Self::SessionEnd => Ok(()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Focus {
pub app: String,
}
impl Validate for Focus {
fn validate(&self) -> Result<(), ValidationError> {
if self.app.trim().is_empty() {
return Err(ValidationError::Empty { field: "app" });
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AwaitWindow {
pub app: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_ms: Option<u64>,
}
impl Validate for AwaitWindow {
fn validate(&self) -> Result<(), ValidationError> {
if self.app.trim().is_empty() {
return Err(ValidationError::Empty { field: "app" });
}
if self.timeout_ms == Some(0) {
return Err(ValidationError::ZeroTtl);
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionStart {
pub client_name: String,
}
impl Validate for SessionStart {
fn validate(&self) -> Result<(), ValidationError> {
if self.client_name.trim().is_empty() {
return Err(ValidationError::Empty {
field: "client_name",
});
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Point {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub y: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<String>,
pub display_id: DisplayId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_ms: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PointTarget<'a> {
Coords(LogicalPoint),
Named(Position),
Query(&'a str),
}
impl Point {
pub const fn at(x: f64, y: f64, display_id: DisplayId) -> Self {
Self {
x: Some(x),
y: Some(y),
at: None,
query: None,
display_id,
label: None,
ttl_ms: None,
}
}
pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
Self {
x: None,
y: None,
at: None,
query: Some(query.into()),
display_id,
label: None,
ttl_ms: None,
}
}
pub fn named(at: impl Into<String>, display_id: DisplayId) -> Self {
Self {
x: None,
y: None,
at: Some(at.into()),
query: None,
display_id,
label: None,
ttl_ms: None,
}
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
self.ttl_ms = ttl_ms;
self
}
pub fn target(&self) -> Result<PointTarget<'_>, ValidationError> {
const EXPECTED: &str = "x and y, or at, or query";
let coords = self.x.is_some() || self.y.is_some();
let named = self.at.is_some();
let queried = self.query.is_some();
match (coords, named, queried) {
(false, false, false) => {
return Err(ValidationError::MissingTarget {
message: "point",
expected: EXPECTED,
});
}
(true, true, _) | (true, _, true) | (_, true, true) => {
return Err(ValidationError::AmbiguousTarget {
message: "point",
expected: EXPECTED,
});
}
_ => {}
}
if let Some(at) = self.at.as_deref() {
return Position::parse(at).map(PointTarget::Named);
}
if let Some(query) = self.query.as_deref() {
return if query.trim().is_empty() {
Err(ValidationError::Empty { field: "query" })
} else {
Ok(PointTarget::Query(query))
};
}
match (self.x, self.y) {
(Some(x), Some(y)) => {
let p = LogicalPoint::new(x, y);
if !p.is_finite() {
return Err(ValidationError::NonFiniteCoordinate { field: "x, y" });
}
Ok(PointTarget::Coords(p))
}
_ => Err(ValidationError::AmbiguousTarget {
message: "point",
expected: EXPECTED,
}),
}
}
}
impl Validate for Point {
fn validate(&self) -> Result<(), ValidationError> {
validate_ttl(self.ttl_ms)?;
self.target().map(|_| ())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Highlight {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rect: Option<LogicalRect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<String>,
pub display_id: DisplayId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_ms: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HighlightTarget<'a> {
Rect(LogicalRect),
Query(&'a str),
}
impl Highlight {
pub const fn over(rect: LogicalRect, display_id: DisplayId) -> Self {
Self {
rect: Some(rect),
query: None,
display_id,
label: None,
ttl_ms: None,
}
}
pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
Self {
rect: None,
query: Some(query.into()),
display_id,
label: None,
ttl_ms: None,
}
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
self.ttl_ms = ttl_ms;
self
}
pub fn target(&self) -> Result<HighlightTarget<'_>, ValidationError> {
const EXPECTED: &str = "rect or query";
match (self.rect, self.query.as_deref()) {
(Some(rect), None) => {
if !rect.is_valid() {
return Err(ValidationError::InvalidRect { field: "rect" });
}
Ok(HighlightTarget::Rect(rect))
}
(None, Some(q)) if !q.trim().is_empty() => Ok(HighlightTarget::Query(q)),
(None, Some(_)) => Err(ValidationError::Empty { field: "query" }),
(None, None) => Err(ValidationError::MissingTarget {
message: "highlight",
expected: EXPECTED,
}),
(Some(_), Some(_)) => Err(ValidationError::AmbiguousTarget {
message: "highlight",
expected: EXPECTED,
}),
}
}
}
impl Validate for Highlight {
fn validate(&self) -> Result<(), ValidationError> {
validate_ttl(self.ttl_ms)?;
self.target().map(|_| ())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Textbox {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub anchor: Option<Anchor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rect: Option<LogicalRect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_id: Option<DisplayId>,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub style: Option<TextboxStyle>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_ms: Option<u64>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextboxStyle {
#[default]
Note,
Guide,
}
impl Textbox {
pub fn new(anchor: Anchor, text: impl Into<String>) -> Self {
Self {
anchor: Some(anchor),
rect: None,
display_id: None,
text: text.into(),
style: None,
ttl_ms: None,
}
}
#[must_use]
pub fn with_style(mut self, style: TextboxStyle) -> Self {
self.style = Some(style);
self
}
#[must_use]
pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
self.ttl_ms = ttl_ms;
self
}
pub fn resolved_anchor(&self) -> Result<Anchor, ValidationError> {
const EXPECTED: &str = "anchor, or rect with display_id";
match (&self.anchor, self.rect, self.display_id) {
(Some(anchor), None, None) => {
if !anchor.screen_rect.is_valid() {
return Err(ValidationError::InvalidRect {
field: "anchor.screen_rect",
});
}
Ok(anchor.clone())
}
(None, Some(rect), Some(display_id)) => {
if !rect.is_valid() {
return Err(ValidationError::InvalidRect { field: "rect" });
}
Ok(Anchor::new(rect, display_id))
}
(None, None, _) => Err(ValidationError::MissingTarget {
message: "textbox",
expected: EXPECTED,
}),
_ => Err(ValidationError::AmbiguousTarget {
message: "textbox",
expected: EXPECTED,
}),
}
}
}
impl Validate for Textbox {
fn validate(&self) -> Result<(), ValidationError> {
validate_ttl(self.ttl_ms)?;
if self.text.trim().is_empty() {
return Err(ValidationError::Empty { field: "text" });
}
self.resolved_anchor().map(|_| ())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Draw {
pub display_id: DisplayId,
pub path: Vec<[f64; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub style: Option<StrokeStyle>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_ms: Option<u64>,
}
impl Draw {
pub fn new(display_id: DisplayId, path: Vec<[f64; 2]>) -> Self {
Self {
display_id,
path,
style: None,
ttl_ms: None,
}
}
#[must_use]
pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
self.ttl_ms = ttl_ms;
self
}
pub fn points(&self) -> impl Iterator<Item = LogicalPoint> + '_ {
self.path.iter().map(|&[x, y]| LogicalPoint::new(x, y))
}
}
impl Validate for Draw {
fn validate(&self) -> Result<(), ValidationError> {
validate_ttl(self.ttl_ms)?;
if self.path.len() < 2 {
return Err(ValidationError::PathTooShort {
got: self.path.len(),
});
}
if !self.points().all(|p| p.is_finite()) {
return Err(ValidationError::NonFiniteCoordinate { field: "path" });
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StrokeStyle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Arrow {
pub display_id: DisplayId,
pub from: ArrowEnd,
pub to: ArrowEnd,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bow: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub style: Option<StrokeStyle>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_ms: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
untagged,
expecting = "an [x, y] pair, or a position like `top-left` or `50%,30%`"
)]
pub enum ArrowEnd {
Coords([f64; 2]),
Named(String),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ArrowTarget {
Coords(LogicalPoint),
Named(Position),
}
impl ArrowEnd {
pub const fn coords(x: f64, y: f64) -> Self {
Self::Coords([x, y])
}
pub fn named(at: impl Into<String>) -> Self {
Self::Named(at.into())
}
pub fn target(&self) -> Result<ArrowTarget, ValidationError> {
match self {
Self::Coords([x, y]) => {
let p = LogicalPoint::new(*x, *y);
if !p.is_finite() {
return Err(ValidationError::NonFiniteCoordinate { field: "from, to" });
}
Ok(ArrowTarget::Coords(p))
}
Self::Named(at) => Position::parse(at).map(ArrowTarget::Named),
}
}
}
impl Arrow {
pub fn new(display_id: DisplayId, from: ArrowEnd, to: ArrowEnd) -> Self {
Self {
display_id,
from,
to,
bow: None,
style: None,
ttl_ms: None,
}
}
#[must_use]
pub fn with_bow(mut self, bow: f64) -> Self {
self.bow = Some(bow);
self
}
#[must_use]
pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
self.ttl_ms = ttl_ms;
self
}
}
impl Validate for Arrow {
fn validate(&self) -> Result<(), ValidationError> {
validate_ttl(self.ttl_ms)?;
let from = self.from.target()?;
let to = self.to.target()?;
if from == to {
return Err(ValidationError::ZeroLengthArrow);
}
if let Some(bow) = self.bow {
if !bow.is_finite() || bow.abs() > 1.0 {
return Err(ValidationError::BowOutOfRange {
got: bow.to_string(),
});
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Clear {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub annotation_id: Option<AnnotationId>,
#[serde(default, skip_serializing_if = "is_false")]
pub all: bool,
}
impl Clear {
pub const fn all() -> Self {
Self {
annotation_id: None,
all: true,
}
}
pub const fn one(annotation_id: AnnotationId) -> Self {
Self {
annotation_id: Some(annotation_id),
all: false,
}
}
}
impl Validate for Clear {
fn validate(&self) -> Result<(), ValidationError> {
const EXPECTED: &str = "annotation_id or all";
match (&self.annotation_id, self.all) {
(Some(_), false) | (None, true) => Ok(()),
(None, false) => Err(ValidationError::MissingTarget {
message: "clear",
expected: EXPECTED,
}),
(Some(_), true) => Err(ValidationError::AmbiguousTarget {
message: "clear",
expected: EXPECTED,
}),
}
}
}