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:
817 files changed
+143101
No files matched your search
@@ -0,0 +1,86 @@
|
||||
//! Event batches pushed to the client (LOK-03).
|
||||
|
||||
use super::{OUT, quit};
|
||||
use crate::events::{Events, Rect};
|
||||
use crate::ipc::{self, Pack, tag};
|
||||
|
||||
/// Pushes each document's new events as they come (LOK-03).
|
||||
pub(super) fn push() {
|
||||
loop {
|
||||
crate::events::wait_unpushed();
|
||||
// Drained under the output lock: current at send.
|
||||
let out = OUT.get().expect("the output is set");
|
||||
let mut out = out.lock().expect("the output lock");
|
||||
for (id, batch) in crate::events::unpushed() {
|
||||
let revision = super::revision::of(id).unwrap_or(0);
|
||||
let body = [Pack::new().u64(id).u64(revision).bytes(), pack_events(batch)].concat();
|
||||
if let Err(error) = ipc::write_frame(&mut *out, tag::EVENTS, ipc::UNASKED, &body) {
|
||||
log::warn!("lok-worker: event write failed: {error}");
|
||||
quit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One event batch on the wire.
|
||||
fn pack_events(batch: Events) -> Vec<u8> {
|
||||
let rects = |pack: Pack, rects: &[Rect]| {
|
||||
rects
|
||||
.iter()
|
||||
.fold(pack.u64(rects.len() as u64), |pack, &(x, y, w, h)| {
|
||||
pack.i64(x as i64).i64(y as i64).i64(w as i64).i64(h as i64)
|
||||
})
|
||||
};
|
||||
let pack = Pack::new()
|
||||
.u64(batch.seq)
|
||||
.u64(batch.generation)
|
||||
.u64(batch.all as u64);
|
||||
let pack = rects(pack, &batch.rects);
|
||||
let pack = rects(pack, batch.cursor.as_slice());
|
||||
let pack = pack.u64(batch.cursor_visible as u64);
|
||||
let pack = rects(pack, &batch.selection);
|
||||
let pack = rects(pack, batch.graphic.as_slice()).u64(batch.cropping as u64);
|
||||
let pack = pack
|
||||
.u64(batch.review)
|
||||
.u64(batch.searched)
|
||||
.u64(batch.resized);
|
||||
let pack = rects(pack, &batch.found);
|
||||
let pack = pack.str(batch.menu.as_deref().unwrap_or_default());
|
||||
let pack = batch
|
||||
.faults
|
||||
.iter()
|
||||
.fold(pack.u64(batch.faults.len() as u64), |pack, fault| {
|
||||
pack.str(fault)
|
||||
});
|
||||
let pack = batch
|
||||
.fonts
|
||||
.iter()
|
||||
.fold(pack.u64(batch.fonts.len() as u64), |pack, font| {
|
||||
pack.str(font)
|
||||
});
|
||||
let pack = batch.states.iter().fold(
|
||||
pack.u64(batch.states.len() as u64),
|
||||
|pack, (name, state)| pack.str(name).str(state),
|
||||
);
|
||||
let pack = batch
|
||||
.blocked
|
||||
.iter()
|
||||
.fold(pack.u64(batch.blocked.len() as u64), |pack, title| {
|
||||
pack.str(title)
|
||||
});
|
||||
let pack = batch
|
||||
.tabs
|
||||
.iter()
|
||||
.fold(pack.u64(batch.tabs.len() as u64), |pack, tab| {
|
||||
pack.i64(*tab as i64)
|
||||
});
|
||||
let a11y = &batch.a11y;
|
||||
let signed = |at: Option<usize>| at.map_or(-1, |at| at as i64);
|
||||
let (start, end) = a11y.selection.unzip();
|
||||
let pack = pack
|
||||
.str(&a11y.text)
|
||||
.i64(signed(a11y.caret))
|
||||
.i64(signed(start))
|
||||
.i64(signed(end));
|
||||
batch.cell.pack(pack).bytes()
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Fatal signals print the native stack first.
|
||||
|
||||
use std::ffi::{c_int, c_void};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn backtrace(buffer: *mut *mut c_void, size: c_int) -> c_int;
|
||||
fn backtrace_symbols_fd(buffer: *const *mut c_void, size: c_int, fd: c_int);
|
||||
}
|
||||
|
||||
extern "C" fn report(signal: c_int) {
|
||||
let mut frames = [std::ptr::null_mut(); 64];
|
||||
// As a log record, so the app's relay keeps it.
|
||||
let note = b"[fatal ERROR ely_lok::worker::fatal] native stack follows\n";
|
||||
unsafe {
|
||||
libc::write(2, note.as_ptr().cast(), note.len());
|
||||
let count = backtrace(frames.as_mut_ptr(), frames.len() as c_int);
|
||||
backtrace_symbols_fd(frames.as_ptr(), count, 2);
|
||||
libc::signal(signal, libc::SIG_DFL);
|
||||
libc::raise(signal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints a stack for crash signals.
|
||||
pub(super) fn watch() {
|
||||
for signal in [libc::SIGSEGV, libc::SIGBUS, libc::SIGILL, libc::SIGABRT] {
|
||||
unsafe { libc::signal(signal, report as *const () as libc::sighandler_t) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
use std::io;
|
||||
|
||||
use super::with_doc;
|
||||
use crate::commands::{Arg, Check, Command};
|
||||
|
||||
use crate::ffi::Document;
|
||||
use crate::history::Step;
|
||||
use crate::ipc::{self, Pack, Unpack};
|
||||
|
||||
/// `.uno:Paste` arguments, as `doc_paste` sets them.
|
||||
const PASTE_ARGS: &str = r#"{"AnchorType":{"type":"unsigned short","value":"1"},"IgnoreComments":{"type":"boolean","value":"true"},"SkipDetection":{"type":"boolean","value":"true"}}"#;
|
||||
/// The clipboard flavors Ely moves (LOK-06).
|
||||
const CLIP_MIMES: [&str; 3] = ["text/html", "text/plain;charset=utf-8", "image/png"];
|
||||
|
||||
/// A failed request as its error text.
|
||||
fn invalid(what: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, what.to_string())
|
||||
}
|
||||
|
||||
/// Paints one tile after checking the geometry (LOK-03).
|
||||
fn paint(unpack: &mut Unpack) -> io::Result<(u64, Vec<u8>)> {
|
||||
let id = unpack.u64()?;
|
||||
let (x, y, w, h) = (unpack.i64()?, unpack.i64()?, unpack.i64()?, unpack.i64()?);
|
||||
let (pw, ph) = (unpack.i64()?, unpack.i64()?);
|
||||
let geometry_ok = (1..=i32::MAX as i64).contains(&w)
|
||||
&& (1..=i32::MAX as i64).contains(&h)
|
||||
&& pw > 0
|
||||
&& ph > 0;
|
||||
let len = (geometry_ok)
|
||||
.then(|| (pw as u64).checked_mul(ph as u64)?.checked_mul(4))
|
||||
.flatten()
|
||||
.filter(|len| *len <= (ipc::MAX_FRAME - 16) as u64);
|
||||
let Some(len) = len else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"bad tile geometry",
|
||||
));
|
||||
};
|
||||
let tile = with_doc(id, |doc| {
|
||||
let mut tile = vec![0u8; len as usize];
|
||||
doc.paint_rect(
|
||||
&mut tile,
|
||||
(pw as i32, ph as i32),
|
||||
(x as i32, y as i32, w as i32, h as i32),
|
||||
);
|
||||
tile
|
||||
})?;
|
||||
Ok((id, tile))
|
||||
}
|
||||
|
||||
/// One slide's whole picture at the asked pixels.
|
||||
pub(super) fn part_painted(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, part, master) = (unpack.u64()?, unpack.u64()?, unpack.u64()? != 0);
|
||||
let (pw, ph) = (unpack.u64()?, unpack.u64()?);
|
||||
let len = (pw > 0 && ph > 0)
|
||||
.then(|| pw.checked_mul(ph)?.checked_mul(4))
|
||||
.flatten()
|
||||
.filter(|len| *len <= (ipc::MAX_FRAME - 16) as u64)
|
||||
.ok_or_else(|| invalid("bad part geometry"))?;
|
||||
let part = i32::try_from(part).map_err(|_| invalid("bad part"))?;
|
||||
with_doc(id, |doc| {
|
||||
if part >= doc.parts() {
|
||||
return Err(invalid("no such part"));
|
||||
}
|
||||
let mut pixels = vec![0u8; len as usize];
|
||||
doc.paint_part(
|
||||
&mut pixels,
|
||||
(part, i32::from(master)),
|
||||
(pw as i32, ph as i32),
|
||||
);
|
||||
Ok(pixels)
|
||||
})?
|
||||
}
|
||||
|
||||
/// A painted tile behind its generation.
|
||||
pub(super) fn painted(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, tile) = paint(unpack)?;
|
||||
let mut body = Pack::new().u64(crate::events::generation(id)).bytes();
|
||||
body.extend_from_slice(&tile);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// The kernel's accelerators that close its frame or quit.
|
||||
const CLOSING: [i64; 3] = [534, 771, 528];
|
||||
|
||||
/// A key press and release (LOK-06).
|
||||
pub(super) fn key(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, char_code, key_code) = (unpack.u64()?, unpack.i64()?, unpack.i64()?);
|
||||
// Mod1 with W, F4 or Q closes our document.
|
||||
if key_code & 0x2000 != 0 && CLOSING.contains(&(key_code & 0x0fff)) {
|
||||
return Err(io::Error::other(format!("key {key_code} closes the kernel's frame")));
|
||||
}
|
||||
with_doc(id, |doc| {
|
||||
doc.post_key(0, char_code as i32, key_code as i32);
|
||||
doc.post_key(1, char_code as i32, key_code as i32);
|
||||
})?;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// One mouse event: kind, x, y, count, buttons, modifiers.
|
||||
pub(super) fn mouse(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let id = unpack.u64()?;
|
||||
let mut event = [0i32; 6];
|
||||
for slot in &mut event {
|
||||
*slot = unpack.i64()? as i32;
|
||||
}
|
||||
if !(0..=2).contains(&event[0]) {
|
||||
return Err(invalid("bad mouse event"));
|
||||
}
|
||||
with_doc(id, |doc| doc.post_mouse(event))?;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// A selected object's handle drag: 0 start, 1 end.
|
||||
pub(super) fn graphic(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, kind, x, y) = (unpack.u64()?, unpack.i64()?, unpack.i64()?, unpack.i64()?);
|
||||
if !(0..=1).contains(&kind) {
|
||||
return Err(invalid("bad graphic selection"));
|
||||
}
|
||||
with_doc(id, |doc| {
|
||||
doc.set_graphic_selection(kind as i32, x as i32, y as i32)
|
||||
})?;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// IME text: 0 composing, 2 commit (LOK-07).
|
||||
pub(super) fn text(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, kind, text) = (unpack.u64()?, unpack.i64()?, unpack.str()?);
|
||||
if kind != 0 && kind != 2 {
|
||||
return Err(invalid("bad text event"));
|
||||
}
|
||||
with_doc(id, |doc| doc.post_text(kind as i32, &text))??;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// How long a state check waits for the kernel.
|
||||
const STATE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Runs a table command and confirms it took (LOK-02, LOK-08).
|
||||
pub(super) fn uno(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, name) = (unpack.u64()?, unpack.str()?);
|
||||
let values = (0..unpack.u64()?)
|
||||
.map(|_| unpack.str())
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let values: Vec<&str> = values.iter().map(String::as_str).collect();
|
||||
let command = crate::commands::find(&name)?;
|
||||
let args = command.args_json(&values)?;
|
||||
with_doc(id, |doc| {
|
||||
run_checked(id, doc, command, &values, args.as_deref())
|
||||
})??;
|
||||
log::info!("lok-worker: ran {name}");
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Dispatches `command` and applies its check.
|
||||
fn run_checked(
|
||||
id: u64,
|
||||
doc: &Document,
|
||||
command: &Command,
|
||||
values: &[&str],
|
||||
args: Option<&str>,
|
||||
) -> io::Result<()> {
|
||||
let refuse = |why: String| Err(io::Error::other(format!("{}: {why}", command.id)));
|
||||
for (arg, value) in command.args.iter().zip(values) {
|
||||
if matches!(arg, Arg::Font(_)) && !font_listed(doc, value)? {
|
||||
return refuse(format!("the kernel lists no font {value}"));
|
||||
}
|
||||
}
|
||||
if command.check == Check::History && doc.kind() == 1 {
|
||||
return sheet_history(id, doc, command, args);
|
||||
}
|
||||
let history = format!("{}Count", command.uno);
|
||||
let before = if command.check == Check::History {
|
||||
let count = history_count(doc, &history)?;
|
||||
if count == 0 {
|
||||
return refuse(format!("{history} is 0"));
|
||||
}
|
||||
count
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let undo_before = undo_entries(doc)?;
|
||||
crate::events::clear_result(id);
|
||||
doc.post_uno_notify(command.uno, args)?;
|
||||
let checked = match command.check {
|
||||
Check::Result => match crate::events::take_result(id) {
|
||||
Some((_, true)) => Ok(()),
|
||||
outcome => refuse(format!("the kernel reported {outcome:?}")),
|
||||
},
|
||||
Check::History => match history_count(doc, &history)? {
|
||||
after if after + 1 == before => Ok(()),
|
||||
after => refuse(format!("{history} went {before} to {after}")),
|
||||
},
|
||||
Check::Undoable => match new_steps(&undo_before, &undo_entries(doc)?) {
|
||||
0 => refuse("the undo history did not move".into()),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Check::Listed => {
|
||||
let json = doc.command_values(".uno:StyleApply")?;
|
||||
let styles = crate::commands::styles(&json, values[1])?;
|
||||
if styles.iter().any(|name| name == values[0]) {
|
||||
Ok(())
|
||||
} else {
|
||||
refuse(format!("the style list lacks {}", values[0]))
|
||||
}
|
||||
}
|
||||
Check::Finished => match crate::events::take_result(id) {
|
||||
Some(_) => Ok(()),
|
||||
None => refuse("the kernel reported no completion".into()),
|
||||
},
|
||||
Check::Cropping => match crate::events::wait_cropping(id, STATE_WAIT) {
|
||||
true => Ok(()),
|
||||
false => refuse("the image did not enter crop mode".into()),
|
||||
},
|
||||
Check::Reports => {
|
||||
let want = reported_form(&command.args[0], values[0]);
|
||||
match crate::events::wait_state(id, command.uno, &want, STATE_WAIT) {
|
||||
Some(state) if state == want => Ok(()),
|
||||
state => refuse(format!("the kernel reports {state:?}, not {want}")),
|
||||
}
|
||||
}
|
||||
};
|
||||
if checked.is_err() && command.check != Check::History {
|
||||
let steps = new_steps(&undo_before, &undo_entries(doc)?);
|
||||
for _ in 0..steps {
|
||||
doc.post_uno(".uno:Undo", None)?;
|
||||
}
|
||||
log::warn!("lok-worker: {} failed, {steps} steps undone", command.id);
|
||||
}
|
||||
checked
|
||||
}
|
||||
|
||||
/// Calc undo acts on the sheet or the edited cell.
|
||||
fn sheet_history(id: u64, doc: &Document, command: &Command, args: Option<&str>) -> io::Result<()> {
|
||||
let gone = || io::Error::other("the document left the event watch");
|
||||
let history = format!("{}Count", command.uno);
|
||||
let (count, text) = (
|
||||
history_count(doc, &history)?,
|
||||
crate::events::a11y_text(id).ok_or_else(gone)?,
|
||||
);
|
||||
doc.post_uno(command.uno, args)?;
|
||||
if history_count(doc, &history)? + 1 == count {
|
||||
return Ok(());
|
||||
}
|
||||
let after = crate::events::wait_a11y_change(id, &text, STATE_WAIT).ok_or_else(gone)?;
|
||||
if after == text {
|
||||
return Err(io::Error::other(format!(
|
||||
"{}: neither {history} nor the cell edit moved",
|
||||
command.id
|
||||
)));
|
||||
}
|
||||
log::info!("lok-worker: {} in a cell edit", command.id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The kernel's synchronous history depth.
|
||||
fn history_count(doc: &Document, command: &str) -> io::Result<usize> {
|
||||
let count = doc.command_values(command)?;
|
||||
count
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| io::Error::other(format!("a bad {command}: {count}")))
|
||||
}
|
||||
|
||||
/// How the kernel spells a value in its state.
|
||||
fn reported_form(arg: &Arg, value: &str) -> String {
|
||||
match arg {
|
||||
Arg::Points(_) => value
|
||||
.parse::<f64>()
|
||||
.map_or_else(|_| value.to_string(), |points| points.to_string()),
|
||||
_ => value.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the kernel's font list names `family`.
|
||||
fn font_listed(doc: &Document, family: &str) -> io::Result<bool> {
|
||||
let json = doc.command_values(".uno:CharFontName")?;
|
||||
Ok(crate::commands::fonts(&json)?
|
||||
.iter()
|
||||
.any(|name| name == family))
|
||||
}
|
||||
|
||||
/// A kernel list: fonts or styles (LOK-05).
|
||||
pub(super) fn values(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, command) = (unpack.u64()?, unpack.str()?);
|
||||
let base = command.split('?').next().expect("split has a first part");
|
||||
if !crate::commands::VALUES.contains(&command.as_str())
|
||||
&& !crate::commands::QUERIES.contains(&base)
|
||||
{
|
||||
return Err(invalid(&format!("{command} is not a readable list")));
|
||||
}
|
||||
let json = with_doc(id, |doc| doc.command_values(&command))??;
|
||||
Ok(Pack::new().str(&json).bytes())
|
||||
}
|
||||
|
||||
/// Copies the selection; its flavors come back (LOK-06).
|
||||
pub(super) fn copy(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let id = unpack.u64()?;
|
||||
let entries = with_doc(id, |doc| {
|
||||
if doc.selection_type() == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
doc.post_uno(".uno:Copy", None)?;
|
||||
let entries = doc.clipboard(&CLIP_MIMES)?;
|
||||
if entries.is_empty() {
|
||||
return Err(io::Error::other("the copy produced no flavor"));
|
||||
}
|
||||
Ok(entries)
|
||||
})??
|
||||
.into_iter()
|
||||
.map(|(mime, mut data)| {
|
||||
// LOK's HTML ends in a NUL.
|
||||
if mime.starts_with("text/") {
|
||||
while data.last() == Some(&0) {
|
||||
data.pop();
|
||||
}
|
||||
}
|
||||
(mime, data)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
log::info!("lok-worker: copied {} flavors", entries.len());
|
||||
let pack = Pack::new().u64(entries.len() as u64);
|
||||
Ok(entries
|
||||
.iter()
|
||||
.fold(pack, |pack, (mime, data)| pack.str(mime).blob(data))
|
||||
.bytes())
|
||||
}
|
||||
|
||||
/// Cuts the selection; a selection left behind is an error.
|
||||
pub(super) fn cut(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let id = unpack.u64()?;
|
||||
with_doc(id, |doc| {
|
||||
doc.post_uno(".uno:Cut", None)?;
|
||||
if doc.selection_type() != 0 {
|
||||
return Err(io::Error::other("the selection survived the cut"));
|
||||
}
|
||||
Ok(())
|
||||
})??;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// The undo entries, newest first.
|
||||
fn undo_entries(doc: &Document) -> io::Result<Vec<Step>> {
|
||||
crate::history::steps(&doc.command_values(".uno:Undo")?)
|
||||
}
|
||||
|
||||
/// Entries added since `before`; a full history drops old ones.
|
||||
fn new_steps(before: &[Step], after: &[Step]) -> usize {
|
||||
match before.first() {
|
||||
Some(top) => after
|
||||
.iter()
|
||||
.position(|entry| entry == top)
|
||||
.unwrap_or(after.len()),
|
||||
None => after.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every image a `data:` URI carries must decode.
|
||||
fn check_html_images(html: &str) -> io::Result<()> {
|
||||
use base64::Engine;
|
||||
for (at, _) in html.match_indices("data:image/") {
|
||||
let rest = &html[at..];
|
||||
let Some(comma) = rest.find(";base64,") else {
|
||||
return Err(invalid("an inline image is not base64"));
|
||||
};
|
||||
let body = &rest[comma + 8..];
|
||||
let end = body
|
||||
.find(|c: char| c == '"' || c == '\'' || c == ')' || c.is_whitespace())
|
||||
.unwrap_or(body.len());
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(&body[..end])
|
||||
.map_err(|error| invalid(&format!("an inline image is bad base64: {error}")))?;
|
||||
image::load_from_memory(&bytes)
|
||||
.map_err(|error| invalid(&format!("an inline image does not decode: {error}")))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuses payloads the engine would drop half way.
|
||||
fn check_payload(mime: &str, data: &[u8]) -> io::Result<()> {
|
||||
if data.is_empty() {
|
||||
return Err(invalid("an empty paste"));
|
||||
}
|
||||
if mime == "image/png" {
|
||||
image::load_from_memory_with_format(data, image::ImageFormat::Png)
|
||||
.map_err(|error| invalid(&format!("the png does not decode: {error}")))?;
|
||||
return Ok(());
|
||||
}
|
||||
let text = std::str::from_utf8(data).map_err(|_| invalid("the text is not UTF-8"))?;
|
||||
if mime == "text/html" {
|
||||
check_html_images(text)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pastes one flavor; a failed import is undone and reported.
|
||||
pub(super) fn paste(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, mime, data) = (unpack.u64()?, unpack.str()?, unpack.blob()?);
|
||||
if !CLIP_MIMES.contains(&mime.as_str()) {
|
||||
return Err(invalid("unsupported paste flavor"));
|
||||
}
|
||||
check_payload(&mime, &data)?;
|
||||
with_doc(id, |doc| {
|
||||
let before = undo_entries(doc)?;
|
||||
doc.set_clipboard(&mime, &data)?;
|
||||
doc.post_uno(".uno:Paste", Some(PASTE_ARGS))?;
|
||||
let steps = new_steps(&before, &undo_entries(doc)?);
|
||||
// A pasted image ends selected.
|
||||
let landed = steps > 0 && (mime != "image/png" || doc.selection_type() == 3);
|
||||
if landed {
|
||||
return Ok(());
|
||||
}
|
||||
for _ in 0..steps {
|
||||
doc.post_uno(".uno:Undo", None)?;
|
||||
}
|
||||
log::warn!("lok-worker: paste of {mime} failed, {steps} steps undone");
|
||||
Err(io::Error::other(format!("the engine did not paste {mime}")))
|
||||
})??;
|
||||
log::info!("lok-worker: pasted {mime}, {} bytes", data.len());
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(comment: &str, time: &str) -> (String, String) {
|
||||
(comment.into(), time.into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_steps_survive_a_full_history() {
|
||||
let old = vec![entry("Typing", "1"), entry("Typing", "0")];
|
||||
let grown = vec![entry("Paste", "2"), entry("Typing", "1")];
|
||||
assert_eq!(new_steps(&old, &grown), 1, "the cap dropped the oldest");
|
||||
assert_eq!(new_steps(&old, &old), 0);
|
||||
assert_eq!(new_steps(&[], &grown), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_must_decode() {
|
||||
let bad = r#"<img src="data:image/png;base64,dGhpcyBpcyBub3QgYSBwbmc=">"#;
|
||||
assert!(check_payload("text/html", bad.as_bytes()).is_err());
|
||||
assert!(check_payload("text/html", b"<b>plain</b>").is_ok());
|
||||
assert!(check_payload("text/html", br#"<img src="data:image/png,raw">"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Answers the kernel's password question during a load.
|
||||
|
||||
use std::{
|
||||
ffi::{CStr, c_char, c_void},
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
/// LOK_CALLBACK_DOCUMENT_PASSWORD.
|
||||
const PASSWORD: i32 = 20;
|
||||
|
||||
/// The password for the load in progress, given once.
|
||||
static GIVEN: Mutex<Option<String>> = Mutex::new(None);
|
||||
/// The kernel asked and got none.
|
||||
static REFUSED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Readies `password` for the next load.
|
||||
pub(super) fn arm(password: Option<String>) {
|
||||
*GIVEN.lock().expect("the password lock") = password;
|
||||
REFUSED.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether the last load lacked a right password.
|
||||
pub(super) fn refused() -> bool {
|
||||
REFUSED.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Answers once; a second ask means the password failed.
|
||||
pub(super) unsafe extern "C" fn on_kit(kind: i32, payload: *const c_char, _: *mut c_void) {
|
||||
if kind != PASSWORD || payload.is_null() {
|
||||
return;
|
||||
}
|
||||
let url = unsafe { CStr::from_ptr(payload) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let given = GIVEN.lock().expect("the password lock").take();
|
||||
log::info!(
|
||||
"lok-worker: a password asked, one given: {}",
|
||||
given.is_some()
|
||||
);
|
||||
REFUSED.store(given.is_none(), Ordering::SeqCst);
|
||||
super::lok().set_password(&url, given.as_deref());
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Each document's revision: requests that may change it count.
|
||||
|
||||
use std::{collections::HashMap, io, sync::Mutex};
|
||||
|
||||
use crate::ipc::{self, Pack, Unpack, tag};
|
||||
|
||||
fn revisions() -> &'static Mutex<HashMap<u64, u64>> {
|
||||
static REVISIONS: std::sync::OnceLock<Mutex<HashMap<u64, u64>>> = std::sync::OnceLock::new();
|
||||
REVISIONS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
/// A new session number: this process's prefix, then a count.
|
||||
pub fn session() -> u64 {
|
||||
static PREFIX: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
// Another worker's numbers match nothing here.
|
||||
let prefix = *PREFIX.get_or_init(|| {
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |at| at.subsec_nanos());
|
||||
(u64::from(std::process::id()) ^ u64::from(nanos)) & 0xffff_ffff
|
||||
});
|
||||
let id = (prefix << 32) | NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
revisions().lock().expect("the revisions lock").insert(id, 0);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn forget(id: u64) {
|
||||
revisions().lock().expect("the revisions lock").remove(&id);
|
||||
}
|
||||
|
||||
pub fn of(id: u64) -> io::Result<u64> {
|
||||
let revisions = revisions().lock().expect("the revisions lock");
|
||||
revisions.get(&id).copied().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such document"))
|
||||
}
|
||||
|
||||
/// The revision now, answered.
|
||||
pub fn current(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
Ok(Pack::new().u64(of(unpack.u64()?)?).bytes())
|
||||
}
|
||||
|
||||
/// Refuses unless the document is at the revision asked for.
|
||||
pub fn expect(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, expected) = (unpack.u64()?, unpack.u64()?);
|
||||
let now = of(id)?;
|
||||
match now == expected {
|
||||
true => Ok(Vec::new()),
|
||||
false => Err(io::Error::other(format!("{}document {id} is at {now}, not {expected}", ipc::STALE))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Before `request` runs: input and commands may change the document.
|
||||
pub fn bump(request: u8, payload: &[u8]) {
|
||||
let changes = matches!(
|
||||
request,
|
||||
tag::POST_KEY | tag::POST_MOUSE | tag::GRAPHIC | tag::POST_TEXT | tag::POST_UNO | tag::PASTE | tag::CUT | tag::COMPLETE_FUNCTION
|
||||
);
|
||||
let mut unpack = Unpack::new(payload);
|
||||
let Ok(id) = unpack.u64() else {
|
||||
return;
|
||||
};
|
||||
if !changes || request == tag::POST_MOUSE && hover(&mut unpack) {
|
||||
return;
|
||||
}
|
||||
if let Some(revision) = revisions().lock().expect("the revisions lock").get_mut(&id) {
|
||||
*revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move with no button held changes nothing.
|
||||
fn hover(unpack: &mut Unpack) -> bool {
|
||||
// Kind, x, y, count, buttons; kind 2 is a move.
|
||||
let fields: Result<Vec<i64>, _> = (0..5).map(|_| unpack.i64()).collect();
|
||||
fields.is_ok_and(|fields| fields[0] == 2 && fields[4] == 0)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use std::io;
|
||||
|
||||
use super::with_doc;
|
||||
use crate::ipc::{self, Pack, Unpack};
|
||||
|
||||
/// Slide `part`'s slideshow layers at about the asked pixels.
|
||||
pub(super) fn slide_layers(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, part) = (unpack.u64()?, unpack.u64()?);
|
||||
let (width, height) = (unpack.u64()?, unpack.u64()?);
|
||||
let bad = |what: &str| io::Error::new(io::ErrorKind::InvalidInput, what.to_string());
|
||||
let part = i32::try_from(part).map_err(|_| bad("bad part"))?;
|
||||
let pixels = (u32::try_from(width), u32::try_from(height));
|
||||
let (Ok(width), Ok(height)) = pixels else {
|
||||
return Err(bad("bad size"));
|
||||
};
|
||||
with_doc(id, |doc| {
|
||||
let info: serde_json::Value =
|
||||
serde_json::from_str(&doc.presentation_info()?).map_err(io::Error::other)?;
|
||||
let slide = usize::try_from(part).ok().and_then(|at| info["slides"].get(at));
|
||||
let hash = slide
|
||||
.and_then(|slide| slide["hash"].as_str())
|
||||
.ok_or_else(|| bad("no such slide"))?;
|
||||
let ((width, height), layers) =
|
||||
doc.slide_layers((part, hash), (width, height), ipc::MAX_FRAME - 1024)?;
|
||||
let mut body = Pack::new()
|
||||
.u64(u64::from(width))
|
||||
.u64(u64::from(height))
|
||||
.u64(layers.len() as u64);
|
||||
for layer in &layers {
|
||||
body = body.str(&layer.json).u64(u64::from(layer.pixels.is_some()));
|
||||
if let Some(pixels) = &layer.pixels {
|
||||
body = body.blob(pixels);
|
||||
}
|
||||
}
|
||||
Ok(body.bytes())
|
||||
})?
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
use std::{io, path::Path};
|
||||
|
||||
use super::{LOK, docs, quit};
|
||||
|
||||
/// Frees documents, destroys the kit, and reports what failed (LOK-10).
|
||||
pub(super) fn teardown_work() -> io::Result<()> {
|
||||
let mut docs = docs().lock().expect("the docs lock");
|
||||
crate::events::stop_all(&docs);
|
||||
docs.clear();
|
||||
let kit = LOK.swap(std::ptr::null_mut(), std::sync::atomic::Ordering::SeqCst);
|
||||
if !kit.is_null() {
|
||||
let kit = unsafe { Box::from_raw(kit) };
|
||||
let joined = kit.join_threads();
|
||||
log::info!("lok-worker: threads joined={joined}");
|
||||
drop(kit);
|
||||
}
|
||||
let Some(profile) = PROFILE.get() else {
|
||||
return Ok(());
|
||||
};
|
||||
let lock = profile.join(".lock");
|
||||
match std::fs::remove_file(&lock) {
|
||||
Ok(()) => log::info!("lok-worker: stale profile lock removed"),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
return Err(io::Error::new(
|
||||
error.kind(),
|
||||
format!("profile lock stays: {error}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
let temp = profile.join("tmp");
|
||||
let entries = match std::fs::read_dir(&temp) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => {
|
||||
return Err(io::Error::new(
|
||||
error.kind(),
|
||||
format!("temp dir unreadable: {error}"),
|
||||
));
|
||||
}
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
if !name.to_string_lossy().starts_with("lu") {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
unprotect(&path);
|
||||
let gone = if path.is_dir() {
|
||||
std::fs::remove_dir_all(&path)
|
||||
} else {
|
||||
std::fs::remove_file(&path)
|
||||
};
|
||||
gone.map_err(|error| {
|
||||
io::Error::new(
|
||||
error.kind(),
|
||||
format!("temp {} stays: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
log::info!("lok-worker: torn down");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tears down and exits with the work's verdict.
|
||||
pub(super) fn teardown(code: i32) -> ! {
|
||||
let outcome = teardown_work();
|
||||
if let Err(error) = &outcome {
|
||||
log::warn!("lok-worker: teardown failed: {error}");
|
||||
}
|
||||
quit(if outcome.is_ok() { code } else { 1 });
|
||||
}
|
||||
|
||||
/// Clears macOS's immutable flag on a kernel temp file.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn unprotect(path: &Path) {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let Some(c) = std::ffi::CString::new(path.as_os_str().as_bytes()).ok() else {
|
||||
return;
|
||||
};
|
||||
unsafe { libc::chflags(c.as_ptr(), 0) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn unprotect(_: &Path) {}
|
||||
|
||||
/// The isolated profile directory, for the stale lock at exit.
|
||||
pub(super) static PROFILE: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
|
||||
@@ -0,0 +1,59 @@
|
||||
//! CSV in and out, from typed fields only (TABLE-12, 13).
|
||||
|
||||
use std::io;
|
||||
|
||||
use super::{close, load, with_doc};
|
||||
use crate::ffi::Lok;
|
||||
use crate::ipc::Unpack;
|
||||
|
||||
/// Loads a text file from typed CSV options.
|
||||
pub(super) fn import(lok: &Lok, unpack: &mut Unpack) -> io::Result<u64> {
|
||||
use crate::sheet::csv::{COLUMNS, ENCODINGS, Import};
|
||||
let bad = |what: &str| io::Error::new(io::ErrorKind::InvalidInput, format!("a bad {what}"));
|
||||
let url = unpack.str()?;
|
||||
let character = |code: u64| u32::try_from(code).ok().and_then(char::from_u32);
|
||||
let separator = character(unpack.u64()?).ok_or_else(|| bad("separator"))?;
|
||||
let quote = match unpack.u64()? {
|
||||
0 => None,
|
||||
code => Some(character(code).ok_or_else(|| bad("quote"))?),
|
||||
};
|
||||
let pick = |at: u64, len| usize::try_from(at).ok().filter(|at| *at < len);
|
||||
let encoding =
|
||||
ENCODINGS[pick(unpack.u64()?, ENCODINGS.len()).ok_or_else(|| bad("encoding"))?];
|
||||
let columns = (0..unpack.u64()?)
|
||||
.map(|_| {
|
||||
let at = pick(unpack.u64()?, COLUMNS.len()).ok_or_else(|| bad("column"))?;
|
||||
Ok(COLUMNS[at])
|
||||
})
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let how = Import {
|
||||
separator,
|
||||
quote,
|
||||
encoding,
|
||||
columns,
|
||||
};
|
||||
let filter = format!("FilterName=Text - txt - csv (StarCalc),{}", how.filter());
|
||||
let id = load(lok, &url, String::new(), &filter)?;
|
||||
// A .txt name must not land in Writer.
|
||||
let kind = with_doc(id, |doc| doc.kind())?;
|
||||
if kind != 1 {
|
||||
close(id);
|
||||
return Err(io::Error::other(format!(
|
||||
"the text loaded as kind {kind}, not a sheet"
|
||||
)));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Writes the shown sheet as text from a typed separator.
|
||||
pub(super) fn export(unpack: &mut Unpack) -> io::Result<()> {
|
||||
let (id, url) = (unpack.u64()?, unpack.str()?);
|
||||
let separator = u32::try_from(unpack.u64()?)
|
||||
.ok()
|
||||
.and_then(char::from_u32)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "a bad separator"))?;
|
||||
let options = crate::sheet::csv::export(separator);
|
||||
with_doc(id, |doc| doc.save_as(&url, "csv", &options))??;
|
||||
log::info!("lok-worker: exported text split by {separator:?}");
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user