icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
use std::borrow::Cow;
use std::collections::BTreeMap;

use icedwright_protocol::*;
use icedwright_types::{
    CursorSeen, Point, Rect, Role, ScaleFactor, Size, StateName, StateValue, Vector,
};
use serde::Serialize;
use serde::de::DeserializeOwned;

type TestResult = Result<(), Box<dyn std::error::Error>>;

fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
    Rect::new(Point::new(x, y), Size::new(w, h))
}

fn every_call() -> RawTree {
    let annotation = RawAnnotation {
        source: AnnotationSource::Component,
        role: Some(Role::TreeItem),
        name: Some("Roadmap".to_owned()),
        description: Some("A project".to_owned()),
        tooltip: Some("Open".to_owned()),
        placeholder: None,
        value: Some(RawValue::Number {
            now: 0.5,
            min: Some(0.0),
            max: Some(1.0),
            step: None,
        }),
        test_id: Some("roadmap".to_owned()),
        rust_path: Some("projects::Ids::Roadmap".to_owned()),
        kind: Some(Cow::Borrowed("iced_cube::tree")),
        props: BTreeMap::from([("unsaved".to_owned(), "true".to_owned())]),
        text_size: Some(14.0),
        states: vec![
            (StateName::Expanded, StateValue::Bool(true)),
            (StateName::Checked, StateValue::Mixed),
        ],
        level: Some(2),
        position: Some((1, 3)),
        key: Some(RawKey::Name("roadmap".to_owned())),
        labelled_by: vec![RawKey::Unique(4)],
        label_for: vec![],
        described_by: vec![RawKey::Name("hint".to_owned())],
        controls: vec![RawKey::Unique(5)],
        owns: vec![RawKey::Unique(6)],
        carets: vec![(0, Point::new(1.0, 2.0)), (3, Point::new(9.0, 2.0))],
        cursor_seen: Some(CursorSeen::Levitating),
    };
    let base = RawNode::new(RawCall::Container, rect(0.0, 0.0, 800.0, 600.0))
        .with_id(WidgetId::Custom("main".to_owned()))
        .with_children([
            RawNode::new(
                RawCall::Scrollable {
                    content_bounds: rect(0.0, 0.0, 800.0, 2000.0),
                    translation: Vector::new(0.0, 300.0),
                    ordinal: 0,
                },
                rect(0.0, 0.0, 800.0, 600.0),
            ),
            RawNode::new(
                RawCall::TextInput {
                    text: "Search".to_owned(),
                },
                rect(10.0, 10.0, 200.0, 30.0),
            )
            .with_id(WidgetId::Unique(7)),
            RawNode::new(
                RawCall::Focusable {
                    focused: true,
                    ordinal: 0,
                },
                rect(10.0, 10.0, 200.0, 30.0),
            ),
            RawNode::new(
                RawCall::Text {
                    content: "Hello".to_owned(),
                },
                rect(10.0, 50.0, 60.0, 20.0),
            ),
            RawNode::new(
                RawCall::Annotation(Box::new(annotation)),
                rect(10.0, 80.0, 100.0, 20.0),
            ),
            RawNode::new(RawCall::Group, rect(0.0, 0.0, 0.0, 0.0)),
        ]);
    let overlay = RawNode::new(RawCall::Overlay { depth: 1 }, rect(0.0, 0.0, 800.0, 600.0));
    let root =
        RawNode::new(RawCall::Group, rect(0.0, 0.0, 800.0, 600.0)).with_children([base, overlay]);
    RawTree {
        windows: vec![RawWindow {
            id: Some(WindowId(0)),
            info: Some(RawWindowInfo {
                id: WindowId(0),
                title: "Todo".to_owned(),
                size: Size::new(800.0, 600.0),
                scale_factor: ScaleFactor::default(),
            }),
            root,
        }],
    }
}

fn round_trip<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(
    value: &T,
) -> TestResult {
    let json = serde_json::to_string(value)?;
    let back: T = serde_json::from_str(&json)?;
    assert_eq!(&back, value, "{json}");
    Ok(())
}

#[test]
fn a_raw_tree_with_every_call_round_trips() -> TestResult {
    round_trip(&every_call())
}

