use tilo_actions::ActionAddress;
pub use tilo_ui_graph::rich;
use serde::{Deserialize, Serialize};
use crate::WireError;
pub mod diff;
pub mod local;
#[cfg(windows)]
pub mod pipe;
#[cfg(unix)]
pub mod unix;
pub mod validate;
pub const VERSION: u16 = 3;
#[must_use]
pub fn is_virtual_list(kind: &str) -> bool {
matches!(kind, "ui.VirtualList" | "ui.TreeView" | "ui.MediaGrid")
}
pub const PAGE: &str = "page";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Level {
Root,
Detail,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Node {
pub kind: String,
pub key: String,
pub props: std::collections::BTreeMap<String, Value>,
pub binding: Option<Binding>,
pub events: std::collections::BTreeMap<String, Event>,
pub anchor: Option<String>,
pub children: Vec<Node>,
}
impl Node {
#[must_use]
pub fn empty(kind: &str, key: &str) -> Self {
Self {
kind: kind.to_owned(),
key: key.to_owned(),
..Self::default()
}
}
#[must_use]
pub fn at(&self, path: &[String]) -> Option<&Self> {
let mut node = self;
for key in path {
node = node.children.iter().find(|child| child.key == *key)?;
}
Some(node)
}
pub fn at_mut(&mut self, path: &[String]) -> Option<&mut Self> {
let mut node = self;
for key in path {
node = node.children.iter_mut().find(|child| child.key == *key)?;
}
Some(node)
}
#[must_use]
pub fn find(&self, key: &str) -> Option<&Self> {
if self.key == key {
return Some(self);
}
self.children.iter().find_map(|child| child.find(key))
}
#[must_use]
pub fn of_kind(&self, kind: &str) -> Vec<&Self> {
let mut out = Vec::new();
let mut at = vec![self];
while let Some(node) = at.pop() {
if node.kind == kind {
out.push(node);
}
at.extend(node.children.iter().rev());
}
out
}
#[must_use]
pub fn first_of_kind(&self, kind: &str) -> Option<&Self> {
self.of_kind(kind).into_iter().next()
}
#[must_use]
pub fn count(&self) -> usize {
1usize.saturating_add(self.children.iter().map(Self::count).sum::<usize>())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ResourceRef {
pub id: String,
pub ty: String,
}
impl ResourceRef {
#[must_use]
pub fn id_string(&self) -> String {
self.id.clone()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Actor {
pub id: tilo_actions::Actor,
pub name: String,
#[serde(default)]
pub hue: Option<u8>,
#[serde(default)]
pub picture: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Value {
Unit,
Int(i64),
Float(f64),
Bool(bool),
Text(String),
List(Vec<Value>),
Opt(Option<Box<Value>>),
Enum(String),
Case {
case: String,
fields: Vec<(String, Value)>,
},
Ref(ResourceRef),
Actor(Actor),
Rich(rich::RichText),
Error(String),
Map(Vec<(Value, Value)>),
Action(Offered),
Picture(Picture),
File(File),
Link {
reference: String,
title: String,
},
}
pub use tilo_ui_graph::component::File;
pub use tilo_ui_graph::component::Offered;
pub use tilo_ui_graph::component::Picture;
#[must_use]
pub fn description(kind: &str) -> Option<&'static tilo_ui_graph::component::Description> {
tilo_ui_graph::component::catalogue().get(kind.strip_prefix("ui.")?)
}
pub use tilo_ui_graph::component::Type as PropType;
impl Value {
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self::Text(text.into())
}
#[must_use]
pub fn some(value: Self) -> Self {
Self::Opt(Some(Box::new(value)))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Binding {
pub field: Option<(String, String)>,
pub kind: Option<String>,
pub name: String,
}
impl Binding {
#[must_use]
pub fn field(&self) -> Option<(&str, &str)> {
self.field
.as_ref()
.map(|(target, field)| (target.as_str(), field.as_str()))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
pub toggles: Option<(String, String)>,
pub invokes: Option<Invocation>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Invocation {
pub resource: String,
pub action: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Patch {
SetRoot(Node),
Insert {
parent: Vec<String>,
index: u32,
node: Node,
},
Remove {
parent: Vec<String>,
key: String,
},
Move {
parent: Vec<String>,
key: String,
to: u32,
},
SetProp {
path: Vec<String>,
name: String,
value: Option<Value>,
},
SetBinding {
path: Vec<String>,
binding: Option<Binding>,
},
SetEvent {
path: Vec<String>,
event: String,
action: Option<Event>,
},
SetAnchor {
path: Vec<String>,
anchor: Option<String>,
},
SpliceProp {
path: Vec<String>,
name: String,
at: u32,
remove: u32,
insert: Vec<Value>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("a patch names a node the tree does not have")]
pub struct Unapplied;
impl Patch {
pub fn apply(self, root: &mut Node) -> Result<(), Unapplied> {
match self {
Self::SetRoot(node) => *root = node,
Self::Insert {
parent,
index,
node,
} => {
let parent = root.at_mut(&parent).ok_or(Unapplied)?;
let index = usize::try_from(index)
.unwrap_or(usize::MAX)
.min(parent.children.len());
parent.children.insert(index, node);
}
Self::Remove { parent, key } => {
let parent = root.at_mut(&parent).ok_or(Unapplied)?;
let at = parent
.children
.iter()
.position(|child| child.key == key)
.ok_or(Unapplied)?;
parent.children.remove(at);
}
Self::Move { parent, key, to } => {
let parent = root.at_mut(&parent).ok_or(Unapplied)?;
let at = parent
.children
.iter()
.position(|child| child.key == key)
.ok_or(Unapplied)?;
let moved = parent.children.remove(at);
let to = usize::try_from(to)
.unwrap_or(usize::MAX)
.min(parent.children.len());
parent.children.insert(to, moved);
}
Self::SetProp { path, name, value } => {
let node = root.at_mut(&path).ok_or(Unapplied)?;
match value {
Some(value) => {
node.props.insert(name, value);
}
None => {
node.props.remove(&name);
}
}
}
Self::SetBinding { path, binding } => {
root.at_mut(&path).ok_or(Unapplied)?.binding = binding;
}
Self::SetEvent {
path,
event,
action,
} => {
let node = root.at_mut(&path).ok_or(Unapplied)?;
match action {
Some(action) => {
node.events.insert(event, action);
}
None => {
node.events.remove(&event);
}
}
}
Self::SetAnchor { path, anchor } => {
root.at_mut(&path).ok_or(Unapplied)?.anchor = anchor;
}
Self::SpliceProp {
path,
name,
at,
remove,
insert,
} => {
let node = root.at_mut(&path).ok_or(Unapplied)?;
let Some(Value::List(items)) = node.props.get_mut(&name) else {
return Err(Unapplied);
};
let at = usize::try_from(at).map_err(|_| Unapplied)?;
let end = at
.checked_add(usize::try_from(remove).map_err(|_| Unapplied)?)
.filter(|end| *end <= items.len())
.ok_or(Unapplied)?;
items.splice(at..end, insert);
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RowChange {
Inserted {
index: u32,
key: String,
},
Removed {
index: u32,
},
Moved {
from: u32,
to: u32,
},
Changed {
row: Box<Node>,
},
Reset,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Words {
Phrase {
id: String,
args: Vec<(String, String)>,
},
Plain(String),
}
impl Words {
#[must_use]
pub fn phrase(id: &str) -> Self {
Self::Phrase {
id: id.to_owned(),
args: Vec::new(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum NoticeKind {
Info,
Error,
Success,
Warning,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Front {
Input,
Action,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ask {
pub action: String,
pub invoker: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Answer {
Allow,
Decline,
Always,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[allow(
clippy::struct_excessive_bools,
reason = "each bool is an independent facet the app decides about its form"
)]
pub struct Form {
pub id: u64,
pub title: String,
pub submit: String,
pub destructive: bool,
pub ready: bool,
pub error: Option<String>,
pub from: Option<(Level, String)>,
pub fields: Vec<(String, String)>,
pub short: bool,
pub answers: Vec<String>,
pub confirm: bool,
pub tree: Node,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ToUi {
Loading,
Open {
level: Level,
target: ResourceRef,
tree: Node,
front: Option<Front>,
capture_protected: bool,
},
Close,
Front {
front: Front,
shows: Option<(u64, ResourceRef)>,
},
Patch { level: Level, patches: Vec<Patch> },
Bound {
level: Level,
key: String,
value: Value,
acked: u64,
},
Rows {
level: Level,
list: String,
len: u32,
start: u32,
keys: Vec<String>,
rows: Vec<Node>,
},
RowsChanged {
level: Level,
list: String,
len: u32,
changes: Vec<RowChange>,
},
Spaces { level: Level, keys: Vec<String> },
Notice {
words: Words,
kind: NoticeKind,
undo: bool,
},
Ask(Option<Ask>),
Form(Option<Box<Form>>),
Activate,
ShowRun { run: String },
Took { fired: u64 },
Actions(#[serde(with = "serde_bytes")] Vec<u8>),
Speak(String),
Kept(bool),
Heard(#[serde(with = "serde_bytes")] Vec<u8>),
History(bool),
Page {
request_id: u32,
#[serde(with = "serde_bytes")]
request: Vec<u8>,
},
Outputs(#[serde(with = "serde_bytes")] Vec<u8>),
CallPictures {
shown: Vec<CallShown>,
pictures: Vec<CallPicture>,
},
Focus { key: Option<String> },
CloseWindow,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CallPictureSource {
Camera,
Screen,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallShown {
pub person: String,
pub source: CallPictureSource,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallPicture {
pub person: String,
pub stream: String,
pub source: CallPictureSource,
#[serde(with = "serde_bytes")]
pub object: Vec<u8>,
}
pub const MAX_CALL_PICTURES: usize = 64;
pub const MAX_CALL_PICTURE_BYTES: usize = 512 * 1024;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Held {
pub shift: bool,
pub command: bool,
pub alt: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ToApp {
Fire {
level: Level,
key: String,
event: String,
value: Option<Value>,
gesture: Option<String>,
},
Toggle {
level: Level,
target: ResourceRef,
key: String,
checked: bool,
},
Splice {
level: Level,
target: ResourceRef,
key: String,
seq: u64,
at: u32,
delete: u32,
insert: String,
},
Edit {
level: Level,
target: ResourceRef,
key: String,
text: String,
},
EditRich {
level: Level,
target: ResourceRef,
key: String,
rich: rich::RichText,
gesture: Option<String>,
},
Resolve {
level: Level,
key: String,
approve: bool,
},
Open {
resource: ResourceRef,
},
OpenReference {
reference: String,
},
Back,
Rows {
level: Level,
list: String,
start: u32,
end: u32,
open: Option<String>,
menu: Option<String>,
},
Answer(Answer),
FormEdit {
form: u64,
field: String,
text: String,
},
FormSubmit {
form: u64,
},
FormCancel {
form: u64,
},
Undo,
Focus {
at: Option<(Level, String)>,
},
Composing(bool),
Held(Held),
Space {
level: Level,
key: String,
width: f32,
height: f32,
rem: f32,
},
Redo,
Invoke {
address: ActionAddress,
argument: Option<String>,
},
SaveAgain,
History {
open: bool,
},
Serving {
#[serde(with = "serde_bytes")]
call: Vec<u8>,
invoker: Option<String>,
},
PageAnswer {
request_id: u32,
#[serde(with = "serde_bytes")]
answer: Vec<u8>,
},
PagePrompt {
#[serde(with = "serde_bytes")]
prompt: Vec<u8>,
},
}
pub const MAX_BATCH_BYTES: usize = 16 << 20;
pub const MAX_PAGE_BYTES: usize = 8 << 20;
pub fn encode_batch<T: Serialize>(messages: &[T]) -> Result<Vec<u8>, WireError> {
let mut bytes = Vec::with_capacity(64);
bytes.extend_from_slice(&VERSION.to_le_bytes());
let bytes = postcard::to_extend(messages, bytes).map_err(|_| WireError::Malformed("batch"))?;
if bytes.len() > MAX_BATCH_BYTES {
return Err(WireError::OverLimit("batch size"));
}
Ok(bytes)
}
pub fn decode_batch<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<Vec<T>, WireError> {
if bytes.len() > MAX_BATCH_BYTES {
return Err(WireError::OverLimit("batch size"));
}
let (version, body) = bytes.split_at_checked(2).ok_or(WireError::Truncated)?;
if version != VERSION.to_le_bytes() {
return Err(WireError::Malformed("batch version"));
}
let (messages, rest) =
postcard::take_from_bytes(body).map_err(|_| WireError::Malformed("batch"))?;
if !rest.is_empty() {
return Err(WireError::Malformed("bytes after a batch"));
}
Ok(messages)
}
pub trait Transport {
fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError>;
fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError>;
}
#[cfg(test)]
mod tests {
use super::*;
fn text(key: &str, value: &str) -> Node {
let mut node = Node::empty("ui.Text", key);
node.props.insert("value".to_owned(), Value::text(value));
node
}
#[test]
fn patches_apply_by_key_and_refuse_a_node_the_tree_lacks() {
let mut root = Node::empty("stack", "s");
root.children = vec![text("a", "1"), text("b", "2")];
Patch::Insert {
parent: Vec::new(),
index: 0,
node: text("n", "0"),
}
.apply(&mut root)
.expect("applies");
Patch::Move {
parent: Vec::new(),
key: "b".to_owned(),
to: 1,
}
.apply(&mut root)
.expect("applies");
Patch::SetProp {
path: vec!["a".to_owned()],
name: "value".to_owned(),
value: Some(Value::text("3")),
}
.apply(&mut root)
.expect("applies");
let keys: Vec<&str> = root.children.iter().map(|c| c.key.as_str()).collect();
assert_eq!(keys, ["n", "b", "a"]);
assert_eq!(
root.find("a").and_then(|a| a.props.get("value")),
Some(&Value::text("3"))
);
assert_eq!(
Patch::Remove {
parent: vec!["nowhere".to_owned()],
key: "a".to_owned()
}
.apply(&mut root),
Err(Unapplied)
);
}
#[test]
fn a_batch_reads_back_as_it_was_sent_and_scribbles_are_refused() {
let batch = vec![
ToUi::Open {
level: Level::Root,
target: ResourceRef {
id: "doc".to_owned(),
ty: "notes.Notebook".to_owned(),
},
tree: text("t", "Notes"),
front: None,
capture_protected: false,
},
ToUi::Patch {
level: Level::Root,
patches: vec![Patch::SetProp {
path: Vec::new(),
name: "value".to_owned(),
value: Some(Value::text("Ideas")),
}],
},
];
let bytes = encode_batch(&batch).expect("encodes");
let back: Vec<ToUi> = decode_batch(&bytes).expect("decodes");
assert_eq!(back, batch);
for cut in 0..bytes.len() {
let truncated: Result<Vec<ToUi>, _> = decode_batch(&bytes[..cut]);
assert!(truncated.is_err() || cut == bytes.len());
}
let mut other = bytes;
other[0] = 9;
assert!(decode_batch::<ToUi>(&other).is_err(), "another version");
}
#[test]
fn rich_text_reads_back_as_it_was_sent_with_or_without_its_parts() {
let reference = r#"{"app":"a.b","id":"t1","kind":"a.task"}"#;
let rich = |marks: Vec<rich::Mark>, embeds: Vec<rich::Embed>| rich::RichText {
blocks: vec![rich::Block {
kind: "paragraph".to_owned(),
text: "see Fix it".to_owned(),
marks,
attrs: std::collections::BTreeMap::new(),
}],
styles: std::collections::BTreeMap::default(),
embeds,
};
let batch: Vec<ToUi> = [
rich(Vec::new(), Vec::new()),
rich(
vec![rich::Mark {
start: 4,
end: 10,
name: "mention".to_owned(),
value: rich::Attr::Text(reference.to_owned()),
}],
vec![
rich::Embed {
reference: reference.to_owned(),
view: rich::InlineView::Resource {
title: "Fix the build".to_owned(),
icon: None,
detail: None,
},
preview: None,
},
rich::Embed {
reference: "u-ada".to_owned(),
view: rich::InlineView::Unreadable,
preview: None,
},
],
),
]
.into_iter()
.map(|value| ToUi::Patch {
level: Level::Root,
patches: vec![Patch::SetProp {
path: Vec::new(),
name: "value".to_owned(),
value: Some(Value::Rich(value)),
}],
})
.collect();
let bytes = encode_batch(&batch).expect("encodes");
assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
}
#[test]
fn a_rich_inputs_edit_round_trips_empty_or_not() {
let plain = rich::RichText {
blocks: vec![rich::Block {
kind: "paragraph".into(),
text: "hi".into(),
..rich::Block::default()
}],
embeds: Vec::new(),
styles: std::collections::BTreeMap::default(),
};
for rich in [rich::RichText::default(), plain] {
let edit = vec![ToApp::EditRich {
level: Level::Root,
target: ResourceRef {
id: "n1".into(),
ty: "Note".into(),
},
key: "draft".into(),
rich,
gesture: None,
}];
let bytes = encode_batch(&edit).expect("encodes");
assert_eq!(decode_batch::<ToApp>(&bytes).expect("decodes"), edit);
}
}
#[test]
fn maps_offered_actions_and_list_splices_round_trip_and_apply() {
let who = |id: &str| {
Value::Actor(Actor {
id: tilo_actions::MemberId::person(id).into(),
name: id.to_owned(),
hue: None,
picture: None,
})
};
let reactions = Value::Map(vec![
(Value::text("👍"), Value::List(vec![who("ada"), who("leo")])),
(Value::text("🎉"), Value::List(vec![who("mia")])),
]);
let offered = Value::List(vec![Value::Action(Offered {
label: "Pin".to_owned(),
icon: Some("pin".to_owned()),
on: Some(false),
event: "actions.0".to_owned(),
..Offered::default()
})]);
let item = |id: &str| {
Value::Ref(ResourceRef {
id: id.to_owned(),
ty: "chat.Message".to_owned(),
})
};
let mut node = Node::empty("ui.Reactions", "r");
node.props.insert("reactions".to_owned(), reactions);
node.props.insert("actions".to_owned(), offered);
node.props.insert(
"items".to_owned(),
Value::List(vec![item("m1"), item("m3")]),
);
let splice = Patch::SpliceProp {
path: Vec::new(),
name: "items".to_owned(),
at: 1,
remove: 0,
insert: vec![item("m2")],
};
let batch = vec![
ToUi::Open {
level: Level::Root,
target: ResourceRef {
id: "c".to_owned(),
ty: "chat.Conversation".to_owned(),
},
tree: node.clone(),
front: None,
capture_protected: false,
},
ToUi::Patch {
level: Level::Root,
patches: vec![splice.clone()],
},
];
let bytes = encode_batch(&batch).expect("encodes");
assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
splice.apply(&mut node).expect("applies");
assert_eq!(
node.props.get("items"),
Some(&Value::List(vec![item("m1"), item("m2"), item("m3")]))
);
let past_the_end = Patch::SpliceProp {
path: Vec::new(),
name: "items".to_owned(),
at: 3,
remove: 1,
insert: Vec::new(),
};
assert_eq!(past_the_end.apply(&mut node), Err(Unapplied));
let not_a_list = Patch::SpliceProp {
path: Vec::new(),
name: "reactions".to_owned(),
at: 0,
remove: 0,
insert: Vec::new(),
};
assert_eq!(not_a_list.apply(&mut node), Err(Unapplied));
}
}