Ely Office: six offline-first desktop apps in Rust and GPUI

ElyDoc, ElyTable, ElyShow (LibreOfficeKit), ElyPDF (MuPDF), ElyTree (Git),
ElyMark (Milkdown and CodeMirror in CEF). ElyMail and ElyAgent follow.
This commit is contained in:
ZacharyZhang-NY committed 2026-10-08 21:20:08 -04:00
commit b7fca0146d
817 files changed
+143101

No files matched your search

+347
View File
@@ -0,0 +1,347 @@
//! What a spreadsheet reports about the current cell (TABLE-02, 03).
use serde_json::Value;
use super::Rect;
use crate::ipc::{Pack, Unpack};
/// What a spreadsheet reports about the current cell.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Cell {
/// The cell cursor in twips; None while it hides.
pub cursor: Option<Rect>,
/// The cell's content as the formula bar shows it.
pub formula: String,
/// The selection's address, as "A1" or "A1:B3".
pub address: String,
/// Bumps when sheets switch or the sheet size changes.
pub sheets: u64,
/// Bumps when row or column headers change.
pub headers: u64,
/// The references of the formula being typed.
pub marks: Vec<Mark>,
/// Functions that fit the name being typed.
pub functions: Vec<Function>,
/// The call being typed: its signature and the argument.
pub usage: String,
/// Bumps on each request.
pub requests: u64,
/// The last thing the kernel asked Ely to show.
pub request: Option<Request>,
}
/// What the kernel asks Ely to show (TABLE-08, 09).
#[derive(Clone, Debug, PartialEq)]
pub enum Request {
/// The filter menu of a column's button.
Filter { column: u32, row: u32 },
/// The validation list to choose from.
Choices { column: u32, row: u32 },
/// An entry the validation refused or warned of.
Invalid {
title: String,
message: String,
/// stop, warning or info.
style: String,
accepted: bool,
},
}
/// One reference of a formula being typed.
#[derive(Clone, Debug, PartialEq)]
pub struct Mark {
pub rect: Rect,
/// 0xRRGGBB, as the kernel colors the reference.
pub color: u32,
pub part: usize,
}
/// A function the kernel offers for a typed name.
#[derive(Clone, Debug, PartialEq)]
pub struct Function {
pub name: String,
pub signature: String,
pub description: String,
}
impl Request {
/// The request's kind, for logs without document text.
pub fn kind(&self) -> &'static str {
match self {
Request::Filter { .. } => "a filter menu",
Request::Choices { .. } => "a choice list",
Request::Invalid { .. } => "an entry notice",
}
}
}
impl Cell {
pub(crate) fn pack(&self, pack: Pack) -> Pack {
let (x, y, w, h) = self.cursor.unwrap_or((-1, -1, -1, -1));
let pack = pack
.i64(x.into())
.i64(y.into())
.i64(w.into())
.i64(h.into())
.str(&self.formula)
.str(&self.address)
.u64(self.sheets)
.u64(self.headers)
.u64(self.marks.len() as u64);
let pack = self.marks.iter().fold(pack, |pack, mark| {
let (x, y, w, h) = mark.rect;
pack.i64(x.into())
.i64(y.into())
.i64(w.into())
.i64(h.into())
.u64(mark.color.into())
.u64(mark.part as u64)
});
let pack = pack.u64(self.functions.len() as u64);
let pack = self
.functions
.iter()
.fold(pack, |pack, function| {
pack.str(&function.name)
.str(&function.signature)
.str(&function.description)
})
.str(&self.usage)
.u64(self.requests);
match &self.request {
None => pack.u64(0),
Some(Request::Filter { column, row }) => {
pack.u64(1).u64((*column).into()).u64((*row).into())
}
Some(Request::Choices { column, row }) => {
pack.u64(2).u64((*column).into()).u64((*row).into())
}
Some(Request::Invalid {
title,
message,
style,
accepted,
}) => pack
.u64(3)
.str(title)
.str(message)
.str(style)
.u64((*accepted).into()),
}
}
pub(crate) fn unpack(unpack: &mut Unpack) -> std::io::Result<Cell> {
fn number(unpack: &mut Unpack) -> std::io::Result<i32> {
i32::try_from(unpack.i64()?).map_err(std::io::Error::other)
}
fn rect(unpack: &mut Unpack) -> std::io::Result<Rect> {
Ok((
number(unpack)?,
number(unpack)?,
number(unpack)?,
number(unpack)?,
))
}
let cursor = rect(unpack)?;
let (formula, address) = (unpack.str()?, unpack.str()?);
let (sheets, headers) = (unpack.u64()?, unpack.u64()?);
let marks = (0..unpack.u64()?)
.map(|_| {
Ok(Mark {
rect: rect(unpack)?,
color: u32::try_from(unpack.u64()?).map_err(std::io::Error::other)?,
part: unpack.u64()? as usize,
})
})
.collect::<std::io::Result<_>>()?;
let functions = (0..unpack.u64()?)
.map(|_| {
Ok(Function {
name: unpack.str()?,
signature: unpack.str()?,
description: unpack.str()?,
})
})
.collect::<std::io::Result<_>>()?;
let usage = unpack.str()?;
let requests = unpack.u64()?;
let index = |unpack: &mut Unpack| -> std::io::Result<u32> {
u32::try_from(unpack.u64()?).map_err(std::io::Error::other)
};
let request = match unpack.u64()? {
0 => None,
1 => Some(Request::Filter {
column: index(unpack)?,
row: index(unpack)?,
}),
2 => Some(Request::Choices {
column: index(unpack)?,
row: index(unpack)?,
}),
3 => Some(Request::Invalid {
title: unpack.str()?,
message: unpack.str()?,
style: unpack.str()?,
accepted: unpack.u64()? != 0,
}),
other => return Err(std::io::Error::other(format!("no request {other}"))),
};
Ok(Cell {
cursor: (cursor.2 >= 0).then_some(cursor),
formula,
address,
sheets,
headers,
marks,
functions,
usage,
requests,
request,
})
}
}
/// A REFERENCE_MARKS payload.
pub fn marks_of(text: &str) -> Option<Vec<Mark>> {
let json: Value = serde_json::from_str(text).ok()?;
json["marks"]
.as_array()?
.iter()
.map(|mark| {
Some(Mark {
rect: super::parse::rect_of(mark["rectangle"].as_str()?)?,
color: u32::from_str_radix(mark["color"].as_str()?, 16).ok()?,
part: mark["part"].as_str()?.parse().ok()?,
})
})
.collect()
}
/// A CALC_FUNCTION_LIST payload; "hidetip" is empty.
pub fn functions_of(text: &str) -> Option<Vec<Function>> {
if text == "hidetip" {
return Some(Vec::new());
}
let json: Value = serde_json::from_str(text).ok()?;
json.as_array()?
.iter()
.map(|entry| {
let signature = entry["signature"].as_str()?.to_string();
let name = signature.split('(').next()?.trim().to_string();
Some(Function {
name,
signature,
description: entry["description"].as_str()?.to_string(),
})
})
.collect()
}
/// A TOOLTIP payload's usage text, if it is one.
pub fn usage_of(text: &str) -> Option<String> {
let json: Value = serde_json::from_str(text).ok()?;
(json["type"] == "formulausage").then(|| json["text"].as_str().map(str::to_string))?
}
/// A TOOLTIP payload asking for a menu or a notice.
pub fn request_of(text: &str) -> Option<Request> {
let json: Value = serde_json::from_str(text).ok()?;
let index = |key: &str| u32::try_from(json[key].as_i64()?).ok();
let text = |key: &str| json[key].as_str().map(str::to_string);
match json["type"].as_str()? {
"autofilter" => Some(Request::Filter {
column: index("col")?,
row: index("row")?,
}),
"datalist" => Some(Request::Choices {
column: index("col")?,
row: index("row")?,
}),
"validityerror" => Some(Request::Invalid {
title: text("title")?,
message: text("message")?,
style: text("style")?,
accepted: json["accepted"].as_bool()?,
}),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calc_formula_hints_read_out() {
let marks = r#"{ "marks": [ { "rectangle": "1280, 512, 1279, 255", "color": "ef0fff", "part": "0" } ] }"#;
assert_eq!(
marks_of(marks),
Some(vec![Mark {
rect: (1280, 512, 1279, 255),
color: 0xef0fff,
part: 0
}])
);
assert_eq!(marks_of(r#"{ "marks": [ ] }"#), Some(Vec::new()));
let list = r#"[ {"index": 4, "signature": "SUM( Number 1, Number 2, ... )", "description": "Returns the sum of all arguments.", "namedRange": false } ]"#;
let functions = functions_of(list).expect("a list");
assert_eq!(functions[0].name, "SUM");
assert_eq!(functions_of("hidetip"), Some(Vec::new()));
assert_eq!(
request_of(r#"{"type":"autofilter","col":2,"row":0}"#),
Some(Request::Filter { column: 2, row: 0 })
);
let refused = r#"{"type":"validityerror","title":"Bad","message":"No","style":"stop","accepted":false}"#;
assert!(matches!(
request_of(refused),
Some(Request::Invalid {
accepted: false,
..
})
));
assert_eq!(
request_of(r#"{"type":"autofilter","col":-1,"row":0}"#),
None
);
let usage = r#"{ "type": "formulausage", "text": "SUM(► Number 1) : The numbers."}"#;
assert_eq!(
usage_of(usage).as_deref(),
Some("SUM(► Number 1) : The numbers.")
);
assert_eq!(usage_of(r#"{ "text": "Author: Ada" }"#), None);
}
#[test]
fn a_cell_packs_and_unpacks() {
let cell = Cell {
cursor: Some((1, 2, 3, 4)),
formula: "=SUM(B3".into(),
address: "A2".into(),
sheets: 1,
headers: 2,
marks: vec![Mark {
rect: (5, 6, 7, 8),
color: 0xff0000,
part: 1,
}],
functions: vec![Function {
name: "SUM".into(),
signature: "SUM()".into(),
description: "Adds.".into(),
}],
usage: "SUM(►)".into(),
requests: 3,
request: Some(Request::Invalid {
title: "Bad".into(),
message: "No".into(),
style: "stop".into(),
accepted: false,
}),
};
let bytes = cell.pack(Pack::new()).bytes();
assert_eq!(
Cell::unpack(&mut Unpack::new(&bytes)).expect("unpacks"),
cell
);
}
}
+294
View File
@@ -0,0 +1,294 @@
//! Callback payload parsers.
use serde_json::Value;
use super::Rect;
/// The focused paragraph or cell for assistive tech (§7 tail).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct A11y {
pub text: String,
/// Caret and selection in chars; LOK's -1 is None.
pub caret: Option<usize>,
pub selection: Option<(usize, usize)>,
}
/// A kernel window event that matters to the guard.
pub enum Dialog {
/// A dialog is up; close it.
Opened { window: u32, title: Option<String> },
/// A window got its title.
Titled { window: u32, title: String },
}
/// Parses "x, y, w, h" plus optional fields.
pub fn rect_of(text: &str) -> Option<Rect> {
let parts: Vec<i32> = text
.split(',')
.filter_map(|part| part.trim().parse().ok())
.collect();
match parts.as_slice() {
[x, y, w, h, ..] => Some((*x, *y, *w, *h)),
_ => None,
}
}
/// A search's matches, each by its first rectangle.
pub fn found_of(text: &str) -> Option<Vec<Rect>> {
let json: Value = serde_json::from_str(text).ok()?;
json["searchResultSelection"]
.as_array()?
.iter()
.map(|found| rect_of(found["rectangles"].as_str()?.split(';').next()?))
.collect()
}
/// The missing font families of a FONTS_MISSING payload.
pub fn fonts_of(text: &str) -> Option<Vec<String>> {
let json: Value = serde_json::from_str(text).ok()?;
json["fontsmissing"]
.as_array()?
.iter()
.map(|font| font.as_str().map(str::to_string))
.collect()
}
/// A STATE_CHANGED payload: ".uno:X=v" or JSON with commandName.
pub fn state_of(text: &str) -> Option<(String, String)> {
if text.starts_with('{') {
let json: Value = serde_json::from_str(text).ok()?;
let name = json["commandName"].as_str()?.to_string();
if json["dontcare"] == true {
return Some((name, super::MIXED.to_string()));
}
let state = match &json["state"] {
Value::String(state) => state.clone(),
other => other.to_string(),
};
return Some((name, state));
}
let (name, state) = text.split_once('=')?;
Some((name.to_string(), state.to_string()))
}
/// The text Calc's input line shows, from its JSDialog.
pub fn formula_text(text: &str) -> Option<String> {
let json: Value = serde_json::from_str(text).ok()?;
let data = &json["data"];
let line = json["jsontype"] == "formulabar"
&& data["control_id"] == "sc_input_window"
&& data["action_type"] == "setText";
line.then(|| data["text"].as_str().map(str::to_string))?
}
/// A ruler's custom tab stops; style 4 is default.
pub fn tabs_of(text: &str) -> Vec<i32> {
let Some(tabs) = text.split("\"tabs\"").nth(1) else {
return Vec::new();
};
// The keys repeat, so read the pairs as text.
let number = |field: &str, from: &str| -> Option<i32> {
let rest = from.split(field).nth(1)?;
let digits: String = rest
.trim_start_matches([':', ' ', '"'])
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '-')
.collect();
digits.parse().ok()
};
tabs.split('{')
.skip(2)
.filter_map(|entry| Some((number("\"position\"", entry)?, number("\"style\"", entry)?)))
.filter(|(_, style)| *style != 4)
.map(|(position, _)| position)
.collect()
}
/// A completion payload: command name and success.
pub fn result_of(text: &str) -> Option<(String, bool)> {
let json: Value = serde_json::from_str(text).ok()?;
Some((
json["commandName"].as_str()?.to_string(),
json["success"].as_bool()?,
))
}
/// A number field sent as text or number.
fn number(value: &Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_str().and_then(|text| text.parse().ok()))
}
/// The dialog event in a WINDOW or JSDIALOG payload.
pub fn dialog_of(jsdialog: bool, text: &str) -> Option<Dialog> {
let json: Value = serde_json::from_str(text).ok()?;
let action = json["action"].as_str().unwrap_or("");
let window = u32::try_from(number(&json["id"])?).ok()?;
let title = json["title"]
.as_str()
.or_else(|| json["text"].as_str())
.map(str::to_string);
if !jsdialog && action == "title_changed" {
return Some(Dialog::Titled {
window,
title: title?,
});
}
let opens = if jsdialog {
json["jsontype"] == "dialog" && action != "close"
} else {
// A tooltip is no dialog.
action == "created" && json["type"] != "tooltip"
};
opens.then_some(Dialog::Opened { window, title })
}
/// A signed LOK position; -1 and absent are None.
fn position(value: &Value) -> Option<usize> {
let signed = value
.as_i64()
.or_else(|| value.as_str().and_then(|text| text.parse().ok()))?;
usize::try_from(signed).ok()
}
/// Folds a focus, caret or selection payload into `a11y`.
fn fold_paragraph(a11y: &mut A11y, json: &Value) {
if let Some(text) = json["content"].as_str() {
a11y.text = text.to_string();
}
if !json["position"].is_null() {
a11y.caret = position(&json["position"]);
}
if !json["start"].is_null() {
a11y.selection = position(&json["start"]).zip(position(&json["end"]));
}
}
/// Folds an A11Y callback of LOK kind `kind` (62..69).
pub fn a11y_update(a11y: &mut A11y, kind: i32, text: &str) {
let Ok(json) = serde_json::from_str::<Value>(text) else {
log::warn!("lok: an a11y payload is not JSON");
return;
};
match kind {
// Focused cell, editing state: a nested paragraph.
67 | 68 => fold_paragraph(a11y, &json["paragraph"]),
// Object or cell selection.
69 => {
*a11y = A11y::default();
if json["action"] != "remove" {
a11y.text = json["text"].as_str().unwrap_or_default().to_string();
}
}
_ => fold_paragraph(a11y, &json),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dont_care_states_read_as_mixed() {
let mixed = state_of(r#"{"commandName":".uno:Bold","dontcare":true}"#);
assert_eq!(
mixed,
Some((".uno:Bold".into(), super::super::MIXED.into()))
);
assert_eq!(
state_of(".uno:Bold=false"),
Some((".uno:Bold".into(), "false".into()))
);
}
#[test]
fn ruler_tabs_keep_the_custom_stops() {
let ruler = r#"{ "margin1": 0, "tabs": { "": { "position": 1251, "style": 4}, "": { "position": 2000, "style": 0}, "": { "position": 3500, "style": 3} }, "unit": "\""}"#;
assert_eq!(tabs_of(ruler), [2000, 3500]);
assert_eq!(tabs_of(r#"{"tabs": { }}"#), Vec::<i32>::new());
}
#[test]
fn states_parse_both_forms() {
assert_eq!(
state_of(".uno:Bold=true"),
Some((".uno:Bold".into(), "true".into()))
);
assert_eq!(
state_of(r#"{"commandName":".uno:FontHeight","state":"12"}"#),
Some((".uno:FontHeight".into(), "12".into()))
);
assert_eq!(state_of("garbage"), None);
}
fn opened(event: Option<Dialog>) -> Option<(u32, Option<String>)> {
match event? {
Dialog::Opened { window, title } => Some((window, title)),
Dialog::Titled { .. } => None,
}
}
#[test]
fn dialogs_open_on_created_or_jsdialog() {
let created = dialog_of(false, r#"{"id":"7","action":"created","title":"Font"}"#);
assert_eq!(opened(created), Some((7, Some("Font".into()))));
assert!(dialog_of(false, r#"{"id":"7","action":"invalidate"}"#).is_none());
let tip = r#"{"id":"2","action":"created","type":"tooltip","parentId":"0"}"#;
assert!(dialog_of(false, tip).is_none(), "a tooltip is no dialog");
let titled = dialog_of(
false,
r#"{"id":"2","action":"title_changed","title":"Delete"}"#,
);
assert!(matches!(titled, Some(Dialog::Titled { window: 2, .. })));
let js = r#"{"id":"Delete","text":"Delete Contents","id":2,"jsontype":"dialog"}"#;
assert_eq!(
opened(dialog_of(true, js)),
Some((2, Some("Delete Contents".into())))
);
let update = dialog_of(true, r#"{"jsontype":"dialog","action":"update","id":2}"#);
assert_eq!(opened(update), Some((2, None)));
assert!(dialog_of(true, r#"{"jsontype":"formulabar","id":0}"#).is_none());
assert!(dialog_of(true, r#"{"jsontype":"dialog","action":"close","id":2}"#).is_none());
}
#[test]
fn the_calc_input_line_reads_out() {
let line = r#"{"jsontype":"formulabar","action":"action","id":0,"data":{"control_id":"sc_input_window","text":"Hello","action_type":"setText"}}"#;
assert_eq!(formula_text(line).as_deref(), Some("Hello"));
let address = r#"{"jsontype":"addressinputfield","data":{"control_id":"pos_window","text":"A1","action_type":"setText"}}"#;
assert_eq!(formula_text(address), None);
}
#[test]
fn a11y_folds_focus_caret_and_selection() {
let mut a11y = A11y::default();
let focus = r#"{"content":"Hello","position":"2","start":"1","end":"3"}"#;
a11y_update(&mut a11y, 62, focus);
let want = A11y {
text: "Hello".into(),
caret: Some(2),
selection: Some((1, 3)),
};
assert_eq!(a11y, want);
a11y_update(&mut a11y, 63, r#"{"position":"5"}"#);
assert_eq!(a11y.caret, Some(5));
a11y_update(&mut a11y, 64, r#"{"start":"-1","end":"-1"}"#);
assert_eq!(a11y.selection, None, "-1 clears the selection");
let cell = r#"{"paragraph":{"content":"B1","position":"0"}}"#;
a11y_update(&mut a11y, 67, cell);
assert_eq!(a11y.text, "B1");
a11y_update(
&mut a11y,
69,
r#"{"cell":"1","action":"create","text":"A1 text"}"#,
);
assert_eq!(a11y.text, "A1 text");
a11y_update(
&mut a11y,
69,
r#"{"cell":"1","action":"remove","text":"A1 text"}"#,
);
assert_eq!(a11y, A11y::default(), "a removed selection clears");
}
}