#[test]
fn an_unknown_role_reads_as_unknown() -> TestResult {
    let json = r#"{"call":"annotation","role":"hologram"}"#;
    let call: RawCall = serde_json::from_str(json)?;
    let RawCall::Annotation(annotation) = call else {
        panic!("not an annotation: {call:?}");
    };
    assert_eq!(annotation.role, Some(Role::Unknown));
    Ok(())
}

#[test]
fn unknown_fields_are_ignored_and_missing_ones_default() -> TestResult {
    let json = r#"{"protocol":[1,4],"client":"other 2.0","from_the_future":true}"#;
    let hello: Hello = serde_json::from_str(json)?;
    assert_eq!(
        hello,
        Hello {
            protocol: (1, 4),
            client: "other 2.0".to_owned(),
            os_keyboard: false,
        }
    );
    let node: RawNode = serde_json::from_str(
        r#"{"call":"container","bounds":{"x":0,"y":0,"width":1,"height":1},"extra":1}"#,
    )?;
    assert!(node.children.is_empty());
    Ok(())
}

#[test]
fn a_test_id_without_a_rust_path_reads_as_a_string_id() -> TestResult {
    let older: RawAnnotation = serde_json::from_str(r#"{"test_id":"save"}"#)?;
    assert_eq!(older.test_id.as_deref(), Some("save"));
    assert_eq!(older.rust_path, None);
    let typed: RawAnnotation =
        serde_json::from_str(r#"{"test_id":"save","rust_path":"notes::Ids::Save"}"#)?;
    assert_eq!(typed.rust_path.as_deref(), Some("notes::Ids::Save"));
    Ok(())
}

fn check_request<R: Request + PartialEq + std::fmt::Debug + Clone>(
    request: R,
    response: R::Response,
) -> TestResult
where
    R::Response: PartialEq + std::fmt::Debug,
{
    let call = Call::new(RequestId(3), request.clone());
    assert_eq!(call.method, R::METHOD);
    let json = serde_json::to_value(&call)?;
    assert_eq!(json["method"], R::METHOD);
    let parsed = AnyRequest::from_params(R::METHOD, &json["params"])?;
    assert_eq!(parsed.as_ref().map(AnyRequest::method), Some(R::METHOD));

    let reply = Reply {
        id: RequestId(3),
        body: ReplyBody::Result(response),
    };
    let text = serde_json::to_string(&reply)?;
    let back: Reply<R::Response> = serde_json::from_str(&text)?;
    assert_eq!(back, reply, "{text}");
    Ok(())
}

#[test]
fn every_request_round_trips_in_its_envelope() -> TestResult {
    let window = WindowOrdinal(0);
    let info = RawWindowInfo {
        id: WindowId(0),
        title: "Remote demo".to_owned(),
        size: Size::new(1280.0, 820.0),
        scale_factor: ScaleFactor::default(),
    };
    check_request(
        Hello {
            protocol: PROTOCOL,
            client: "icedwright-remote 0.1.0".to_owned(),
            os_keyboard: false,
        },
        Welcome {
            protocol: PROTOCOL,
            app: "remote-demo".to_owned(),
            pid: 4242,
            iced: "0.14.0".to_owned(),
            semantics: true,
            windows: vec![info.clone()],
        },
    )?;
    check_request(
        Snapshot {
            after: Some(Generation(4)),
            wait: Some(WireDuration(30_000)),
        },
        SnapshotReply::Tree {
            generation: Generation(5),
            frame: FrameCount(9),
            tree: every_call(),
        },
    )?;
    check_request(Snapshot::default(), SnapshotReply::Unchanged)?;
    check_request(
        Input {
            window,
            events: vec![WireEvent::CursorMoved {
                position: Point::new(3.0, 4.0),
            }],
            guard: Some(Guard {
                generation: Generation(5),
                path: "window \"Todo\" / button \"Add\"".to_owned(),
                bounds: rect(1.0, 2.0, 3.0, 4.0),
            }),
        },
        Delivered {
            window,
            generation: Generation(6),
            statuses: vec![WireStatus::Captured],
            cursors: vec![CursorReading {
                layer: 0,
                seen: CursorSeen::Available,
            }],
        },
    )?;
    check_request(
        Screenshot { window },
        ScreenshotHeader {
            window,
            width: 1280,
            height: 820,
            scale_factor: ScaleFactor::default(),
        },
    )?;
    check_request(
        Windows,
        WindowList {
            windows: vec![info],
        },
    )?;
    check_request(Focus { window }, Done)?;
    check_request(
        Drive {
            window,
            exclusive_pointer: true,
        },
        Done,
    )?;
    check_request(Release { window }, Done)?;
    check_request(Inspect { window, on: true }, Done)?;
    check_request(Record { on: false }, Done)?;
    check_request(
        HoldTask {
            name: "remote_demo::Load".to_owned(),
        },
        WireRuleId(1),
    )?;
    check_request(
        RemoveRule {
            rule: WireRuleId(1),
        },
        Done,
    )?;
    check_request(
        NextTask {
            name: "remote_demo::Load".to_owned(),
            wait: None,
        },
        WireTaskId(2),
    )?;
    check_request(
        ReleaseTask {
            name: "remote_demo::Load".to_owned(),
            task: WireTaskId(2),
        },
        Done,
    )?;
    check_request(
        ResolveTask {
            name: "remote_demo::Load".to_owned(),
            task: WireTaskId(2),
            output: TaskOutput::Value("\"Loaded\"".to_owned()),
        },
        Done,
    )?;
    check_request(Bye, Done)?;
    check_request(
        WaitIdle {
            wait: Some(WireDuration::from(std::time::Duration::from_secs(1))),
        },
        Done,
    )?;
    assert_eq!(METHODS.len(), 17);
    Ok(())
}

#[test]
fn an_unknown_method_parses_to_none() -> TestResult {
    let params = serde_json::json!({});
    assert_eq!(AnyRequest::from_params("teleport", &params)?, None);
    Ok(())
}

#[test]
fn a_request_of_the_wrong_shape_is_an_error() {
    let params = serde_json::json!({ "window": "first" });
    assert!(AnyRequest::from_params(Focus::METHOD, &params).is_err());
}

#[test]
fn error_replies_read_as_protocol_errors() -> TestResult {
    let text = r#"{"id":7,"error":{"code":"stale","message":"the node moved"}}"#;
    let reply: Reply<Done> = serde_json::from_str(text)?;
    assert_eq!(reply.id, RequestId(7));
    assert_eq!(
        reply.body.into_result(),
        Err(ProtocolError::Reply {
            code: ErrorCode::Stale,
            message: "the node moved".to_owned(),
        })
    );
    Ok(())
}

#[test]
fn any_response_serialises_as_the_response_itself() -> TestResult {
    let response = AnyResponse::HoldTask(WireRuleId(9));
    assert_eq!(response.method(), HoldTask::METHOD);
    assert_eq!(serde_json::to_string(&response)?, "9");
    assert_eq!(serde_json::to_string(&AnyResponse::Bye(Done))?, "null");
    Ok(())
}

#[test]
fn notifications_round_trip() -> TestResult {
    let notifications = [
        Notification::Generation {
            generation: Generation(1),
            frame: FrameCount(2),
        },
        Notification::Hovered {
            path: "0.0.2".to_owned(),
            tree: every_call(),
            picked: true,
        },
        Notification::Observed {
            generation: Generation(1),
            window: WindowOrdinal(0),
            event: WireEvent::WindowFocused,
            status: WireStatus::Ignored,
        },
        Notification::Task {
            name: "load".to_owned(),
            task: WireTaskId(1),
            change: TaskChange::Failed {
                error: "gone".to_owned(),
            },
        },
        Notification::WindowOpened(RawWindowInfo {
            id: WindowId(1),
            title: "Second".to_owned(),
            size: Size::new(10.0, 10.0),
            scale_factor: ScaleFactor::default(),
        }),
        Notification::WindowClosed {
            window: WindowOrdinal(1),
        },
    ];
    for notification in &notifications {
        round_trip(notification)?;
    }
    let json = serde_json::to_value(&notifications[0])?;
    assert_eq!(json["event"], "generation");
    Ok(())
}