randomPoison / text-edit

1 stars 0 forks source link

Structured serialization/deserialization of RPC messages #3

Open randomPoison opened 7 years ago

randomPoison commented 7 years ago

Currently we've hardcoded the messages being sent to the backend:

let message = match virtual_key_code {
    VirtualKeyCode::Return => Some(r#"{"method":"edit","params":{"method":"insert_newline","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Back => Some(r#"{"method":"edit","params":{"method":"delete_backward","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Delete => Some(r#"{"method":"edit","params":{"method":"delete_forward","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Left => Some(r#"{"method":"edit","params":{"method":"move_left","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Right => Some(r#"{"method":"edit","params":{"method":"move_right","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Up => Some(r#"{"method":"edit","params":{"method":"move_up","params":{},"tab":"0"}}"#),
    VirtualKeyCode::Down => Some(r#"{"method":"edit","params":{"method":"move_down","params":{},"tab":"0"}}"#),
    _ => None,
};

And we manually dig through the JSON in the responses:

let update_value = serde_json::from_str::<Value>(&*message).expect("Failed to parse response json");

// Look for "update" messages.
// TODO: Look for all the other messages xi-core sends.
if let Some(line_data) = update_value.search("lines") {
    for line_contents in line_data.as_array().expect("\"lines\" wasn't an array") {
        let line_contents = line_contents.as_array().expect("Line wasn't an array");
        let line_string = line_contents[0]
            .as_str()
            .expect("First element of line wasn't a string")
            .trim_right()
            .to_string();
    }
}

It would be a vast improvement to use static types to describe the messages we send, and use serde to convert them to and from JSON. Due to the structure of the JSON-PRC 2.0 messages we'll almost certainly need custom serialization/deserialization code.

We should have a look at the other xi frontends to see how much of this work is already done. Some of these types and serialization code live in xi-core, so we might want to make a PR to move them into xi-rpc for more general use.