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

+44
View File
@@ -0,0 +1,44 @@
[package]
name = "ely-lok"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
ely-ipc.workspace = true
base64.workspace = true
serde_json.workspace = true
env_logger.workspace = true
log.workspace = true
gpui = { workspace = true, optional = true }
ely-gpui-component = { workspace = true, optional = true }
ely-platform = { workspace = true, optional = true }
futures = { workspace = true, optional = true }
image.workspace = true
[features]
view = ["dep:gpui", "dep:ely-gpui-component", "dep:ely-platform", "dep:futures"]
[target.'cfg(unix)'.dependencies]
libc.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys.workspace = true
[dev-dependencies]
tempfile.workspace = true
ely-ui.workspace = true
gpui = { workspace = true, features = ["test-support"] }
[[example]]
name = "lokview"
required-features = ["view"]
[[bin]]
name = "ely-lok-worker"
path = "src/bin/ely-lok-worker.rs"
[lints]
workspace = true
+215
View File
@@ -0,0 +1,215 @@
//! A live LokView in ElyDoc's shell, driven by input events.
use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
use ely_lok::{Doc, LokView, Worker};
use ely_platform::{AppId, clipboard};
use gpui::{
App, Bounds, ElementInputHandler, Entity, InputHandler, KeyUpEvent, Keystroke, Modifiers,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, PlatformInput, Point,
Window,
};
/// Line centers and text edges in twips, measured.
const LINE_ONE: i32 = 1556;
const LINE_TWO: i32 = 1832;
const TEXT_LEFT: i32 = 1420;
const PAST_END: i32 = 8000;
fn main() {
ely_ui::run(AppId::Doc, |app, window, cx| {
ely_lok::init(cx);
let install =
PathBuf::from(std::env::var("ELY_LOK_DIR").expect("ELY_LOK_DIR names the LOK build"));
let dir = tempfile::tempdir().expect("a temp dir").keep();
let mut worker = Worker::spawn(&install, &dir.join("profile")).expect("the worker spawns");
let source = dir.join("probe.fodt");
std::fs::write(&source, FODT).expect("the fodt writes");
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let worker = Arc::new(Mutex::new(worker));
let laid = ely_lok::layout(&mut worker.lock().expect("the worker lock"), &doc)
.expect("the layout reads");
let view = LokView::open(Arc::clone(&worker), doc.clone(), laid, cx);
let probe = Probe {
view: view.clone(),
worker,
doc,
dir,
};
window.on_next_frame(move |window, cx| probe.step(0, 0, window, cx));
ely_ui::root(app, Some(view.into()), window, cx)
});
}
const FODT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:body><office:text><text:p>Hello 世界</text:p><text:p>Second line</text:p></office:text></office:body>
</office:document>"#;
struct Probe {
view: Entity<LokView>,
worker: Arc<Mutex<Worker>>,
doc: Doc,
dir: PathBuf,
}
fn key(text: &str) -> Keystroke {
Keystroke::parse(text).expect("a keystroke")
}
fn typed(text: &str) -> Keystroke {
Keystroke {
key_char: Some(text.into()),
..key(text)
}
}
fn press(window: &mut Window, stroke: Keystroke, cx: &mut App) {
window.dispatch_keystroke(stroke.clone(), cx);
window.dispatch_event(PlatformInput::KeyUp(KeyUpEvent { keystroke: stroke }), cx);
}
/// Holds the window for an outside AX reader, then quits.
fn hold(cx: &mut App) {
println!("probe: ax hold");
cx.spawn(async move |cx| {
cx.background_executor()
.timer(std::time::Duration::from_secs(8))
.await;
cx.update(|cx| cx.quit());
})
.detach();
}
/// A left drag from `from` to `to`; equal points click.
fn drag(window: &mut Window, from: Point<Pixels>, to: Point<Pixels>, cx: &mut App) {
let modifiers = Modifiers::default();
window.dispatch_event(
PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: from,
modifiers,
click_count: 1,
first_mouse: false,
}),
cx,
);
if from != to {
window.dispatch_event(
PlatformInput::MouseMove(MouseMoveEvent {
position: to,
pressed_button: Some(MouseButton::Left),
modifiers,
}),
cx,
);
}
window.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: to,
modifiers,
click_count: 1,
}),
cx,
);
}
impl Probe {
/// One step per settled frame window; `wait` counts frames.
fn step(self, step: usize, wait: usize, window: &mut Window, cx: &mut App) {
if wait < 40 {
window.on_next_frame(move |window, cx| self.step(step, wait + 1, window, cx));
return;
}
let clipboard_on = std::env::var_os("ELY_CLIPBOARD_TEST").is_some();
let at = |cx: &App, x, y| self.view.read(cx).window_point((x, y));
match step {
0 => {
let focus = self.view.read(cx).focus_handle().clone();
window.focus(&focus, cx);
if std::env::var("ELY_PROBE_AX").as_deref() == Ok("initial") {
hold(cx);
return;
}
let mut ime = ElementInputHandler::new(Bounds::default(), self.view.clone());
ime.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
ime.replace_and_mark_text_in_range(Some(0..2), "你好", None, window, cx);
ime.unmark_text(window, cx);
ime.replace_and_mark_text_in_range(None, "zz", None, window, cx);
ime.replace_and_mark_text_in_range(None, "", None, window, cx);
}
1 => {
let end = at(cx, PAST_END, LINE_ONE);
drag(window, end, end, cx);
press(window, typed("X"), cx);
}
2 => {
let (from, to) = (at(cx, TEXT_LEFT, LINE_TWO), at(cx, PAST_END, LINE_TWO));
drag(window, from, to, cx);
press(window, typed("Z"), cx);
println!(
"probe: focused={}",
self.view.read(cx).focus_handle().is_focused(window)
);
}
3 if clipboard_on => {
press(window, key("secondary-a"), cx);
press(window, key("secondary-c"), cx);
}
4 if clipboard_on => {
let copied = clipboard::read().expect("the clipboard reads");
println!("probe: copied={copied:?}");
press(window, key("secondary-end"), cx);
press(window, key("enter"), cx);
press(window, key("secondary-v"), cx);
}
3 | 4 => {}
_ => {
let out = self.dir.join("out.fodt");
let mut worker = self.worker.lock().expect("the worker lock");
self.doc
.save_as(&mut worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
let xml = std::fs::read_to_string(&out).expect("the save reads");
println!("probe: paragraphs={}", paragraphs(&xml).join("|"));
drop(worker);
if std::env::var("ELY_PROBE_AX").as_deref() == Ok("edited") {
hold(cx);
return;
}
cx.quit();
return;
}
}
window.on_next_frame(move |window, cx| self.step(step + 1, 0, window, cx));
}
}
/// Each paragraph's text, tags stripped.
fn paragraphs(xml: &str) -> Vec<String> {
xml.split("<text:p")
.skip(1)
.map(|rest| {
let body = &rest[rest.find('>').map_or(0, |at| at + 1)..];
let body = &body[..body.find("</text:p>").unwrap_or(0)];
let mut text = String::new();
let mut tag = false;
for c in body.chars() {
match c {
'<' => tag = true,
'>' => tag = false,
c if !tag => text.push(c),
_ => {}
}
}
text
})
.collect()
}
+18
View File
@@ -0,0 +1,18 @@
use std::io;
fn main() {
// As the app: ELY_LOG, info by default.
env_logger::Builder::from_env(env_logger::Env::new().filter_or("ELY_LOG", "info")).init();
let args: Vec<String> = std::env::args().collect();
let Some((install, profile)) = args.get(1).zip(args.get(2)) else {
log::error!("usage: ely-lok-worker <install-path> <profile-dir>");
std::process::exit(2);
};
let input = io::stdin();
let output = io::stdout();
if let Err(error) = ely_lok::worker_run(install, profile, input, output) {
// A record, so the app's relay passes it on.
log::error!("lok-worker: {error}");
std::process::exit(1);
}
}
+486
View File
@@ -0,0 +1,486 @@
use std::{
io::{self, BufReader, BufWriter},
path::{Path, PathBuf},
process::{Child, ChildStdin, Command, Stdio},
sync::mpsc,
};
use crate::ipc::{self, Pack, Unpack, tag};
pub use crate::events::{A11y, Cell, Events, Function, MIXED, Mark, Rect, Request};
/// The pinned LibreOffice build the worker must report (LOK-01).
pub const BUILD_ID: &str = "8221e31b3ac356a1623c672912a3d2b492f7e3d1";
mod doc;
mod feed;
mod frames;
mod install;
pub use install::{install_dir, templates};
use install::worker_bin;
pub use doc::{Pdf, Sheet, Sheets};
pub use feed::Feed;
#[cfg(test)]
pub(crate) mod tests;
/// The LOK worker process: spawn, talk frames, shut down (LOK-01).
pub struct Worker {
pub(crate) child: Child,
stdin: BufWriter<ChildStdin>,
/// Answers to requests; None once the worker is gone.
replies: mpsc::Receiver<io::Result<(u8, u64, Vec<u8>)>>,
feed: Feed,
down: bool,
/// The last request's id; each reply must carry it.
asked: u64,
/// This worker among all spawned; its documents carry it.
session: u64,
stderr: ely_ipc::Relay,
check: Check,
}
/// The start-up check: to run, passed, or why it failed.
enum Check {
Pending(PathBuf),
Passed,
Failed(String),
}
/// One painted tile and the generation it matches (LOK-03).
pub struct Tile {
pub generation: u64,
pub pixels: Vec<u8>,
}
/// One LOK mouse event; coordinates in twips.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mouse {
/// 0 down, 1 up, 2 move.
pub kind: i32,
pub x: i32,
pub y: i32,
pub count: i32,
/// 1 left, 2 middle, 4 right.
pub buttons: i32,
/// vcl modifier bits.
pub modifiers: i32,
}
/// One open document: its worker, number and revision read.
#[derive(Clone, Debug, PartialEq)]
pub struct Doc {
worker: u64,
id: u64,
/// The document's revision when this handle was taken.
pub(crate) rev: u64,
}
impl Doc {
/// Whether this handle saw a later state than `other`.
pub fn newer_than(&self, other: &Doc) -> bool {
self.rev > other.rev
}
}
/// Whether `error` refused a request made for an older state.
pub fn is_stale(error: &io::Error) -> bool {
error.to_string().starts_with(ipc::STALE)
}
static SESSIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl Worker {
/// Spawns the worker against `install` with an isolated profile (LOK-01).
pub fn spawn(install: &Path, profile_dir: &Path) -> io::Result<Self> {
let mut worker = Self::spawn_mode(install, profile_dir, false)?;
worker.ready()?;
Ok(worker)
}
/// Starts the process only; the first request checks it.
pub fn launch(install: &Path, profile_dir: &Path) -> io::Result<Self> {
Self::spawn_mode(install, profile_dir, false)
}
/// Spawns with the dev-only probes on, for tests.
pub fn spawn_dev(install: &Path, profile_dir: &Path) -> io::Result<Self> {
let mut worker = Self::spawn_mode(install, profile_dir, true)?;
worker.ready()?;
Ok(worker)
}
/// Checks the pinned build and tiles, once (LOK-01).
pub fn ready(&mut self) -> io::Result<()> {
let profile = match &self.check {
Check::Passed => return Ok(()),
Check::Failed(why) => return Err(io::Error::other(format!("the worker failed its check: {why}"))),
Check::Pending(profile) => profile.clone(),
};
// Marked first: the checks' own requests pass through here.
self.check = Check::Passed;
let checked = self.version_checked().and_then(|build| self.verify(&build, &profile).map(|()| build));
match checked {
Ok(build) => {
log::info!("lok: worker up, {build}");
Ok(())
}
Err(error) => {
self.check = Check::Failed(error.to_string());
Err(error)
}
}
}
/// Spawns with or without the dev probes.
fn spawn_mode(install: &Path, profile_dir: &Path, dev: bool) -> io::Result<Self> {
std::fs::create_dir_all(profile_dir)?;
let worker_bin = worker_bin()?;
log::info!("lok: worker from {}", worker_bin.display());
let mut command = Command::new(worker_bin);
command
.arg(install)
.arg(profile_dir)
.env("SAL_FORCE_HIDPI_SCALING", "1")
.env("SAL_SKIA", "raster");
// Calc reports in document twips, as its geometry does.
let options = match cfg!(target_os = "macos") {
true => "unipoll:sc_print_twips_msgs",
false => "sc_print_twips_msgs",
};
command.env("SAL_LOK_OPTIONS", options);
if dev {
command.arg("--dev");
}
if let Ok(sal_log) = std::env::var("ELY_LOK_SAL_LOG") {
command.env("SAL_LOG", sal_log);
}
let temp = profile_dir.join("tmp");
std::fs::create_dir_all(&temp)?;
command.env("TMPDIR", &temp);
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| io::Error::new(error.kind(), format!("lok-worker spawn: {error}")))?;
let stderr = ely_ipc::relay(child.stderr.take().expect("piped stderr"), "lok-worker");
let (stdin, stdout) = (
child.stdin.take().expect("piped stdin"),
child.stdout.take().expect("piped stdout"),
);
let (feed, (sender, replies)) = (Feed::default(), mpsc::channel());
let reading = feed.clone();
std::thread::spawn(move || frames::read_frames(BufReader::new(stdout), &reading, &sender));
let worker = Self {
child,
stdin: BufWriter::new(stdin),
replies,
feed,
down: false,
asked: 0,
session: SESSIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
stderr,
check: Check::Pending(profile_dir.to_path_buf()),
};
Ok(worker)
}
/// The hooked library's BuildId.
pub fn build_id(&mut self) -> io::Result<String> {
let payload = self.request(tag::BUILD_ID, &[])?;
Unpack::new(&payload).str()
}
/// The name new comments and tracked changes carry.
pub fn set_author(&mut self, name: &str) -> io::Result<()> {
log::info!("lok: the author is set");
self.request(tag::SET_AUTHOR, &Pack::new().str(name).bytes())?;
Ok(())
}
/// Loads `url`; macros never run (LOK-11).
pub fn load(&mut self, url: &str) -> io::Result<Doc> {
self.unlock(url, "")
}
/// Loads text `url` as a sheet, read as `how` says.
pub fn import(&mut self, url: &str, how: &crate::sheet::csv::Import) -> io::Result<Doc> {
use crate::sheet::csv::{COLUMNS, ENCODINGS};
let at = |found: Option<usize>| found.expect("a listed choice") as u64;
let pack = Pack::new()
.str(url)
.u64(u64::from(how.separator))
.u64(how.quote.map_or(0, u64::from))
.u64(at(ENCODINGS.iter().position(|e| *e == how.encoding)))
.u64(how.columns.len() as u64);
let pack = how.columns.iter().fold(pack, |pack, column| {
pack.u64(at(COLUMNS.iter().position(|c| c == column)))
});
let payload = self.request(tag::IMPORT, &pack.bytes())?;
let id = Unpack::new(&payload).u64()?;
self.feed.opened(id);
Ok(Doc { worker: self.session, id, rev: 0 })
}
/// Loads `url` with its password; a locked one is PermissionDenied.
pub fn unlock(&mut self, url: &str, password: &str) -> io::Result<Doc> {
let request = Pack::new().str(url).str(password).bytes();
let payload = self.request(tag::LOAD, &request).map_err(|error| {
if error.to_string() == crate::ipc::LOCKED {
io::Error::new(io::ErrorKind::PermissionDenied, error.to_string())
} else {
error
}
})?;
let id = Unpack::new(&payload).u64()?;
self.feed.opened(id);
Ok(Doc { worker: self.session, id, rev: 0 })
}
/// Runs a macro by its URL (LOK-11 probe).
pub fn run_macro(&mut self, url: &str) -> io::Result<i32> {
let payload = self.request(tag::RUN_MACRO, &Pack::new().str(url).bytes())?;
Ok(Unpack::new(&payload).u64()? as i32)
}
/// Posts a key press and release (LOK-06).
pub fn post_key(&mut self, doc: &Doc, char_code: u32, key_code: i32) -> io::Result<()> {
self.request(
tag::POST_KEY,
&Pack::new()
.u64(self.doc_id(doc)?)
.i64(char_code as i64)
.i64(key_code as i64)
.bytes(),
)?;
Ok(())
}
/// Drags a selected object's handle, start then end.
pub fn drag_graphic(&mut self, doc: &Doc, from: (i32, i32), to: (i32, i32)) -> io::Result<()> {
for (kind, (x, y)) in [(0, from), (1, to)] {
let pack = Pack::new()
.u64(self.doc_id(doc)?)
.i64(kind)
.i64(x.into())
.i64(y.into());
self.request(tag::GRAPHIC, &pack.bytes())?;
}
Ok(())
}
/// Posts one mouse event in twips (LOK-04).
pub fn post_mouse(&mut self, doc: &Doc, event: Mouse) -> io::Result<()> {
let pack = [
event.kind as i64,
event.x as i64,
event.y as i64,
event.count as i64,
event.buttons as i64,
event.modifiers as i64,
]
.into_iter()
.fold(Pack::new().u64(self.doc_id(doc)?), Pack::i64);
self.request(tag::POST_MOUSE, &pack.bytes())?;
Ok(())
}
/// Updates the IME composition, or commits it (LOK-07).
pub fn post_text(&mut self, doc: &Doc, commit: bool, text: &str) -> io::Result<()> {
let kind = if commit { 2 } else { 0 };
self.request(
tag::POST_TEXT,
&Pack::new().u64(self.doc_id(doc)?).i64(kind).str(text).bytes(),
)?;
Ok(())
}
/// Copies the selection; one (mime, bytes) per flavor (LOK-06).
pub fn copy(&mut self, doc: &Doc) -> io::Result<Vec<(String, Vec<u8>)>> {
let payload = self.request(tag::COPY, &Pack::new().u64(self.doc_id(doc)?).bytes())?;
let mut unpack = Unpack::new(&payload);
let count = unpack.u64()?;
(0..count)
.map(|_| Ok((unpack.str()?, unpack.blob()?)))
.collect()
}
/// Cuts the selection after a copy went out (LOK-06).
pub fn cut(&mut self, doc: &Doc) -> io::Result<()> {
self.request(tag::CUT, &Pack::new().u64(self.doc_id(doc)?).bytes())?;
Ok(())
}
/// Pastes one flavor into the document (LOK-06).
pub fn paste(&mut self, doc: &Doc, mime: &str, data: &[u8]) -> io::Result<()> {
self.request(
tag::PASTE,
&Pack::new().u64(self.doc_id(doc)?).str(mime).blob(data).bytes(),
)?;
Ok(())
}
/// Runs a table command; the worker confirms it took (LOK-02).
pub fn run(&mut self, doc: &Doc, id: &str, values: &[&str]) -> io::Result<()> {
self.run_all(doc, &[(id, values)])
}
/// Commands made from one read; the state is checked once.
pub fn run_all(&mut self, doc: &Doc, commands: &[(&str, &[&str])]) -> io::Result<()> {
let mut addressed = false;
for (id, values) in commands {
let command = crate::commands::find(id)?;
command.args_json(values)?;
addressed |= command.addressed(values);
}
// Numbers hold only in the state they were read.
if addressed {
self.request(tag::EXPECT, &Pack::new().u64(self.doc_id(doc)?).u64(doc.rev).bytes())?;
}
for (id, values) in commands {
let pack = values.iter().fold(
Pack::new().u64(self.doc_id(doc)?).str(id).u64(values.len() as u64),
|pack, value| pack.str(value),
);
self.request(tag::POST_UNO, &pack.bytes())?;
}
Ok(())
}
/// `doc` as of now: commands by number use this revision.
pub fn now(&mut self, doc: &Doc) -> io::Result<Doc> {
let payload = self.request(tag::REVISION, &Pack::new().u64(self.doc_id(doc)?).bytes())?;
Ok(Doc { rev: Unpack::new(&payload).u64()?, ..doc.clone() })
}
/// `doc`'s number here; another worker's document is refused.
pub(crate) fn doc_id(&self, doc: &Doc) -> io::Result<u64> {
match doc.worker == self.session {
true => Ok(doc.id),
false => Err(io::Error::new(io::ErrorKind::NotFound, "a document of another lok worker")),
}
}
/// The kernel's JSON list for `command`: fonts or styles (LOK-05).
pub fn values(&mut self, doc: &Doc, command: &str) -> io::Result<String> {
let payload = self.request(tag::VALUES, &Pack::new().u64(self.doc_id(doc)?).str(command).bytes())?;
Unpack::new(&payload).str()
}
/// Events past seq `known`, waiting up to `timeout_ms`.
pub fn poll_events(&self, doc: &Doc, known: u64, timeout_ms: u64) -> io::Result<Events> {
self.feed.wait(doc, known, timeout_ms)
}
/// The pushed events, waited on without this worker's lock.
pub fn feed(&self) -> Feed {
self.feed.clone()
}
/// A worker whose output failed: stopped, reaped, and why.
fn broken(&mut self, request: u8, error: io::Error) -> io::Error {
let _ = self.child.kill();
let status = self.child.wait().map(|status| status.to_string()).unwrap_or_else(|wait| wait.to_string());
log::error!("lok: the worker failed on request {request} ({status})");
let said = self.stderr.last_error().map_or_else(String::new, |said| format!(": {said}"));
io::Error::new(error.kind(), format!("the lok worker failed: {error} ({status}){said}"))
}
/// One round trip per request.
pub(crate) fn request(&mut self, request: u8, payload: &[u8]) -> io::Result<Vec<u8>> {
// Nothing reaches a worker that has not passed its checks.
self.ready()?;
self.asked += 1;
ipc::write_frame(&mut self.stdin, request, self.asked, payload)?;
let (reply, id, body) = match self.replies.recv() {
Ok(Ok(frame)) => frame,
Ok(Err(error)) => return Err(self.broken(request, error)),
Err(_) => return Err(self.broken(request, io::Error::other("the reply reader stopped"))),
};
if let Err(error) = ipc::check_reply(self.asked, id) {
return Err(self.broken(request, error));
}
match reply {
tag::OK => Ok(body),
tag::ERR => Err(io::Error::other(Unpack::new(&body).str()?)),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unknown reply {other}"),
)),
}
}
/// Why the worker process ended, if it has.
pub fn ended(&mut self) -> Option<String> {
match self.child.try_wait() {
Ok(status) => status.map(|status| status.to_string()),
Err(error) => Some(error.to_string()),
}
}
/// Closes the document in the worker.
pub fn close_doc(&mut self, doc: Doc) -> io::Result<()> {
self.request(tag::CLOSE_DOC, &Pack::new().u64(self.doc_id(&doc)?).bytes())?;
self.feed.closed(doc.id);
Ok(())
}
/// Shuts the worker down and reaps it.
pub fn shutdown(&mut self) -> io::Result<()> {
if self.down {
return Ok(());
}
self.down = true;
let mut outcome = self.answer_shutdown();
if outcome.is_err() {
let _ = self.child.kill();
}
let status = match self.child.wait() {
Ok(status) => status,
Err(error) => {
let _ = self.child.kill();
return Err(io::Error::new(
error.kind(),
format!("the lok worker could not be reaped: {error}"),
));
}
};
if outcome.is_ok() && !status.success() {
outcome = Err(io::Error::other(format!(
"the lok worker exited as {status}"
)));
}
if outcome.is_ok() {
log::info!("lok: worker down ({status})");
}
outcome
}
/// The shutdown round trip alone.
fn answer_shutdown(&mut self) -> io::Result<()> {
self.asked += 1;
ipc::write_frame(&mut self.stdin, tag::SHUTDOWN, self.asked, &[])?;
let reply = match self.replies.recv() {
Ok(Ok(frame)) => frame,
Ok(Err(error)) => return Err(self.broken(tag::SHUTDOWN, error)),
Err(_) => return Err(self.broken(tag::SHUTDOWN, io::Error::other("the reply reader stopped"))),
};
ipc::check_reply(self.asked, reply.1)?;
match reply {
(tag::OK, _, _) => Ok(()),
(tag::ERR, _, body) => Err(io::Error::other(Unpack::new(&body).str()?)),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("bad shutdown answer: {other:?}"),
)),
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
if let Err(error) = self.shutdown() {
log::warn!("lok: shutdown failed: {error}");
}
}
}
+233
View File
@@ -0,0 +1,233 @@
//! A document's requests: size, pages, tiles, saving.
use std::io;
use super::{Doc, Rect, Tile, Worker};
use crate::ipc::{Pack, Unpack, tag};
/// How a PDF goes out: pages, comments, tracked changes.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Pdf {
/// First and last page, from 1; None is every page.
pub pages: Option<(u32, u32)>,
/// Comments print in the margin.
pub comments: bool,
/// Tracked changes show as marked.
pub changes: bool,
/// Slides per handout page; 0 prints the slides.
pub handouts: u8,
}
/// One sheet: its name and whether it shows.
#[derive(Clone, Debug, PartialEq)]
pub struct Sheet {
pub name: String,
pub visible: bool,
}
/// The sheets of a spreadsheet and the shown one.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Sheets {
pub current: usize,
pub list: Vec<Sheet>,
}
impl Doc {
/// The sheets, in order, and the one shown.
pub fn sheets(&self, worker: &mut Worker) -> io::Result<Sheets> {
let payload = worker.request(tag::SHEETS, &Pack::new().u64(worker.doc_id(self)?).bytes())?;
let mut unpack = Unpack::new(&payload);
let current = usize::try_from(unpack.u64()?).map_err(io::Error::other)?;
let count = unpack.u64()?;
let list = (0..count)
.map(|_| {
let name = unpack.str()?;
let info: serde_json::Value = serde_json::from_str(&unpack.str()?)
.map_err(|error| io::Error::other(format!("bad part info: {error}")))?;
let visible = match info["visible"].as_u64() {
Some(1) => true,
Some(0) => false,
_ => return Err(io::Error::other(format!("no visibility: {info}"))),
};
Ok(Sheet { name, visible })
})
.collect::<io::Result<_>>()?;
Ok(Sheets { current, list })
}
/// Tells the kernel the area the view shows, in twips.
pub fn visible_area(&self, worker: &mut Worker, (x, y, w, h): Rect) -> io::Result<()> {
let request = Pack::new()
.u64(worker.doc_id(self)?)
.i64(x.into())
.i64(y.into())
.i64(w.into())
.i64(h.into())
.bytes();
worker.request(tag::VISIBLE_AREA, &request)?;
Ok(())
}
/// The selection as plain text; Calc joins cells by tabs.
pub fn selection_text(&self, worker: &mut Worker) -> io::Result<String> {
let payload = worker.request(tag::SELECTION_TEXT, &Pack::new().u64(worker.doc_id(self)?).bytes())?;
Unpack::new(&payload).str()
}
/// Completes the function name being typed (TABLE-03).
pub fn complete_function(&self, worker: &mut Worker, name: &str) -> io::Result<()> {
log::info!("lok: completes a function");
let request = Pack::new().u64(worker.doc_id(self)?).str(name).bytes();
worker.request(tag::COMPLETE_FUNCTION, &request)?;
Ok(())
}
/// Shows sheet `part`, from 0.
pub fn show_sheet(&self, worker: &mut Worker, part: usize) -> io::Result<()> {
let request = Pack::new().u64(worker.doc_id(self)?).u64(part as u64).bytes();
worker.request(tag::SHOW_SHEET, &request)?;
Ok(())
}
/// Page count or area in LOK twips.
pub fn size(&self, worker: &mut Worker) -> io::Result<(i64, i64)> {
let payload = worker.request(tag::DOC_SIZE, &Pack::new().u64(worker.doc_id(self)?).bytes())?;
let mut unpack = Unpack::new(&payload);
Ok((unpack.i64()?, unpack.i64()?))
}
/// Page rectangles in twips; empty without pages.
pub fn pages(&self, worker: &mut Worker) -> io::Result<Vec<Rect>> {
let payload = worker.request(tag::PAGES, &Pack::new().u64(worker.doc_id(self)?).bytes())?;
let text = Unpack::new(&payload).str()?;
text.split(';')
.filter(|part| !part.trim().is_empty())
.map(|part| {
let numbers: Vec<i32> = part
.split(',')
.map(|n| {
n.trim()
.parse()
.map_err(|_| io::Error::other(format!("a bad page rect: {part}")))
})
.collect::<io::Result<_>>()?;
match numbers.as_slice() {
[x, y, w, h] => Ok((*x, *y, *w, *h)),
_ => Err(io::Error::other(format!("a bad page rect: {part}"))),
}
})
.collect()
}
/// Paints one tile: twips rect into a pixel size.
pub fn paint_tile(
&self,
worker: &mut Worker,
twips: (i32, i32, i32, i32),
pixels: (u32, u32),
) -> io::Result<Tile> {
let (x, y, w, h) = twips;
let (pw, ph) = pixels;
let payload = worker.request(
tag::PAINT_TILE,
&Pack::new()
.u64(worker.doc_id(self)?)
.i64(x as i64)
.i64(y as i64)
.i64(w as i64)
.i64(h as i64)
.i64(pw as i64)
.i64(ph as i64)
.bytes(),
)?;
let mut unpack = Unpack::new(&payload);
let generation = unpack.u64()?;
Ok(Tile {
generation,
pixels: unpack.rest().to_vec(),
})
}
/// Slide or master `part` whole, as `pixels` of BGRA.
pub fn paint_part(
&self,
worker: &mut Worker,
(part, master): (usize, bool),
pixels: (u32, u32),
) -> io::Result<Vec<u8>> {
let request = Pack::new()
.u64(worker.doc_id(self)?)
.u64(part as u64)
.u64(u64::from(master))
.u64(u64::from(pixels.0))
.u64(u64::from(pixels.1))
.bytes();
worker.request(tag::PAINT_PART, &request)
}
/// Slide `part`'s slideshow layers at about `pixels`.
pub fn slide_layers(
&self,
worker: &mut Worker,
part: usize,
pixels: (u32, u32),
) -> io::Result<crate::show::Layers> {
let request = Pack::new()
.u64(worker.doc_id(self)?)
.u64(part as u64)
.u64(u64::from(pixels.0))
.u64(u64::from(pixels.1))
.bytes();
crate::show::layers(&worker.request(tag::SLIDE_LAYERS, &request)?)
}
/// Saves to `url` as `format`; failure surfaces (LOK-09).
pub fn save_as(&self, worker: &mut Worker, url: &str, format: &str) -> io::Result<()> {
self.store(worker, url, format, "")
}
/// Writes the shown sheet as text split by `separator`.
pub fn export_text(&self, worker: &mut Worker, url: &str, separator: char) -> io::Result<()> {
let request = Pack::new()
.u64(worker.doc_id(self)?)
.str(url)
.u64(u64::from(separator))
.bytes();
worker.request(tag::EXPORT_TEXT, &request)?;
Ok(())
}
/// Writes a PDF of `pages` (from 1, inclusive) to `url`.
pub fn export_pdf(&self, worker: &mut Worker, url: &str, pdf: &Pdf) -> io::Result<()> {
let (from, to) = pdf.pages.unwrap_or((0, 0));
let request = Pack::new()
.u64(worker.doc_id(self)?)
.str(url)
.u64(u64::from(from))
.u64(u64::from(to))
.u64(u64::from(pdf.comments))
.u64(u64::from(pdf.changes))
.u64(u64::from(pdf.handouts))
.bytes();
worker.request(tag::EXPORT_PDF, &request)?;
Ok(())
}
/// Saves and moves the document to `url`; modified clears.
pub fn save_owned(&self, worker: &mut Worker, url: &str, format: &str) -> io::Result<()> {
self.store(worker, url, format, "TakeOwnership")
}
fn store(&self, worker: &mut Worker, url: &str, format: &str, options: &str) -> io::Result<()> {
worker.request(
tag::SAVE_AS,
&Pack::new()
.u64(worker.doc_id(self)?)
.str(url)
.str(format)
.str(options)
.bytes(),
)?;
Ok(())
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Event batches the worker pushes, kept per document (LOK-03).
use std::{
collections::{HashMap, HashSet},
io,
sync::{Arc, Condvar, Mutex},
task::{Poll, Waker},
time::{Duration, Instant},
};
use super::Doc;
use crate::events::Events;
/// The longest event wait in milliseconds.
const MAX_WAIT_MS: u64 = 1000;
#[derive(Default)]
struct Docs {
/// The last snapshot, and the batch not yet taken.
open: HashMap<u64, (Events, Option<Events>)>,
closed: HashSet<u64>,
dead: bool,
/// Async waiters to wake on any change.
wakers: Vec<Waker>,
}
/// Waits on pushed events without the worker lock.
#[derive(Clone, Default)]
pub struct Feed(Arc<(Mutex<Docs>, Condvar)>);
/// `next` with the one-shot parts of `before` kept.
fn merge(before: Events, mut next: Events) -> Events {
next.all |= before.all;
let mut rects = before.rects;
rects.append(&mut next.rects);
next.rects = rects;
let mut states = before.states;
states.retain(|(name, _)| !next.states.iter().any(|(newer, _)| newer == name));
states.append(&mut next.states);
next.states = states;
let mut blocked = before.blocked;
blocked.append(&mut next.blocked);
next.blocked = blocked;
next.menu = next.menu.or(before.menu);
let mut faults = before.faults;
faults.append(&mut next.faults);
next.faults = faults;
next
}
/// A snapshot with the one-shot parts cleared.
fn snapshot(batch: &Events) -> Events {
Events {
all: false,
rects: Vec::new(),
states: Vec::new(),
blocked: Vec::new(),
menu: None,
faults: Vec::new(),
..batch.clone()
}
}
impl Feed {
fn docs(&self) -> std::sync::MutexGuard<'_, Docs> {
self.0.0.lock().expect("the feed lock")
}
pub(crate) fn opened(&self, id: u64) {
self.docs().open.entry(id).or_default();
}
pub(crate) fn closed(&self, id: u64) {
let mut docs = self.docs();
docs.open.remove(&id);
docs.closed.insert(id);
self.wake(docs);
}
pub(crate) fn push(&self, id: u64, batch: Events) {
let mut docs = self.docs();
if docs.closed.contains(&id) {
return;
}
let (last, fresh) = docs.open.entry(id).or_default();
*last = snapshot(&batch);
*fresh = Some(match fresh.take() {
Some(before) => merge(before, batch),
None => batch,
});
self.wake(docs);
}
pub(crate) fn died(&self) {
let mut docs = self.docs();
docs.dead = true;
self.wake(docs);
}
/// Wakes blocked and async waiters.
fn wake(&self, mut docs: std::sync::MutexGuard<'_, Docs>) {
let wakers = std::mem::take(&mut docs.wakers);
drop(docs);
self.0.1.notify_all();
wakers.into_iter().for_each(Waker::wake);
}
/// Events after `known`, awaited without holding a thread.
pub async fn next(&self, doc: &Doc, known: u64) -> io::Result<Events> {
std::future::poll_fn(|cx| {
let mut docs = self.docs();
if docs.dead {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"the lok worker is gone",
)));
}
let Some((_, fresh)) = docs.open.get_mut(&doc.id) else {
return Poll::Ready(Err(io::Error::other("no such document")));
};
if fresh.as_ref().is_some_and(|batch| batch.seq > known) {
return Poll::Ready(Ok(fresh.take().expect("checked above")));
}
docs.wakers.push(cx.waker().clone());
Poll::Pending
})
.await
}
/// Events after `known`, or the snapshot after `timeout_ms`.
pub fn wait(&self, doc: &Doc, known: u64, timeout_ms: u64) -> io::Result<Events> {
let id = doc.id;
let deadline = Instant::now() + Duration::from_millis(timeout_ms.min(MAX_WAIT_MS));
let mut docs = self.docs();
loop {
if docs.dead {
return Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"the lok worker is gone",
));
}
let Some((last, fresh)) = docs.open.get_mut(&id) else {
return Err(io::Error::other("no such document"));
};
if fresh.as_ref().is_some_and(|batch| batch.seq > known) {
return Ok(fresh.take().expect("checked above"));
}
let now = Instant::now();
if now >= deadline {
return Ok(last.clone());
}
docs = self
.0
.1
.wait_timeout(docs, deadline - now)
.expect("the feed wait")
.0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queued_batches_keep_their_one_shot_parts() {
let feed = Feed::default();
feed.opened(1);
let first = Events {
seq: 1,
rects: vec![(0, 0, 1, 1)],
states: vec![("a".into(), "1".into()), ("b".into(), "1".into())],
..Events::default()
};
let second = Events {
seq: 2,
all: true,
states: vec![("a".into(), "2".into())],
..Events::default()
};
feed.push(1, first);
feed.push(1, second);
let batch = feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 0, 0).expect("a batch");
assert_eq!((batch.seq, batch.all, batch.rects.len()), (2, true, 1));
assert_eq!(
batch.states,
[("b".to_string(), "1".to_string()), ("a".into(), "2".into())]
);
let idle = feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 2, 0).expect("the snapshot");
assert!(idle.rects.is_empty() && idle.states.is_empty() && idle.seq == 2);
feed.closed(1);
assert!(
feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 2, 0).is_err(),
"a closed document"
);
}
}
+150
View File
@@ -0,0 +1,150 @@
//! The worker's output: replies and pushed events (LOK-03).
use std::{io, sync::mpsc};
use super::Feed;
use crate::events::{A11y, Events, Rect};
use crate::ipc::{self, Unpack, tag};
/// One pushed event batch: its document and events.
fn unpack_pushed(body: &[u8]) -> io::Result<(u64, Events)> {
let mut unpack = Unpack::new(body);
let (id, revision) = (unpack.u64()?, unpack.u64()?);
let (seq, generation, all) = (unpack.u64()?, unpack.u64()?, unpack.u64()? != 0);
let rects = rects_of(&mut unpack)?;
let cursor = rects_of(&mut unpack)?.first().copied();
let cursor_visible = unpack.u64()? != 0;
let selection = rects_of(&mut unpack)?;
let graphic = rects_of(&mut unpack)?.first().copied();
let cropping = unpack.u64()? != 0;
let review = unpack.u64()?;
let searched = unpack.u64()?;
let resized = unpack.u64()?;
let found = rects_of(&mut unpack)?;
let menu = Some(unpack.str()?).filter(|menu| !menu.is_empty());
let faults = (0..unpack.u64()?)
.map(|_| unpack.str())
.collect::<io::Result<_>>()?;
let fonts = (0..unpack.u64()?)
.map(|_| unpack.str())
.collect::<io::Result<_>>()?;
let states = (0..unpack.u64()?)
.map(|_| Ok((unpack.str()?, unpack.str()?)))
.collect::<io::Result<_>>()?;
let blocked = (0..unpack.u64()?)
.map(|_| unpack.str())
.collect::<io::Result<_>>()?;
let tabs = (0..unpack.u64()?)
.map(|_| Ok(unpack.i64()? as i32))
.collect::<io::Result<Vec<_>>>()?;
let text = unpack.str()?;
let mut at = || -> io::Result<Option<usize>> { Ok(usize::try_from(unpack.i64()?).ok()) };
let caret = at()?;
let marked = at()?.zip(at()?);
let a11y = A11y {
text,
caret,
selection: marked,
};
let cell = crate::events::Cell::unpack(&mut unpack)?;
let events = Events {
seq,
revision,
generation,
all,
rects,
cursor,
cursor_visible,
selection,
graphic,
cropping,
review,
searched,
resized,
found,
menu,
faults,
fonts,
states,
blocked,
a11y,
tabs,
cell,
};
Ok((id, events))
}
/// Splits the worker's output: replies to requests, pushed events.
pub(super) fn read_frames(
mut stdout: impl io::Read,
feed: &Feed,
replies: &mpsc::Sender<io::Result<(u8, u64, Vec<u8>)>>,
) {
loop {
let frame = match ipc::read_frame(&mut stdout) {
Ok(Some((tag::EVENTS, _, body))) => match unpack_pushed(&body) {
Ok((id, batch)) => {
feed.push(id, batch);
continue;
}
Err(error) => Err(error),
},
Ok(Some(frame)) => Ok(Some(frame)),
Ok(None) => Ok(None),
Err(error) => Err(error),
};
// The reason output stopped reaches the waiting request.
let ended = match frame {
Ok(Some(frame)) => {
if replies.send(Ok(frame)).is_err() {
return;
}
continue;
}
Ok(None) => io::Error::new(io::ErrorKind::UnexpectedEof, "the lok worker closed its output"),
Err(error) => {
log::error!("lok: the worker output is unreadable: {error}");
error
}
};
feed.died();
let _ = replies.send(Err(ended));
return;
}
}
/// A counted rect list off the wire.
fn rects_of(unpack: &mut Unpack) -> io::Result<Vec<Rect>> {
let count = unpack.u64()? as usize;
let mut rects = Vec::with_capacity(count.min(1024));
for _ in 0..count {
rects.push((
unpack.i64()? as i32,
unpack.i64()? as i32,
unpack.i64()? as i32,
unpack.i64()? as i32,
));
}
Ok(rects)
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use super::read_frames;
use crate::client::Feed;
#[test]
fn a_broken_output_reaches_the_waiting_request() {
let (sender, replies) = mpsc::channel();
// A header claiming more than the cap.
read_frames(&u32::MAX.to_le_bytes()[..], &Feed::default(), &sender);
let error = replies.recv().expect("a message").expect_err("an error");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData, "{error}");
let (sender, replies) = mpsc::channel();
read_frames(&[][..], &Feed::default(), &sender);
let error = replies.recv().expect("a message").expect_err("an error");
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof, "{error}");
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Where the LOK build and the worker binary are.
use std::{
io,
path::{Path, PathBuf},
};
/// The kernel's bundled templates of `kind`, such as `presnt`.
pub fn templates(kind: &str) -> io::Result<Vec<PathBuf>> {
let install = install_dir()?;
let root = install
.parent()
.ok_or_else(|| io::Error::other("the install has no parent"))?;
let common = match cfg!(target_os = "macos") {
true => root.join("Resources/template/common"),
false => root.join("share/template/common"),
};
let mut found = std::fs::read_dir(common.join(kind))?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<io::Result<Vec<_>>>()?;
found.sort();
Ok(found)
}
/// The LOK build: `ELY_LOK_DIR`, the app bundle's, or engines/.
pub fn install_dir() -> io::Result<PathBuf> {
if let Ok(dir) = std::env::var("ELY_LOK_DIR") {
let path = PathBuf::from(dir);
return if path.try_exists()? {
Ok(path)
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("ELY_LOK_DIR {} does not exist", path.display()),
))
};
}
let exe = std::env::current_exe()?;
let bundled = exe
.parent()
.unwrap_or(Path::new("."))
.join("../Frameworks");
if cfg!(target_os = "macos") && bundled.join("libmergedlo.dylib").try_exists()? {
return Ok(bundled);
}
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../engines/lo-src/instdir/LibreOffice.app/Contents/Frameworks");
if dev.try_exists()? {
return Ok(dev);
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"no LOK build (set ELY_LOK_DIR)",
))
}
/// The worker binary: env override, else beside this exe.
pub(super) fn worker_bin() -> io::Result<PathBuf> {
if let Ok(bin) = std::env::var("ELY_LOK_WORKER") {
if bin.is_empty() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"ELY_LOK_WORKER is empty",
));
}
let path = PathBuf::from(&bin);
return if path.try_exists()? {
Ok(path)
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("ELY_LOK_WORKER {bin} does not exist"),
))
};
}
let sibling = std::env::current_exe()?
.parent()
.unwrap_or(Path::new("."))
.join(if cfg!(windows) {
"ely-lok-worker.exe"
} else {
"ely-lok-worker"
});
if sibling.try_exists()? {
return Ok(sibling);
}
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../target/debug")
.join(if cfg!(windows) {
"ely-lok-worker.exe"
} else {
"ely-lok-worker"
});
if dev.try_exists()? {
return Ok(dev);
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"no ely-lok-worker binary (set ELY_LOK_WORKER)",
))
}
+410
View File
@@ -0,0 +1,410 @@
use std::path::PathBuf;
use super::*;
mod analysis;
mod charts;
mod check;
mod commands;
mod format;
mod formula;
mod handouts;
mod independent;
pub(crate) mod input;
mod latency;
mod layout;
mod media;
mod motion;
mod output;
mod paint;
mod playlist;
mod print;
mod refs;
mod roundtrip;
mod rules;
mod sheet;
pub(crate) mod show;
mod slides;
mod tools;
mod workbook;
/// The pinned LibreOffice commit the build must report.
const PINNED_BUILD: &str = "8221e31";
/// The pinned build, or None when absent.
pub(crate) fn install() -> Option<PathBuf> {
install_dir().ok()
}
/// A tiny flat-XML document; no zip needed.
pub(crate) const FODT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:body><office:text><text:p>Hello 世界</text:p></office:text></office:body>
</office:document>"#;
/// A document whose button runs the Basic marker writer.
fn macro_fodt(marker: &std::path::Path) -> String {
let marker = marker.display().to_string().replace('\\', "/");
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:ooo="http://openoffice.org/2004/office"
xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0"
xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0"
xmlns:xlink="http://www.w3.org/1999/xlink" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:scripts>
<office:script script:language="ooo:Basic">
<ooo:libraries>
<ooo:library-embedded ooo:name="Standard">
<ooo:module ooo:name="Module1">
<ooo:source-code>Sub Sneaky&#x0A; Open "{marker}" For Output As #1&#x0A; Write #1, "ran"&#x0A; Close #1&#x0A;End Sub</ooo:source-code>
</ooo:module>
</ooo:library-embedded>
</ooo:libraries>
</office:script>
</office:scripts>
<office:body>
<office:text>
<office:forms form:automatic-focus="false" form:apply-design-mode="false">
<form:form>
<form:button form:name="btn" form:control-implementation="ooo:com.sun.star.form.component.CommandButton" xml:id="btn1" form:id="btn1" form:label="Run">
<office:event-listeners>
<script:event-listener script:language="ooo:script" script:event-name="form:performaction" xlink:href="vnd.sun.star.script:Standard.Module1.Sneaky?language=Basic&amp;location=document" xlink:type="simple"/>
</office:event-listeners>
</form:button>
</form:form>
</office:forms>
<text:p>Macro doc</text:p>
</office:text>
</office:body>
</office:document>"#
)
}
/// Clicks (x, y) twips: left press and release.
pub(crate) fn click(worker: &mut Worker, doc: &Doc, x: i32, y: i32) {
for kind in [0, 1] {
let event = Mouse {
kind,
x,
y,
count: 1,
buttons: 1,
modifiers: 0,
};
worker.post_mouse(doc, event).expect("the click posts");
}
}
/// Polls past `from` until `done` or `wait`; rects pile up.
pub(crate) fn poll_until(
worker: &mut Worker,
doc: &Doc,
from: &Events,
wait: std::time::Duration,
done: impl Fn(&Events) -> bool,
) -> Events {
let deadline = std::time::Instant::now() + wait;
let mut seen = Events {
rects: Vec::new(),
all: false,
states: Vec::new(),
blocked: Vec::new(),
..from.clone()
};
loop {
let batch = worker
.poll_events(doc, seen.seq, 250)
.expect("the poll returns");
let mut rects = std::mem::take(&mut seen.rects);
let mut states = std::mem::take(&mut seen.states);
let mut blocked = std::mem::take(&mut seen.blocked);
let all = seen.all || batch.all;
rects.extend(batch.rects.iter().copied());
states.extend(batch.states.iter().cloned());
blocked.extend(batch.blocked.iter().cloned());
seen = Events {
rects,
all,
states,
blocked,
..batch
};
if done(&seen) || std::time::Instant::now() >= deadline {
return seen;
}
}
}
fn write(path: &Path, body: &str) {
std::fs::write(path, body).expect("the fixture writes");
}
#[test]
fn the_worker_round_trips_a_document() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let profile = dir.path().join("配置 profile");
let mut worker = Worker::spawn(&install, &profile).expect("the worker spawns");
let build = worker.build_id().expect("the build id");
assert!(build.contains(PINNED_BUILD), "the pinned build: {build}");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let url = format!("file://{}", source.display());
let doc = worker.load(&url).expect("the document loads");
let (width, height) = doc.size(&mut worker).expect("the size");
assert!(width > 0 || height > 0, "a nonzero document size");
let odt = dir.path().join("note.odt");
doc.save_as(&mut worker, &format!("file://{}", odt.display()), "odt")
.expect("the odt save");
assert!(odt.try_exists().expect("the odt exists"));
let doc2 = worker
.load(&format!("file://{}", odt.display()))
.expect("the odt reloads");
let pdf = dir.path().join("note.pdf");
doc2.save_as(&mut worker, &format!("file://{}", pdf.display()), "pdf")
.expect("the pdf save");
let head = std::fs::read(&pdf).expect("the pdf reads");
assert!(head.starts_with(b"%PDF"), "a real PDF comes out");
worker.close_doc(doc2).expect("the second doc closes");
worker.close_doc(doc).expect("the first doc closes");
}
#[test]
fn a_missing_file_is_an_error_never_a_success() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let missing = dir.path().join("gone.odt");
let outcome = worker.load(&format!("file://{}", missing.display()));
assert!(outcome.is_err(), "LOK-09: the failure is an error");
}
#[test]
fn a_failed_check_refuses_every_later_request() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let profile = dir.path().join("profile");
// The self-check cannot write its sample over a folder.
std::fs::create_dir_all(profile.join("lok-verify.fodt")).expect("the blocker");
let mut worker = Worker::launch(&install, &profile).expect("the worker");
assert!(worker.ready().is_err(), "the check fails");
assert!(worker.ready().is_err(), "and stays failed");
assert!(worker.load("private:factory/swriter").is_err(), "no document reaches it");
}
/// Initializes the profile fully, the CLI way (registers Basic).
fn seed_basic(install: &Path, profile: &Path) {
let soffice = install.parent().expect("the app dir").join("MacOS/soffice");
let url = ipc::file_url_of(profile);
let status = std::process::Command::new(&soffice)
.args(["--headless", "--norestore", "--terminate_after_init"])
.arg(format!("-env:UserInstallation={url}"))
.status()
.expect("soffice runs");
assert!(status.success(), "the profile initializes");
}
/// The macro module: writes its marker through the UCB.
fn module(marker: &Path) -> String {
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE script:module PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\" \"module.dtd\">\n<script:module xmlns:script=\"http://openoffice.org/2000/script\" script:name=\"Module1\" script:language=\"StarBasic\">Sub Sneaky\n oSFA = createUnoService(\"com.sun.star.ucb.SimpleFileAccess\")\n oOut = oSFA.openFileWrite(\"{}\")\n oOut.writeString(\"ran\")\n oOut.closeOutput()\nEnd Sub\n</script:module>\n",
marker.display().to_string().replace('\\', "/")
)
}
const MACRO_URL: &str = "macro:///Standard.Module1.Sneaky";
/// 未验证: this backend never dispatches document events to Basic.
#[test]
fn a_macro_never_writes_its_marker() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let profile = dir.path().join("profile");
let marker = dir.path().join("macro-ran.txt");
seed_basic(&install, &profile);
std::fs::write(
profile.join("user/basic/Standard/Module1.xba"),
module(&marker),
)
.expect("the module writes");
let mut worker = Worker::spawn_dev(&install, &profile).expect("the worker");
let source = dir.path().join("macro.fodt");
std::fs::write(&source, macro_fodt(&marker)).expect("the macro fodt writes");
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the macro document loads");
std::thread::sleep(std::time::Duration::from_millis(800));
assert!(
!marker.try_exists().expect("the marker check"),
"LOK-11: loading ran no macro"
);
let ran = worker.run_macro(MACRO_URL).expect("the macro channel");
assert!(ran != 0, "the build runs the library macro when asked");
assert!(
marker.try_exists().expect("the marker check"),
"the sample is real: it writes when run"
);
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn a_production_worker_refuses_run_macro() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let refused = worker.run_macro(MACRO_URL);
assert!(
refused.is_err(),
"LOK-11: the production worker keeps the gate"
);
}
#[cfg(target_os = "macos")]
#[test]
fn an_unpatched_build_is_rejected() {
let dmg = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../engines/LibreOffice_26.2.6_MacOS_aarch64.dmg");
if !dmg.try_exists().expect("the dmg check") {
eprintln!("SKIP: no official dmg");
return;
}
let mount = tempfile::tempdir().expect("a temp dir");
let attached = std::process::Command::new("hdiutil")
.args(["attach", "-nobrowse", "-readonly", "-mountpoint"])
.arg(mount.path())
.arg(&dmg)
.status()
.expect("hdiutil runs");
assert!(attached.success(), "the official dmg mounts");
let frameworks = mount.path().join("LibreOffice.app/Contents/Frameworks");
let dir = tempfile::tempdir().expect("a temp dir");
let outcome = Worker::spawn(&frameworks, &dir.path().join("profile"));
assert!(outcome.is_err(), "the unpatched build must be rejected");
let detached = std::process::Command::new("hdiutil")
.args(["detach", "-quiet"])
.arg(mount.path())
.status()
.expect("hdiutil detaches");
assert!(detached.success());
}
#[test]
fn shutdown_leaves_no_locks_or_temp() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let profile = dir.path().join("profile");
let mut worker = Worker::spawn(&install, &profile).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let lock = dir.path().join(".~lock.note.fodt#");
worker.close_doc(doc).expect("the document closes");
worker.shutdown().expect("the worker shuts down");
assert!(
!lock.try_exists().expect("the doc lock check"),
"no stale document lock"
);
assert!(
!profile
.join(".lock")
.try_exists()
.expect("the profile lock check"),
"no profile lock"
);
let lu: Vec<_> = std::fs::read_dir(profile.join("tmp"))
.expect("the temp dir lists")
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_name().to_string_lossy().starts_with("lu"))
.collect();
assert!(lu.is_empty(), "no kernel temp files: {lu:?}");
}
#[test]
fn each_load_is_its_own_session() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker spawns");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let url = format!("file://{}", source.display());
// Freed native documents reuse addresses; sessions never repeat.
let mut old = Vec::new();
for _ in 0..4 {
let doc = worker.load(&url).expect("loads");
assert!(old.iter().all(|seen: &Doc| seen.id != doc.id), "a session came back");
worker.close_doc(doc.clone()).expect("closes");
old.push(doc);
}
for doc in &old {
assert!(doc.size(&mut worker).is_err(), "a closed session answered");
}
let doc = worker.load(&url).expect("loads again");
worker.post_key(&doc, 'x' as u32, 0).expect("a key");
let events = worker.poll_events(&doc, 0, 5_000).expect("events");
assert!(events.seq > 0, "the new session's events flow");
worker.close_doc(doc).expect("closes");
}
#[test]
fn a_document_belongs_to_its_worker() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let url = format!("file://{}", source.display());
let mut first = Worker::spawn(&install, &dir.path().join("one")).expect("a worker");
let mut second = Worker::spawn(&install, &dir.path().join("two")).expect("another worker");
let theirs = first.load(&url).expect("loads");
let ours = second.load(&url).expect("loads");
// Another worker's handle never reaches these documents.
assert!(theirs.size(&mut second).is_err(), "another worker's document answered");
assert!(second.close_doc(theirs.clone()).is_err(), "another worker's document closed");
assert!(ours.size(&mut second).is_ok(), "its own document stays");
first.close_doc(theirs).expect("closes");
second.close_doc(ours).expect("closes");
}
#[test]
fn a_worker_that_cannot_start_says_why() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let Err(error) = Worker::spawn(&dir.path().join("no-install"), &dir.path().join("profile")) else {
panic!("a worker started without a kernel");
};
// The worker's own reason, not only a closed pipe.
assert!(error.to_string().contains("lok-worker:"), "{error}");
}
+333
View File
@@ -0,0 +1,333 @@
use super::rules::row;
use super::sheet::open_book;
use super::*;
use crate::sheet::{self, Layout, Look};
/// Region, Year, Sales; four rows.
fn data() -> String {
let rows: String = [
["Region", "Year", "Sales"],
["East", "2025", "3"],
["West", "2025", "1"],
["East", "2026", "4"],
["West", "2026", "2"],
]
.iter()
.map(|cells| row(cells))
.collect();
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S">{rows}</table:table></office:spreadsheet></office:body>
</office:document>"#
)
}
pub(super) fn cells(worker: &mut Worker, doc: &Doc, range: &str) -> String {
worker.run(doc, "cell.goto", &[range]).expect("the range");
doc.selection_text(worker).expect("the text")
}
/// `range` as the kernel writes it.
fn written(worker: &mut Worker, doc: &Doc, range: &str) -> String {
worker.run(doc, "cell.goto", &[range]).expect("the range");
let read = worker.values(doc, sheet::SELECTED).expect("the selection");
sheet::selected_range(&read)
.expect("parses")
.expect("one range")
.range
}
fn pivot_here(worker: &mut Worker, doc: &Doc) -> Option<sheet::Pivot> {
let read = worker.values(doc, sheet::PIVOT).expect("the pivot read");
sheet::pivot(&read).expect("parses")
}
fn chart_here(worker: &mut Worker, doc: &Doc) -> Option<sheet::Chart> {
let read = worker.values(doc, sheet::CHART).expect("the chart read");
sheet::chart(&read).expect("parses")
}
/// Undo steps in the kernel's history.
pub(super) fn steps(worker: &mut Worker, doc: &Doc) -> usize {
let json = worker.values(doc, ".uno:Undo").expect("the history");
let value: serde_json::Value = serde_json::from_str(&json).expect("parses");
value["actions"].as_array().map_or(0, Vec::len)
}
pub(super) fn skip() -> bool {
let missing = install().is_none();
if missing {
eprintln!("SKIP: no pinned LOK build");
}
missing
}
#[test]
fn pivot_tables_make_change_and_refresh() {
if skip() {
return;
}
let (_dir, mut worker, doc) = open_book(&data());
let (source, dest, other) = (
written(&mut worker, &doc, "A1:C5"),
written(&mut worker, &doc, "E1"),
written(&mut worker, &doc, "K1"),
);
worker
.run(&doc, "cell.goto", &["A1:C7"])
.expect("past the data");
let read = worker.values(&doc, sheet::SELECTED).expect("the selection");
let wide = sheet::selected_range(&read).expect("parses").expect("one");
assert_eq!(wide.data, source, "the data inside, without empty rows");
worker.run(&doc, "cell.goto", &["E1"]).expect("E1");
assert_eq!(pivot_here(&mut worker, &doc), None, "no pivot yet");
let layout = Layout {
rows: vec!["Region".into()],
data: vec![("Sales".into(), "sum".into())],
..Layout::default()
};
let spec = layout.to_json(&source, &dest);
worker.run(&doc, "pivot.make", &[&spec]).expect("makes");
let made = cells(&mut worker, &doc, "E1:F4");
assert!(
made.contains("East\t7") && made.contains("West\t3"),
"{made:?}"
);
worker.run(&doc, "cell.goto", &["E2"]).expect("on it");
let here = pivot_here(&mut worker, &doc).expect("a pivot");
assert_eq!(here.source, source);
assert_eq!(here.fields, ["Region", "Year", "Sales"]);
// The kernel places the data layout field in the columns.
let placed = Layout {
columns: vec![String::new()],
..layout.clone()
};
assert_eq!(here.layout, placed);
let changed = Layout {
columns: vec!["Year".into(), String::new()],
data: vec![("Sales".into(), "max".into())],
..placed
};
worker
.run(&doc, "pivot.make", &[&changed.to_json("", "")])
.expect("changes");
worker.run(&doc, "cell.goto", &["E2"]).expect("on it");
let here = pivot_here(&mut worker, &doc).expect("still a pivot");
assert_eq!(here.layout, changed, "fields and function changed in place");
worker.run(&doc, "cell.goto", &["C2"]).expect("C2");
worker.run(&doc, "cell.enter", &["9"]).expect("enters");
worker.run(&doc, "cell.goto", &["E3"]).expect("on it");
worker.run(&doc, "pivot.refresh", &[]).expect("refreshes");
let fresh = cells(&mut worker, &doc, "E1:H5");
assert!(
fresh.contains("East\t9\t4"),
"the new value shows: {fresh:?}"
);
let bad = Layout {
data: vec![("Nope".into(), "sum".into())],
..Layout::default()
};
worker.run(&doc, "cell.goto", &["K1"]).expect("K1");
assert!(
worker
.run(&doc, "pivot.make", &[&bad.to_json(&source, &other)])
.is_err(),
"an unknown field fails"
);
}
#[test]
fn charts_insert_and_change_in_one_step() {
if skip() {
return;
}
let (_dir, mut worker, doc) = open_book(&data());
let (all, part) = (
written(&mut worker, &doc, "A1:C5"),
written(&mut worker, &doc, "A1:C3"),
);
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
assert_eq!(chart_here(&mut worker, &doc), None, "no chart yet");
let look = Look {
kind: "column".into(),
title: "Sales".into(),
legend: true,
x_title: "Region".into(),
y_title: "Units".into(),
};
worker
.run(&doc, "chart.insert", &[&all, "false", &look.to_json()])
.expect("inserts");
let chart = chart_here(&mut worker, &doc).expect("the new chart is selected");
assert_eq!((&chart.look, &chart.range), (&look, &all));
let pie = Look {
kind: "pie".into(),
title: String::new(),
legend: false,
..Look::default()
};
worker
.run(
&doc,
"chart.change",
&[&chart.name, &part, "true", "true", &pie.to_json()],
)
.expect("changes");
let changed = chart_here(&mut worker, &doc).expect("still selected");
assert_eq!(changed.look, pie);
assert_eq!(changed.range, part);
worker.run(&doc, "edit.undo", &[]).expect("one undo");
let back = chart_here(&mut worker, &doc).expect("still selected");
assert_eq!((back.look, back.range), (look.clone(), chart.range.clone()));
let before = steps(&mut worker, &doc);
for bad in ["bad range", "NoSheet!A1:B3"] {
let change = [chart.name.as_str(), bad, "true", "true", &pie.to_json()];
assert!(
worker.run(&doc, "chart.change", &change).is_err(),
"{bad} changes nothing"
);
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
let insert = [bad, "false", &look.to_json()];
assert!(
worker.run(&doc, "chart.insert", &insert).is_err(),
"{bad} inserts nothing"
);
}
assert_eq!(steps(&mut worker, &doc), before, "nothing changed");
let wrong = Look {
kind: "donut".into(),
..pie
};
assert!(
worker
.run(
&doc,
"chart.change",
&[&chart.name, &part, "true", "true", &wrong.to_json()],
)
.is_err(),
"an unknown kind fails"
);
}
#[test]
fn a_read_layout_applies_back_unchanged() {
if skip() {
return;
}
let (_dir, mut worker, doc) = open_book(&data());
let (source, dest) = (
written(&mut worker, &doc, "A1:C5"),
written(&mut worker, &doc, "E1"),
);
let across = Layout {
rows: vec!["Region".into()],
columns: vec![String::new()],
data: vec![
("Sales".into(), "sum".into()),
("Year".into(), "max".into()),
],
..Layout::default()
};
worker
.run(&doc, "pivot.make", &[&across.to_json(&source, &dest)])
.expect("makes");
let before = cells(&mut worker, &doc, "E1:G4");
worker.run(&doc, "cell.goto", &["E2"]).expect("on it");
let read = pivot_here(&mut worker, &doc).expect("a pivot").layout;
assert_eq!(read, across, "the data field reads in place");
worker
.run(&doc, "pivot.make", &[&read.to_json("", "")])
.expect("applies");
assert_eq!(cells(&mut worker, &doc, "E1:G4"), before, "nothing moved");
}
/// The data with a pivot table that sums Region's subtotals.
fn with_subtotals() -> String {
let table = r#"<table:data-pilot-tables><table:data-pilot-table table:name="P" table:target-range-address="S.E1:G14"><table:source-cell-range table:cell-range-address="S.A1:C5"/><table:data-pilot-field table:source-field-name="Region" table:orientation="row"><table:data-pilot-level table:show-empty="false"><table:data-pilot-subtotals><table:data-pilot-subtotal table:function="sum"/></table:data-pilot-subtotals></table:data-pilot-level></table:data-pilot-field><table:data-pilot-field table:source-field-name="Year" table:orientation="row"><table:data-pilot-level table:show-empty="false"/></table:data-pilot-field><table:data-pilot-field table:source-field-name="Sales" table:orientation="data" table:function="sum"/><table:data-pilot-field table:source-field-name="" table:is-data-layout-field="true" table:orientation="column"/></table:data-pilot-table></table:data-pilot-tables>"#;
data().replace(
"</office:spreadsheet>",
&format!("{table}</office:spreadsheet>"),
)
}
#[test]
fn a_read_layout_keeps_subtotals() {
if skip() {
return;
}
let (_dir, mut worker, doc) = open_book(&with_subtotals());
worker.run(&doc, "cell.goto", &["E3"]).expect("on it");
worker.run(&doc, "pivot.refresh", &[]).expect("refreshes");
let before = cells(&mut worker, &doc, "E1:G14");
assert!(
before.contains("East Sum - Sales"),
"the subtotal shows: {before:?}"
);
worker.run(&doc, "cell.goto", &["E3"]).expect("on it");
let read = pivot_here(&mut worker, &doc).expect("a pivot").layout;
worker
.run(&doc, "pivot.make", &[&read.to_json("", "")])
.expect("applies");
assert_eq!(cells(&mut worker, &doc, "E1:G14"), before, "nothing moved");
}
/// The book saved as flat XML, read back as text.
fn saved(worker: &mut Worker, doc: &Doc, path: &std::path::Path) -> String {
doc.save_as(worker, &crate::file_url(path), "fods")
.expect("saves");
std::fs::read_to_string(path).expect("reads")
}
#[test]
fn undoing_a_new_kind_brings_the_whole_chart_back() {
if skip() {
return;
}
let (dir, mut worker, doc) = open_book(&data());
let all = written(&mut worker, &doc, "A1:C5");
let look = Look {
kind: "column".into(),
legend: true,
..Look::default()
};
worker
.run(&doc, "chart.insert", &[&all, "false", &look.to_json()])
.expect("inserts");
let name = chart_here(&mut worker, &doc).expect("selected").name;
let flat = dir.path().join("stacked.fods");
let text = saved(&mut worker, &doc, &flat);
// The plot area's style gains stacking.
let plot = r#"chart:include-hidden-cells="false""#;
assert!(text.contains(plot), "the plot area style");
let stacked = format!(r#"chart:stacked="true" {plot}"#);
std::fs::write(&flat, text.replace(plot, &stacked)).expect("stacks it");
worker.close_doc(doc).expect("closes");
let doc = worker.load(&crate::file_url(&flat)).expect("reloads");
let before = saved(&mut worker, &doc, &dir.path().join("before.fods"));
assert!(
before.contains(r#"chart:stacked="true""#),
"the kernel reads it stacked"
);
let pie = Look {
kind: "pie".into(),
..look
};
let change = [name.as_str(), &all, "true", "true", &pie.to_json()];
worker.run(&doc, "chart.change", &change).expect("changes");
worker.run(&doc, "edit.undo", &[]).expect("one undo");
let back = saved(&mut worker, &doc, &dir.path().join("back.fods"));
assert!(
back.contains(r#"chart:stacked="true""#),
"the stacking came back"
);
}
+213
View File
@@ -0,0 +1,213 @@
use super::analysis::steps;
use super::show::open_deck;
use super::*;
use crate::show::{self, ChartData};
fn chart(worker: &mut Worker, doc: &Doc) -> show::SlideChart {
let read = worker.values(doc, crate::sheet::CHART).expect("reads");
show::slide_chart(&read).expect("parses").expect("a chart")
}
fn select_chart(worker: &mut Worker, doc: &Doc) {
let objects =
show::objects(&worker.values(doc, show::OBJECTS).expect("reads")).expect("parses");
let at = (objects.objects.iter())
.position(|object| object.kind == "chart")
.expect("a chart");
let state = worker.now(doc).expect("the state");
worker
.run(&state, "object.select", &[&at.to_string(), "false"])
.expect("selects");
}
fn look(kind: &str) -> crate::sheet::Look {
crate::sheet::Look {
kind: kind.into(),
legend: true,
..Default::default()
}
}
/// Saves `doc` as PPTX, reopens it and selects its chart.
fn round_trip(worker: &mut Worker, doc: &Doc, path: &std::path::Path) -> Doc {
doc.save_as(worker, &crate::file_url(path), "pptx")
.expect("saves");
let deck = worker.load(&crate::file_url(path)).expect("loads");
select_chart(worker, &deck);
deck
}
#[test]
fn a_scatter_keeps_editable_data_through_pptx() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let table = |values: [f64; 2]| ChartData {
categories: vec!["10".into(), "20".into()],
series: vec![("North".into(), values.iter().map(|v| Some(*v)).collect())],
};
let json = show::chart_json(&look("scatter"), Some(&table([1.0, 2.0])));
worker.run(&doc, "show.chart", &[&json]).expect("inserts");
let deck = round_trip(&mut worker, &doc, &dir.path().join("one.pptx"));
let read = chart(&mut worker, &deck);
assert_eq!(read.data, Some(table([1.0, 2.0])), "X and Y come back");
let titled = crate::sheet::Look {
title: "Spread".into(),
..read.look
};
let before = steps(&mut worker, &deck);
let json = show::chart_json(&titled, Some(&table([1.0, 5.0])));
worker.run(&deck, "show.chart", &[&json]).expect("changes");
assert_eq!(steps(&mut worker, &deck), before + 1);
let again = round_trip(&mut worker, &deck, &dir.path().join("two.pptx"));
let read = chart(&mut worker, &again);
assert_eq!(
(read.look.title.as_str(), read.data),
("Spread", Some(table([1.0, 5.0])))
);
}
#[test]
fn a_missing_point_reads_as_none_and_goes_back() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let data = ChartData {
categories: vec!["Q1".into(), "Q2".into()],
series: vec![("North".into(), vec![Some(1.0), None])],
};
let json = show::chart_json(&look("column"), Some(&data));
worker.run(&doc, "show.chart", &[&json]).expect("inserts");
let read = chart(&mut worker, &doc);
assert_eq!(read.data.as_ref(), Some(&data));
let titled = crate::sheet::Look {
title: "Gaps".into(),
..read.look
};
let json = show::chart_json(&titled, read.data.as_ref());
worker.run(&doc, "show.chart", &[&json]).expect("retitles");
assert_eq!(chart(&mut worker, &doc).data, Some(data));
}
#[test]
fn a_chart_field_of_the_wrong_type_is_refused() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let data = r#""data":{"categories":["A"],"series":[{"name":"S","values":[1]}]}"#;
let shapes = |worker: &mut Worker| {
let read = worker.values(&doc, show::OBJECTS).expect("reads");
show::objects(&read).expect("parses").objects.len()
};
let (before, objects) = (steps(&mut worker, &doc), shapes(&mut worker));
for bad in [
format!(r#"{{"type":"column","legend":"banana",{data}}}"#),
format!(r#"{{"type":"column","legend":"true",{data}}}"#),
format!(r#"{{"type":"column","title":123,{data}}}"#),
format!(r#"{{"type":"column","title":{{"bad":"object"}},{data}}}"#),
r#"{"type":"column","data":{"categories":["A"],"series":[{"name":"S","values":["1"]}]}}"#
.into(),
r#"{"type":"scatter","data":{"categories":["A"],"series":[{"name":"S","values":[1]}]}}"#
.into(),
] {
assert!(worker.run(&doc, "show.chart", &[&bad]).is_err(), "{bad}");
}
assert_eq!(steps(&mut worker, &doc), before, "no undo step");
assert_eq!(shapes(&mut worker), objects, "no chart");
}
#[test]
fn comments_do_not_shift_object_indices() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let shape = |worker: &mut Worker, kind: &str| {
worker
.run(&doc, "draw.shape", &[kind, "true"])
.expect("draws");
};
shape(&mut worker, "rectangle");
worker
.run(&doc, "comment.insert", &["Between"])
.expect("comments");
shape(&mut worker, "ellipse");
let read = |worker: &mut Worker| {
show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses")
};
let last = read(&mut worker).objects.len() - 1;
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &[&last.to_string(), "false"])
.expect("selects");
let objects = read(&mut worker);
let marked: Vec<bool> = objects.objects.iter().map(|o| o.selected).collect();
assert_eq!(marked.iter().filter(|on| **on).count(), 1, "{marked:?}");
assert!(marked[last], "the ellipse, not the comment");
}
/// Where the first chart series' style sits.
fn series_style(xml: &str) -> (usize, usize) {
let at = xml.find("<chart:series").expect("a series");
let name = xml[at..]
.split("chart:style-name=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("a series style");
let start = xml
.find(&format!("<style:style style:name=\"{name}\""))
.expect("its style");
let end = start + xml[start..].find("</style:style>").expect("ends");
(start, end)
}
#[test]
fn a_retitled_scatter_keeps_its_lines() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let data = ChartData {
categories: vec!["10".into(), "20".into()],
series: vec![("North".into(), vec![Some(1.0), Some(2.0)])],
};
let json = show::chart_json(&look("scatter"), Some(&data));
worker.run(&doc, "show.chart", &[&json]).expect("inserts");
let out = dir.path().join("points.fodp");
doc.save_as(&mut worker, &crate::file_url(&out), "fodp")
.expect("saves");
// Join the points with a line, as another editor would.
let mut xml = std::fs::read_to_string(&out).expect("reads");
let (start, end) = series_style(&xml);
let style = xml[start..end].replace(r#"draw:stroke="none""#, r#"draw:stroke="solid""#);
assert!(style.contains(r#"draw:stroke="solid""#), "{style}");
xml.replace_range(start..end, &style);
let lines = dir.path().join("lines.fodp");
std::fs::write(&lines, xml).expect("writes");
let deck = worker.load(&crate::file_url(&lines)).expect("loads");
select_chart(&mut worker, &deck);
let titled = crate::sheet::Look {
title: "Spread".into(),
..chart(&mut worker, &deck).look
};
let json = show::chart_json(&titled, None);
worker.run(&deck, "show.chart", &[&json]).expect("retitles");
let again = dir.path().join("again.fodp");
deck.save_as(&mut worker, &crate::file_url(&again), "fodp")
.expect("saves");
let xml = std::fs::read_to_string(&again).expect("reads");
let (start, end) = series_style(&xml);
assert!(
!xml[start..end].contains(r#"draw:stroke="none""#),
"{}",
&xml[start..end]
);
}
+48
View File
@@ -0,0 +1,48 @@
use super::*;
use crate::show;
/// A lost font, a lost linked picture, an empty object.
fn trouble() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/show/trouble.fodp")
}
#[test]
fn the_check_finds_fonts_links_and_broken_objects_by_slide() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
// Beside it: an undecodable picture, a linked text.
let path = dir.path().join("trouble.fodp");
std::fs::copy(trouble(), &path).expect("copies");
std::fs::write(dir.path().join("broken.png"), "not a valid image").expect("writes");
let linked = dir.path().join("linked.odt");
let blank = worker.load("private:factory/swriter").expect("a text");
blank.save_as(&mut worker, &crate::file_url(&linked), "odt").expect("saves");
worker.close_doc(blank).expect("closes");
let doc = worker.load(&crate::file_url(&path)).expect("loads");
let json = worker.values(&doc, show::SLIDE_CHECK).expect("reads");
let found = show::check(&json).expect("parses");
assert_eq!(found.slides.len(), 5);
assert!(found.slides[0].fonts.iter().any(|f| f == "Nowhere Sans"), "{json}");
assert!(!found.slides[1].fonts.iter().any(|f| f == "Nowhere Sans"));
assert_eq!(found.slides[1].links, [("file:///nowhere/gone.png".to_string(), true)], "{json}");
assert!(found.slides[1].broken.is_empty(), "said once, as a link");
assert_eq!(found.slides[2].broken, ["Empty"], "{json}");
assert!(!found.masters.is_empty());
let mut bad = found.slides[3].broken.clone();
bad.sort();
assert_eq!(bad, ["Bad", "Junk"], "{json}");
assert_eq!(found.slides[3].links.iter().map(|(_, m)| *m).collect::<Vec<_>>(), [false]);
let ole = |worker: &mut Worker| {
let json = worker.values(&doc, show::SLIDE_CHECK).expect("reads");
show::check(&json).expect("parses").slides[4].links.clone()
};
let there = ole(&mut worker);
assert_eq!(there.len(), 1, "the object is a link");
assert!(there[0].0.ends_with("linked.odt") && !there[0].1);
std::fs::remove_file(&linked).expect("deletes");
assert!(ole(&mut worker)[0].1, "a deleted source is missing");
}
+464
View File
@@ -0,0 +1,464 @@
use super::input::{FODS, open, paragraphs, saved};
use super::*;
use crate::commands;
/// How long a command may take to report.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(10);
/// The latest value the kernel reported for `uno`.
fn state<'a>(seen: &'a Events, uno: &str) -> Option<&'a str> {
seen.states
.iter()
.rev()
.find(|(name, _)| name == uno)
.map(|(_, state)| state.as_str())
}
/// Runs `id` and waits for `uno` to report `want`.
fn run_until(
worker: &mut Worker,
doc: &Doc,
from: &Events,
(id, values): (&str, &[&str]),
(uno, want): (&str, &str),
) -> Events {
worker.run(doc, id, values).expect("the command runs");
let seen = poll_until(worker, doc, from, SETTLE, |seen| {
state(seen, uno) == Some(want)
});
assert_eq!(state(&seen, uno), Some(want), "{id}: {uno}");
seen
}
#[test]
fn every_mapped_command_reaches_the_kernel_and_reports_state() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
assert_eq!(
state(&base, ".uno:Bold"),
Some("false"),
"the kernel seeds state"
);
let typed = {
worker.post_key(&doc, 'a' as u32, 512).expect("a posts");
poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
state(seen, ".uno:Undo") == Some("enabled")
})
};
assert_eq!(
state(&typed, ".uno:Undo"),
Some("enabled"),
"typing enables undo"
);
assert_eq!(state(&typed, ".uno:ModifiedStatus"), Some("true"));
let seen = run_until(
&mut worker,
&doc,
&typed,
("edit.undo", &[]),
(".uno:Redo", "enabled"),
);
let seen = run_until(
&mut worker,
&doc,
&seen,
("edit.redo", &[]),
(".uno:Undo", "enabled"),
);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let seen = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
!seen.selection.is_empty()
});
assert!(!seen.selection.is_empty(), "select all selects");
let mut seen = seen;
for (id, uno) in [
("format.bold", ".uno:Bold"),
("format.italic", ".uno:Italic"),
("format.underline", ".uno:Underline"),
("format.strikeout", ".uno:Strikeout"),
] {
seen = run_until(&mut worker, &doc, &seen, (id, &[]), (uno, "true"));
}
let fonts = worker
.values(&doc, ".uno:CharFontName")
.expect("the font list");
let fonts: serde_json::Value = serde_json::from_str(&fonts).expect("json");
let family = fonts["commandValues"]
.as_object()
.and_then(|fonts| {
fonts
.keys()
.find(|name| name.as_str() != "Liberation Serif")
})
.expect("the kernel lists fonts")
.clone();
seen = run_until(
&mut worker,
&doc,
&seen,
("format.font", &[&family]),
(".uno:CharFontName", &family),
);
seen = run_until(
&mut worker,
&doc,
&seen,
("format.size", &["18"]),
(".uno:FontHeight", "18"),
);
let styles = worker
.values(&doc, ".uno:StyleApply")
.expect("the style list");
assert!(
styles.contains("ParagraphStyles"),
"the kernel lists styles"
);
run_until(
&mut worker,
&doc,
&seen,
("format.style", &["Heading 1", "ParagraphStyles"]),
(".uno:StyleApply", "Heading 1"),
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert!(
paragraphs(&text).is_empty(),
"the paragraph became a heading"
);
let body = text
.replace("<text:h", "<text:p")
.replace("</text:h>", "</text:p>");
assert_eq!(
paragraphs(&body),
["aHello 世界"],
"the heading holds the text"
);
assert!(text.contains("fo:font-weight=\"bold\""), "bold landed");
assert_eq!(
commands::all().count(),
246,
"the rows of text, layout, refs, tools, sheet, calc, data, analysis, page, show and draw"
);
}
#[test]
fn unmapped_commands_and_lists_are_refused() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
assert!(
worker.run(&doc, "format.dialog", &[]).is_err(),
"unknown ids fail here"
);
assert!(
worker.run(&doc, "format.size", &[]).is_err(),
"missing values fail here"
);
let raw = |name: &str, value: &str| Pack::new().u64(doc.id).str(name).u64(1).str(value).bytes();
assert!(
worker
.request(tag::POST_UNO, &raw(".uno:FontDialog", ""))
.is_err(),
"the worker refuses unmapped names"
);
assert!(
worker
.request(tag::POST_UNO, &raw("format.size", "junk"))
.is_err(),
"the worker checks values too"
);
assert!(
worker.values(&doc, ".uno:Copy").is_err(),
"only listed values read"
);
}
#[test]
fn failed_commands_surface_and_change_nothing() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
let size = state(&base, ".uno:FontHeight")
.expect("a seeded size")
.to_string();
assert!(
worker.run(&doc, "edit.undo", &[]).is_err(),
"nothing to undo is an error"
);
assert!(worker.run(&doc, "format.size", &["junk"]).is_err());
assert!(
worker
.run(&doc, "format.font", &["Ely No Such Font"])
.is_err()
);
let missing = worker.run(
&doc,
"format.style",
&["Ely No Such Style", "ParagraphStyles"],
);
assert!(missing.is_err(), "a missing style is an error: {missing:?}");
let seen = poll_until(&mut worker, &doc, &base, SETTLE, |_| false);
assert_eq!(
state(&seen, ".uno:FontHeight").unwrap_or(&size),
size,
"the size stays"
);
assert_ne!(
state(&seen, ".uno:ModifiedStatus"),
Some("true"),
"nothing changed"
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert_eq!(paragraphs(&text), ["Hello 世界"]);
}
#[test]
fn a_kernel_dialog_is_closed_and_reported() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let (done, wait) = std::sync::mpsc::channel();
let (pid_out, pid_in) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
pid_out.send(worker.child.id()).expect("the test waits");
let source = dir.path().join("in.fods");
write(&source, FODS);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the sheet loads");
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
// Calc's Backspace opens Delete Contents.
worker.post_key(&doc, 0, 1283).expect("backspace posts");
let seen = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
!seen.blocked.is_empty()
});
worker
.post_key(&doc, 'z' as u32, 537)
.expect("typing still works");
done.send(seen.blocked).expect("the test waits");
});
let pid = pid_in.recv().expect("the worker starts");
let outcome = wait.recv_timeout(std::time::Duration::from_secs(30));
if outcome.is_err() {
// A blocked worker would hold the test open.
std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.status()
.expect("kill runs");
}
let blocked = outcome.expect("the dialog never blocked the worker");
assert_eq!(blocked, ["Delete Contents"], "the dialog is reported");
}
#[test]
fn a11y_follows_the_focused_paragraph() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
let opened = worker.poll_events(&doc, 0, 250).expect("the first poll");
assert_eq!(
opened.a11y.text, "Hello 世界",
"the open seeds the paragraph"
);
assert_eq!(opened.a11y.caret, Some(0));
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 'a' as u32, 512).expect("a posts");
let seen = poll_until(&mut worker, &doc, &opened, SETTLE, |seen| {
seen.a11y.text == "aHello 世界" && seen.a11y.caret == Some(1)
});
assert_eq!(seen.a11y.text, "aHello 世界", "the paragraph text bridges");
assert_eq!(seen.a11y.caret, Some(1), "the caret bridges");
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let all = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.a11y.selection == Some((0, 9))
});
assert_eq!(all.a11y.selection, Some((0, 9)), "the selection bridges");
worker
.post_key(&doc, 0, 1027)
.expect("Right drops the selection");
let none = poll_until(&mut worker, &doc, &all, SETTLE, |seen| {
seen.a11y.selection.is_none()
});
assert_eq!(none.a11y.selection, None, "-1 clears it");
}
#[test]
fn a_selected_image_reports_its_frame() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let mut png = Vec::new();
image::RgbaImage::from_pixel(200, 200, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("the png encodes");
worker
.paste(&doc, "image/png", &png)
.expect("the image pastes");
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
// The image sits as a character at the text start.
click(&mut worker, &doc, 1418 + 1000, 1418 + 1500);
let seen = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.graphic.is_some()
});
let (x, y, w, h) = seen.graphic.expect("the image frame arrives");
assert!(
(1300..1600).contains(&x) && (1300..1600).contains(&y),
"{:?}",
seen.graphic
);
assert!(w > 0 && h > 0, "the frame has a size");
}
#[test]
fn undo_and_redo_follow_the_live_history() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 'a' as u32, 512).expect("a posts");
worker
.run(&doc, "edit.undo", &[])
.expect("undo right after typing");
assert!(
worker.run(&doc, "edit.undo", &[]).is_err(),
"a second undo has nothing"
);
worker
.run(&doc, "edit.redo", &[])
.expect("redo right after undo");
assert!(
worker.run(&doc, "edit.redo", &[]).is_err(),
"a second redo has nothing"
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert_eq!(paragraphs(&text), ["aHello 世界"]);
}
#[test]
fn a_size_finer_than_the_kernel_keeps_is_refused() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
assert!(worker.run(&doc, "format.size", &["18.01"]).is_err());
let raw = Pack::new()
.u64(doc.id)
.str("format.size")
.u64(1)
.str("18.01")
.bytes();
assert!(
worker.request(tag::POST_UNO, &raw).is_err(),
"the worker refuses it too"
);
worker
.run(&doc, "format.size", &["18.05"])
.expect("0.05 steps run");
let text = saved(&dir, &mut worker, &doc, "out.fodt");
let sizes: Vec<f64> = text
.split("fo:font-size=\"")
.skip(1)
.filter_map(|rest| rest.split("pt").next()?.parse().ok())
.collect();
assert!(
sizes.iter().any(|size| (size - 18.05).abs() < 0.001),
"the kernel keeps 18.05: {sizes:?}"
);
}
#[test]
fn a_refused_size_keeps_the_redo() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 'a' as u32, 512).expect("a posts");
worker.run(&doc, "edit.undo", &[]).expect("undo");
let raw = Pack::new()
.u64(doc.id)
.str("format.size")
.u64(1)
.str("18.05000001")
.bytes();
assert!(
worker.request(tag::POST_UNO, &raw).is_err(),
"the worker refuses it"
);
worker
.run(&doc, "edit.redo", &[])
.expect("the redo survives");
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert_eq!(paragraphs(&text), ["aHello 世界"]);
}
#[test]
fn an_owned_save_clears_the_modified_state() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 'a' as u32, 512).expect("a posts");
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
state(seen, ".uno:ModifiedStatus") == Some("true")
});
let copy = dir.path().join("copy.docx");
doc.save_owned(&mut worker, &format!("file://{}", copy.display()), "docx")
.expect("the owned save");
let saved = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
state(seen, ".uno:ModifiedStatus") == Some("false")
});
assert_eq!(state(&saved, ".uno:ModifiedStatus"), Some("false"));
assert!(
std::fs::read(&copy).expect("the copy").starts_with(b"PK"),
"a docx zip"
);
worker.post_key(&doc, 'b' as u32, 513).expect("b posts");
let edited = poll_until(&mut worker, &doc, &saved, SETTLE, |seen| {
state(seen, ".uno:ModifiedStatus") == Some("true")
});
assert_eq!(state(&edited, ".uno:ModifiedStatus"), Some("true"));
let bad = Pack::new()
.u64(doc.id)
.str("file:///tmp/x.odt")
.str("odt")
.str("Evil")
.bytes();
assert!(
worker.request(tag::SAVE_AS, &bad).is_err(),
"unknown options are refused"
);
}
+312
View File
@@ -0,0 +1,312 @@
use super::input::{open, saved};
use super::*;
/// How long a command may take to report.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
#[test]
fn text_and_paragraph_formatting_land_in_the_file() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
for (id, values) in [
("format.superscript", vec![]),
("format.color", vec!["16711680"]),
("format.highlight", vec!["65280"]),
("paragraph.center", vec![]),
("paragraph.spacing_15", vec![]),
("paragraph.indent", vec![]),
("list.numbering", vec![]),
] {
worker
.run(&doc, id, &values)
.unwrap_or_else(|error| panic!("{id}: {error}"));
}
let text = saved(&dir, &mut worker, &doc, "out.fodt");
for mark in [
"style:text-position=\"super",
"fo:color=\"#ff0000\"",
"fo:background-color=\"#00ff00\"",
"fo:text-align=\"center\"",
"fo:line-height=\"150%\"",
"<text:list",
] {
assert!(text.contains(mark), "{mark} lands");
}
}
#[test]
fn tab_stops_add_and_remove_through_the_ruler() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "paragraph.tab", &["-1", "1134", "false"])
.expect("add a 2 cm stop");
let added = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.tabs.len() == 1
});
assert_eq!(added.tabs.len(), 1, "the ruler shows one stop");
assert!(
(added.tabs[0] - 2000).abs() < 10,
"2 cm in 1/100 mm: {:?}",
added.tabs
);
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "paragraph.tab", &["0", "0", "true"])
.expect("remove it");
let removed = poll_until(&mut worker, &doc, &added, SETTLE, |seen| {
seen.tabs.is_empty()
});
assert!(removed.tabs.is_empty(), "the stop is gone");
}
#[test]
fn styles_are_created_and_updated_from_the_selection() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.run(&doc, "format.bold", &[]).expect("bold");
worker
.run(&doc, "style.new", &["Ely Notes", "2"])
.expect("a paragraph style");
let styles = worker
.values(&doc, ".uno:StyleApply")
.expect("the style list");
assert!(
styles.contains("\"Ely Notes\""),
"the kernel lists the new style"
);
worker.run(&doc, "format.italic", &[]).expect("italic");
worker
.run(&doc, "style.update", &["Ely Notes", "2"])
.expect("the style updates");
worker
.run(&doc, "style.new", &["Ely Mark", "1"])
.expect("a character style");
assert!(
worker.run(&doc, "style.new", &["", "2"]).is_err(),
"a style needs a name"
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert!(
text.contains("style:display-name=\"Ely Notes\"")
|| text.contains("style:name=\"Ely Notes\"")
);
assert!(text.contains("Ely Mark"), "the character style lands");
}
#[test]
fn the_remaining_rows_reach_the_kernel() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
for id in [
"format.subscript",
"paragraph.right",
"paragraph.justify",
"paragraph.left",
"paragraph.indent",
"paragraph.outdent",
"paragraph.spacing_2",
"paragraph.spacing_1",
"list.bullets",
"list.deeper",
"list.higher",
] {
worker
.run(&doc, id, &[])
.unwrap_or_else(|error| panic!("{id}: {error}"));
}
}
#[test]
fn list_levels_go_deeper_and_back() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.run(&doc, "list.numbering", &[]).expect("numbering");
worker
.run(&doc, "list.deeper", &[])
.expect("one level deeper");
let deeper = saved(&dir, &mut worker, &doc, "deeper.fodt");
assert_eq!(
deeper.matches("<text:list-item").count(),
2,
"level 2 nests"
);
worker.run(&doc, "list.higher", &[]).expect("back up");
let higher = saved(&dir, &mut worker, &doc, "higher.fodt");
assert_eq!(
higher.matches("<text:list-item").count(),
1,
"level 1 again"
);
}
#[test]
fn spacing_above_and_below_set_apart() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "paragraph.spacing", &["0", "212"])
.expect("6 pt below");
let below = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
state(seen, ".uno:ULSpacing") == Some("0,212")
});
worker
.run(&doc, "paragraph.spacing", &["423", "212"])
.expect("12 pt above");
poll_until(&mut worker, &doc, &below, SETTLE, |seen| {
state(seen, ".uno:ULSpacing") == Some("423,212")
});
let text = saved(&dir, &mut worker, &doc, "spacing.fodt");
assert!(
text.contains("fo:margin-top=\"0.1665in\" fo:margin-bottom=\"0.0835in\""),
"above changed, below kept"
);
}
#[test]
fn the_character_style_is_reported() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
worker
.run(&doc, "format.style", &["Emphasis", "CharacterStyles"])
.expect("emphasis");
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
state(seen, ".uno:CharStyle") == Some("Emphasis")
});
assert_eq!(state(&seen, ".uno:CharStyle"), Some("Emphasis"));
}
/// The latest value of `uno` in a batch.
fn state<'a>(seen: &'a Events, uno: &str) -> Option<&'a str> {
seen.states
.iter()
.rev()
.find(|(name, _)| name == uno)
.map(|(_, value)| value.as_str())
}
#[test]
fn mixed_selections_report_dont_care() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
for key in "One".chars() {
worker.post_key(&doc, key as u32, 0).expect("a key");
}
worker
.run(&doc, "format.style", &["Heading 1", "ParagraphStyles"])
.expect("a heading");
worker.post_key(&doc, 0, 1029).expect("end");
worker.post_key(&doc, 13, 1280).expect("enter");
for key in "Two".chars() {
worker.post_key(&doc, key as u32, 0).expect("a key");
}
worker
.post_key(&doc, 0, 1028 | 0x1000)
.expect("select the word");
worker
.run(&doc, "format.style", &["Emphasis", "CharacterStyles"])
.expect("emphasis");
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let names = [
".uno:Italic",
".uno:CharStyle",
".uno:StyleApply",
".uno:ULSpacing",
];
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
names
.iter()
.all(|name| state(seen, name) == Some(crate::MIXED))
});
for name in names {
assert_eq!(state(&seen, name), Some(crate::MIXED), "{name} is mixed");
}
}
#[test]
fn character_styles_mix_their_attributes() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
for key in "Alpha Beta".chars() {
worker.post_key(&doc, key as u32, 0).expect("a key");
}
worker.post_key(&doc, 0, 1028).expect("home");
for _ in 0..5 {
worker.post_key(&doc, 0, 1027 | 0x1000).expect("select");
}
worker
.run(&doc, "format.style", &["Source Text", "CharacterStyles"])
.expect("a monospace style");
worker.post_key(&doc, 0, 1029).expect("end");
for _ in 0..4 {
worker.post_key(&doc, 0, 1026 | 0x1000).expect("select");
}
worker
.run(
&doc,
"format.style",
&["Strong Emphasis", "CharacterStyles"],
)
.expect("a bold style");
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let names = [".uno:CharFontName", ".uno:Bold", ".uno:CharStyle"];
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
names
.iter()
.all(|name| state(seen, name) == Some(crate::MIXED))
});
for name in names {
assert_eq!(state(&seen, name), Some(crate::MIXED), "{name} is mixed");
}
}
+362
View File
@@ -0,0 +1,362 @@
use super::input::FODS;
use super::*;
/// How long the kernel may take to answer.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
/// The FODS fixture, loaded and its cursor read.
fn open() -> (tempfile::TempDir, Worker, Doc, Events) {
let install = install().expect("the pinned LOK build");
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("in.fods");
write(&source, FODS);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the sheet loads");
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cell.cursor.is_some()
});
(dir, worker, doc, seen)
}
fn type_text(worker: &mut Worker, doc: &Doc, text: &str) {
for c in text.chars() {
worker.post_key(doc, c as u32, 0).expect("a key posts");
}
}
/// The cells of `range`, as the kernel copies them.
fn values(worker: &mut Worker, doc: &Doc, range: &str) -> String {
worker.run(doc, "cell.goto", &[range]).expect("the range");
doc.selection_text(worker).expect("the text")
}
#[test]
fn typing_a_formula_offers_functions_usage_and_marks() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.post_key(&doc, 0, 1024).expect("Down to A2");
type_text(&mut worker, &doc, "=SU");
let offered = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.cell.functions.iter().any(|f| f.name == "SUMIF")
});
let sum = offered.cell.functions.iter().find(|f| f.name == "SUM");
assert!(
sum.is_some_and(|f| f.signature.contains(", ")),
"the signature takes the Excel separator: {sum:?}"
);
doc.complete_function(&mut worker, "SUMIF")
.expect("the completion");
let done = poll_until(&mut worker, &doc, &offered, SETTLE, |seen| {
seen.cell.formula == "=SUMIF()"
});
assert_eq!(done.cell.formula, "=SUMIF()", "the name completes");
type_text(&mut worker, &doc, "A1,");
let usage = poll_until(&mut worker, &doc, &done, SETTLE, |seen| {
seen.cell.formula == "=SUMIF(A1,)" && seen.cell.usage.contains('►')
});
assert_eq!(usage.cell.formula, "=SUMIF(A1,)", "typing goes on inside");
assert!(
usage.cell.usage.contains("► Criteria"),
"{}",
usage.cell.usage
);
assert!(usage.cell.functions.is_empty(), "the list gives way");
let b3 = usage.cell.cursor.expect("the cell cursor");
let (x, y) = (b3.0 + b3.2 * 3 / 2, b3.1 + b3.3 * 3 / 2);
for kind in [0, 1] {
let click = Mouse {
kind,
x,
y,
count: 1,
buttons: 1,
modifiers: 0,
};
worker.post_mouse(&doc, click).expect("the click posts");
}
let picked = poll_until(&mut worker, &doc, &usage, SETTLE, |seen| {
seen.cell.formula == "=SUMIF(A1,B3)" && !seen.cell.marks.is_empty()
});
assert_eq!(
picked.cell.formula, "=SUMIF(A1,B3)",
"a click picks the cell"
);
assert_eq!(picked.cell.marks.len(), 1, "the picked cell is marked");
assert_eq!(picked.cell.marks[0].part, 0);
type_text(&mut worker, &doc, "*2");
let typed = poll_until(&mut worker, &doc, &picked, SETTLE, |seen| {
seen.cell.formula == "=SUMIF(A1,B3*2)"
});
assert_eq!(
typed.cell.formula, "=SUMIF(A1,B3*2)",
"typing goes on after a pick"
);
let picked = typed;
// The first Escape may only close the kernel's hint.
worker.post_key(&doc, 0, 1281).expect("Escape");
worker.post_key(&doc, 0, 1281).expect("Escape cancels");
let done = poll_until(&mut worker, &doc, &picked, SETTLE, |seen| {
seen.cell.marks.is_empty() && seen.cell.formula.is_empty()
});
assert!(done.cell.marks.is_empty(), "{:?}", done.cell);
worker
.run(&doc, "cell.enter", &["=A1+B3"])
.expect("a formula");
worker.run(&doc, "cell.goto", &["A2"]).expect("back to it");
worker.post_key(&doc, 0, 769).expect("F2 edits it");
let edited = poll_until(&mut worker, &doc, &done, SETTLE, |seen| {
seen.cell.marks.len() == 2
});
assert_eq!(edited.cell.marks.len(), 2, "each reference is marked");
worker.post_key(&doc, 0, 1280).expect("Enter commits");
let entered = poll_until(&mut worker, &doc, &edited, SETTLE, |seen| {
seen.cell.marks.is_empty()
});
assert!(entered.cell.marks.is_empty(), "the commit clears the marks");
}
#[test]
fn a_broken_formula_enters_as_typed_without_a_dialog() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.run(&doc, "cell.goto", &["C1"]).expect("C1");
type_text(&mut worker, &doc, "=1+");
worker.post_key(&doc, 0, 1280).expect("Enter");
let entered = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.cell.address == "C2"
});
assert!(
entered.blocked.is_empty(),
"no dialog: {:?}",
entered.blocked
);
assert!(values(&mut worker, &doc, "C1").starts_with("Err:"));
}
#[test]
fn formulas_take_excel_syntax() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, _) = open();
let sheet = doc.sheets(&mut worker).expect("the sheets").list[0]
.name
.clone();
for (cell, formula) in [
("D1", "=SUM(1,2)"),
("D2", &format!("='{sheet}'!D1*2")),
("D3", "=SUM($D$1:D2,1)"),
] {
worker.run(&doc, "cell.goto", &[cell]).expect("the cell");
worker
.run(&doc, "cell.enter", &[formula])
.expect("the entry");
}
assert_eq!(values(&mut worker, &doc, "D1:D3"), "3\n6\n10\n");
}
/// Enters each formula at its cell.
fn enter(worker: &mut Worker, doc: &Doc, cells: &[(&str, &str)]) {
for (cell, formula) in cells {
worker.run(doc, "cell.goto", &[cell]).expect("the cell");
worker
.run(doc, "cell.enter", &[formula])
.expect("the entry");
}
}
#[test]
fn the_kernel_computes_each_family_of_functions() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, _) = open();
enter(
&mut worker,
&doc,
&[
("F1", "3"),
("F2", "1"),
("F3", "2"),
("F4", "3"),
("G1", "=F1^2+F2*4-F3/2"),
("G2", "=IF(AND(F1>2,NOT(F2=2)),\"yes\",\"no\")"),
("G3", "=COUNTIF(F1:F4,3)+SUMIFS(F1:F4,F1:F4,\">1\")"),
(
"G4",
"=CONCAT(LEFT(\"Ely Office\",3),\"-\",TEXT(0.25,\"0%\"))",
),
(
"G5",
"=DATEDIF(DATE(2026,1,31),EDATE(DATE(2026,1,31),1),\"d\")",
),
(
"G6",
"=XLOOKUP(2,F2:F4,F2:F4*10)+INDEX(F1:F4,MATCH(1,F1:F4,0))",
),
("G7", "=SUM(SORT(UNIQUE(F1:F4),1,-1))"),
("G8", "=ROWS(FILTER(F1:F4,F1:F4>1))*SUM(SEQUENCE(3))"),
],
);
assert_eq!(
values(&mut worker, &doc, "G1:G8"),
"12\nyes\n10\nEly-25%\n28\n21\n6\n18\n"
);
}
#[test]
fn manual_calculation_waits_and_survives_a_save() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc, seen) = open();
enter(&mut worker, &doc, &[("F1", "1"), ("F2", "=F1*2")]);
assert_eq!(values(&mut worker, &doc, "F2"), "2");
worker.run(&doc, "calc.auto", &["false"]).expect("manual");
let manual = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.states
.contains(&(".uno:AutomaticCalculation".into(), "false".into()))
});
assert!(
manual
.states
.contains(&(".uno:AutomaticCalculation".into(), "false".into())),
"the state follows"
);
enter(&mut worker, &doc, &[("F1", "5")]);
assert_eq!(values(&mut worker, &doc, "F2"), "2", "the formula waits");
worker.run(&doc, "calc.now", &[]).expect("a recalc");
assert_eq!(values(&mut worker, &doc, "F2"), "10", "a recalc updates");
for format in ["ods", "xlsx", "xls", "fods"] {
let path = dir.path().join(format!("manual.{format}"));
doc.save_as(&mut worker, &crate::file_url(&path), format)
.expect("the save");
let again = worker
.load(&crate::file_url(&path))
.expect("the copy loads");
let state = poll_until(&mut worker, &again, &Events::default(), SETTLE, |seen| {
seen.states
.iter()
.any(|(name, _)| name == ".uno:AutomaticCalculation")
});
let auto = state
.states
.iter()
.rfind(|(name, _)| name == ".uno:AutomaticCalculation")
.map(|(_, value)| value.as_str());
assert_eq!(auto, Some("false"), "{format} keeps manual calculation");
worker.close_doc(again).expect("the copy closes");
}
}
#[test]
fn a_circular_reference_reports_its_error() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, seen) = open();
enter(&mut worker, &doc, &[("F1", "=F2+1"), ("F2", "=F1")]);
worker.run(&doc, "cell.goto", &["F1"]).expect("F1");
let state = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.states
.iter()
.any(|(name, value)| name == ".uno:StateTableCell" && value.contains("Circular"))
});
assert!(
state
.states
.iter()
.any(|(_, value)| value == "Error: Circular reference"),
"{:?}",
state.states
);
assert_eq!(values(&mut worker, &doc, "F1"), "Err:522");
}
#[test]
fn names_are_defined_changed_removed_and_flag_breaks() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, _) = open();
let sheet = doc.sheets(&mut worker).expect("the sheets").list[0]
.name
.clone();
let read = |worker: &mut Worker| {
crate::sheet::names(&worker.values(&doc, crate::sheet::NAMES).expect("names"))
.expect("the names parse")
};
enter(&mut worker, &doc, &[("F1", "2"), ("F2", "5")]);
let range = format!("'{sheet}'!$F$1");
worker
.run(&doc, "names.define", &["Rate", &range, ""])
.expect("a workbook name");
worker
.run(&doc, "names.define", &["Local", "$F$2", &sheet])
.expect("a sheet name");
enter(&mut worker, &doc, &[("G1", "=Rate*10+Local")]);
assert_eq!(values(&mut worker, &doc, "G1"), "25");
let names = read(&mut worker);
let rate = names.iter().find(|name| name.name == "Rate").expect("Rate");
assert_eq!((rate.scope.as_str(), rate.broken), ("", false));
assert!(
names
.iter()
.any(|name| name.name == "Local" && name.scope == sheet)
);
let moved = format!("'{sheet}'!$F$2");
worker
.run(&doc, "names.define", &["Rate", &moved, ""])
.expect("a new range");
assert_eq!(values(&mut worker, &doc, "G1"), "55", "the range moves");
worker.run(&doc, "edit.undo", &[]).expect("an undo");
assert_eq!(values(&mut worker, &doc, "G1"), "25", "the change undoes");
assert!(
worker
.run(&doc, "names.define", &["A1", "$F$1", ""])
.is_err(),
"a cell address is no name"
);
let check = |worker: &mut Worker, name: &str| {
let query = crate::sheet::name_check_query(name);
crate::sheet::name_check(&worker.values(&doc, &query).expect("a check"))
.expect("the check parses")
};
assert_eq!(check(&mut worker, "Tax_2026"), "valid");
assert_eq!(check(&mut worker, "B2"), "address");
assert_eq!(check(&mut worker, "a b&c"), "characters");
worker.run(&doc, "cell.goto", &["Rate"]).expect("a jump");
assert_eq!(
poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cell.address == "Rate"
})
.cell
.address,
"Rate",
"the name box jumps to a name and shows it"
);
worker.run(&doc, "cell.goto", &["F1"]).expect("F1");
worker.run(&doc, "rows.delete", &[]).expect("row 1 goes");
let names = read(&mut worker);
assert!(
names.iter().any(|name| name.name == "Rate" && name.broken),
"a deleted target breaks the name: {names:?}"
);
worker
.run(&doc, "names.remove", &["Local", &sheet])
.expect("a removal");
assert!(!read(&mut worker).iter().any(|name| name.name == "Local"));
}
@@ -0,0 +1,68 @@
use super::output::pdf_text;
use super::*;
/// Five slides, the fourth hidden.
const FIVE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.presentation">
<office:automatic-styles>
<style:style style:name="dp2" style:family="drawing-page">
<style:drawing-page-properties presentation:visibility="hidden"/>
</style:style>
</office:automatic-styles>
<office:body><office:presentation>
<draw:page draw:name="A"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Alpha</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="B"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Bravo</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="C"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Charlie</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="D" draw:style-name="dp2"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Delta</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="E"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Echo</text:p></draw:text-box></draw:frame></draw:page>
</office:presentation></office:body>
</office:document>"#;
fn handouts(pages: Option<(u32, u32)>, per: u8) -> crate::Pdf {
crate::Pdf {
pages,
handouts: per,
..crate::Pdf::default()
}
}
#[test]
fn handouts_lay_shown_slides_in_range_per_page() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let path = dir.path().join("five.fodp");
std::fs::write(&path, FIVE).expect("writes");
let doc = worker.load(&crate::file_url(&path)).expect("loads");
let pdf = dir.path().join("two.pdf");
let url = crate::file_url(&pdf);
doc.export_pdf(&mut worker, &url, &handouts(None, 2)).expect("exports");
let some = dir.path().join("some.pdf");
doc.export_pdf(&mut worker, &crate::file_url(&some), &handouts(Some((2, 3)), 4))
.expect("exports a range");
assert!(
doc.export_pdf(&mut worker, &url, &handouts(None, 5)).is_err(),
"five a page is not a handout layout"
);
let (Some(all), Some(part)) = (pdf_text(&pdf), pdf_text(&some)) else {
eprintln!("SKIP: no pdftotext to read the PDF");
return;
};
let pages: Vec<&str> = all.split('\x0c').filter(|page| !page.trim().is_empty()).collect();
assert_eq!(pages.len(), 2, "four shown slides, two a page: {all:?}");
assert!(pages[0].contains("Alpha") && pages[0].contains("Bravo"));
assert!(pages[1].contains("Charlie") && pages[1].contains("Echo"));
assert!(!all.contains("Delta"), "hidden slides stay out");
let pages: Vec<&str> = part.split('\x0c').filter(|page| !page.trim().is_empty()).collect();
assert_eq!(pages.len(), 1);
assert!(part.contains("Bravo") && part.contains("Charlie") && !part.contains("Alpha"));
}
@@ -0,0 +1,100 @@
//! §19.2: Ely edits, saves, reopens; another reader checks.
use std::{path::Path, process::Command};
use super::input::{FODS, open};
use super::roundtrip::type_in;
use super::show::open_deck;
use super::*;
/// Saves as `format`, closes, reopens for a second edit.
fn reopened(worker: &mut Worker, doc: Doc, dir: &Path, name: &str, format: &str) -> Doc {
let first = dir.join(format!("{name}.{format}"));
doc.save_as(worker, &crate::file_url(&first), format).expect("the first save");
worker.close_doc(doc).expect("closes");
worker.load(&crate::file_url(&first)).expect("reopens")
}
/// The second save, read by `tests/scripts/ooxml.py`.
fn checked(worker: &mut Worker, doc: Doc, dir: &Path, case: &str, format: &str) {
let last = dir.join(format!("{case}-again.{format}"));
doc.save_as(worker, &crate::file_url(&last), format).expect("the second save");
worker.close_doc(doc).expect("closes");
let reader = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/scripts/ooxml.py");
// The file passes, and each known damage to it fails.
for args in [vec![case], vec!["selftest", case]] {
let out = match Command::new("python3").arg(&reader).args(&args).arg(&last).output() {
Ok(out) => out,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return eprintln!("SKIP: no python3 to read {case}");
}
Err(error) => panic!("the reader did not run: {error}"),
};
let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(out.status.success(), "{args:?}: {said}");
}
}
#[test]
fn a_docx_keeps_text_comments_and_tracking_across_sessions() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
type_in(&mut worker, &doc, "Alpha 甲 ");
worker.run(&doc, "comment.insert", &["Check alpha"]).expect("comments");
worker.run(&doc, "track.toggle", &[]).expect("tracks");
type_in(&mut worker, &doc, "Beta ");
let doc = reopened(&mut worker, doc, dir.path(), "contract", "docx");
type_in(&mut worker, &doc, "Gamma ");
checked(&mut worker, doc, dir.path(), "contract", "docx");
}
#[test]
fn an_xlsx_keeps_formulas_and_results_across_sessions() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODS);
let enter = |worker: &mut Worker, doc: &Doc, cells: &[(&str, &str)]| {
for (cell, entry) in cells {
worker.run(doc, "cell.goto", &[cell]).expect("the cell");
worker.run(doc, "cell.enter", &[entry]).expect("the entry");
}
};
enter(&mut worker, &doc, &[
("H1", "7"),
("H2", "5"),
("H3", "=H1*H2"),
("H4", "=H1/3"),
("H5", "=DATE(2024,2,29)"),
("H6", "=1/0"),
("H7", "=\"Ely\"&\"-\"&TEXT(H1,\"0\")"),
("H8", "=SUM(H1:H2)"),
]);
let doc = reopened(&mut worker, doc, dir.path(), "sheet", "xlsx");
poll_until(&mut worker, &doc, &Events::default(), std::time::Duration::from_secs(3), |seen| {
seen.cell.cursor.is_some()
});
enter(&mut worker, &doc, &[("H9", "=H3+1")]);
checked(&mut worker, doc, dir.path(), "sheet", "xlsx");
}
#[test]
fn a_pptx_keeps_slides_hiding_and_notes_across_sessions() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let at = worker.now(&doc).expect("the state");
worker.run(&at, "notes.set", &["Speaker 甲", "0"]).expect("notes");
doc.show_sheet(&mut worker, 1).expect("slide two");
worker.run(&doc, "slide.hide", &[]).expect("hides");
let doc = reopened(&mut worker, doc, dir.path(), "deck", "pptx");
worker.run(&doc, "slide.insert", &[]).expect("a third slide");
checked(&mut worker, doc, dir.path(), "deck", "pptx");
}
+475
View File
@@ -0,0 +1,475 @@
use super::*;
/// How long an input may take to show.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
/// vcl KEY_A, KEY_MOD1.
const KEY_A: i32 = 512;
const MOD1: i32 = 0x2000;
/// A flat document holding a 2x1 table.
const TABLE_FODT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:body><office:text><table:table table:name="T"><table:table-column table:number-columns-repeated="2"/>
<table:table-row><table:table-cell><text:p>left</text:p></table:table-cell><table:table-cell><text:p>right</text:p></table:table-cell></table:table-row>
</table:table><text:p>after</text:p></office:text></office:body>
</office:document>"#;
/// A worker with one loaded document.
pub(super) fn open(body: &str) -> (tempfile::TempDir, Worker, Doc) {
let install = install().expect("the pinned LOK build");
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("in.fodt");
write(&source, body);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
(dir, worker, doc)
}
/// The document saved as flat XML.
pub(super) fn saved(dir: &tempfile::TempDir, worker: &mut Worker, doc: &Doc, name: &str) -> String {
let out = dir.path().join(name);
doc.save_as(worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
std::fs::read_to_string(&out).expect("the save reads")
}
/// Each paragraph's text, tags stripped.
pub(crate) fn paragraphs(xml: &str) -> Vec<String> {
xml.split("<text:p")
.skip(1)
.map(|rest| {
let body = &rest[rest.find('>').map_or(0, |at| at + 1)..];
let body = &body[..body.find("</text:p>").unwrap_or(0)];
let mut text = String::new();
let mut tag = false;
for c in body.chars() {
match c {
'<' => tag = true,
'>' => tag = false,
c if !tag => text.push(c),
_ => {}
}
}
text
})
.collect()
}
/// A 4x4 red PNG.
pub(super) fn red_png() -> Vec<u8> {
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]));
let mut png = Vec::new();
image
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("the png encodes");
png
}
#[test]
fn an_ime_composition_commits_once() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
for step in ["n", "ni", "你"] {
worker
.post_text(&doc, false, step)
.expect("the update posts");
}
worker.post_text(&doc, true, "").expect("the commit posts");
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert_eq!(text, ["你Hello 世界"], "the composition lands once");
}
#[test]
fn a_cancelled_composition_leaves_nothing() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.post_text(&doc, false, "ni")
.expect("the update posts");
worker.post_text(&doc, false, "").expect("the cancel posts");
worker.post_text(&doc, true, "").expect("the end posts");
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert_eq!(text, ["Hello 世界"], "the paragraph is untouched");
}
#[test]
fn keys_carry_chars_and_modifiers() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 'a' as u32, KEY_A).expect("a posts");
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert_eq!(text, ["aHello 世界"], "the char lands");
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
worker
.post_key(&doc, 0, MOD1 | KEY_A)
.expect("select all posts");
let seen = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
!seen.selection.is_empty()
});
assert!(!seen.selection.is_empty(), "mod1+A selects: {seen:?}");
}
#[test]
fn the_kernels_close_keys_are_refused() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
// Mod1+W, Mod1+F4, Mod1+Q close the frame or quit.
for key in [534, 771, 528] {
let refused = worker.post_key(&doc, 0, MOD1 | key).expect_err("refused");
assert!(refused.to_string().contains("closes the kernel's frame"), "{refused}");
}
std::thread::sleep(std::time::Duration::from_millis(500));
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert_eq!(text, ["Hello 世界"], "the document stays open");
}
#[test]
fn the_cursor_and_selection_arrive_in_twips() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
let (width, height) = doc.size(&mut worker).expect("the size");
click(&mut worker, &doc, 150, 150);
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cursor.is_some()
});
let (x, y, w, h) = seen.cursor.expect("a cursor rect");
assert!(
x >= 0 && y >= 0 && x < width as i32 && y < height as i32 && w >= 0 && h > 0,
"the cursor sits in the page: {:?}",
seen.cursor
);
assert!(seen.cursor_visible, "the cursor shows");
let down = |kind, x| Mouse {
kind,
x,
y: y + h / 2,
count: 1,
buttons: 1,
modifiers: 0,
};
worker.post_mouse(&doc, down(0, x)).expect("press");
worker.post_mouse(&doc, down(2, x + 1500)).expect("drag");
worker.post_mouse(&doc, down(1, x + 1500)).expect("release");
let dragged = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
!seen.selection.is_empty()
});
assert!(!dragged.selection.is_empty(), "a drag selects: {dragged:?}");
}
#[test]
fn copy_gives_text_and_html_and_paste_takes_html() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
assert!(
worker.copy(&doc).expect("copy runs").is_empty(),
"nothing selected, nothing copied"
);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let flavors = worker.copy(&doc).expect("copy runs");
let get = |mime: &str| {
flavors
.iter()
.find(|(name, _)| name == mime)
.map(|(_, data)| String::from_utf8_lossy(data).into_owned())
};
assert_eq!(
get("text/plain;charset=utf-8").as_deref(),
Some("Hello 世界")
);
let html = get("text/html").expect("an html flavor");
assert!(html.contains("Hello"), "the html holds the text: {html}");
assert!(!html.contains('\0'), "no NUL rides along");
let target = dir.path().join("b.fodt");
write(&target, FODT);
let other = worker
.load(&format!("file://{}", target.display()))
.expect("b loads");
click(&mut worker, &other, 150, 150);
worker
.paste(&other, "text/html", html.as_bytes())
.expect("the html pastes");
let text = saved(&dir, &mut worker, &other, "b-out.fodt");
assert_eq!(
text.matches("Hello").count(),
2,
"b gained the text: {text}"
);
}
#[test]
fn a_cut_after_copy_removes_the_selection() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
assert!(
!worker.copy(&doc).expect("copy runs").is_empty(),
"the copy has flavors"
);
worker.cut(&doc).expect("the cut runs");
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert_eq!(text, [""], "the selection is gone");
}
#[test]
fn a_paste_the_engine_drops_is_an_error() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let broken = worker.paste(&doc, "image/png", b"this is not a png");
assert!(broken.is_err(), "a corrupt image is refused: {broken:?}");
assert!(
worker.paste(&doc, "text/html", b"").is_err(),
"an empty paste is refused"
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert_eq!(paragraphs(&text), ["Hello 世界"]);
assert!(!text.contains("<draw:image"));
}
#[test]
fn a_corrupt_image_over_a_selection_keeps_the_text() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let mut bad = red_png();
bad.truncate(bad.len() / 2);
assert!(
worker.paste(&doc, "image/png", &bad).is_err(),
"a cut-off png is refused"
);
assert!(
!worker.copy(&doc).expect("copy runs").is_empty(),
"the selection stays"
);
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert_eq!(paragraphs(&text), ["Hello 世界"], "the text stays");
}
/// A spreadsheet whose A1 holds text.
pub(crate) const FODS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S"><table:table-row><table:table-cell><text:p>Hello 世界</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body>
</office:document>"#;
#[test]
fn a_calc_cut_finishes_without_a_dialog() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let (done, wait) = std::sync::mpsc::channel();
let (pid_out, pid_in) = std::sync::mpsc::channel();
let dir = tempfile::tempdir().expect("a temp dir");
let root = dir.path().to_path_buf();
std::thread::spawn(move || {
let mut worker = Worker::spawn(&install, &root.join("profile")).expect("the worker");
pid_out.send(worker.child.id()).expect("the test waits");
let source = root.join("in.fods");
write(&source, FODS);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the sheet loads");
worker
.post_key(&doc, 0, 1027 | 0x1000)
.expect("shift+right selects");
let copied = worker.copy(&doc).expect("copy runs");
worker.cut(&doc).expect("the cut runs");
let out = root.join("out.fods");
doc.save_as(&mut worker, &format!("file://{}", out.display()), "fods")
.expect("the save works");
let xml = std::fs::read_to_string(&out).expect("the save reads");
done.send((copied.len(), xml.contains("Hello")))
.expect("the test waits");
});
let pid = pid_in.recv().expect("the worker starts");
let outcome = wait.recv_timeout(std::time::Duration::from_secs(20));
if outcome.is_err() {
// A blocked worker would hold the test open.
std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.status()
.expect("kill runs");
}
let (flavors, kept) = outcome.expect("the cut never blocked on a dialog");
assert!(flavors > 0, "the cells copied");
assert!(!kept, "the cut emptied A1");
}
#[test]
fn a_table_survives_copy_and_paste() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(TABLE_FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
worker
.run(&doc, "edit.select_all", &[])
.expect("select the whole text");
let flavors = worker.copy(&doc).expect("copy runs");
let (_, html) = flavors
.iter()
.find(|(mime, _)| mime == "text/html")
.expect("an html flavor");
let html = String::from_utf8_lossy(html);
assert!(
html.contains("<table"),
"the html carries the table: {html}"
);
let target = dir.path().join("b.fodt");
write(&target, FODT);
let other = worker
.load(&format!("file://{}", target.display()))
.expect("b loads");
click(&mut worker, &other, 150, 150);
worker
.paste(&other, "text/html", html.as_bytes())
.expect("the table pastes");
let text = saved(&dir, &mut worker, &other, "b-out.fodt");
assert!(text.contains("<table:table "), "b gained a table: {text}");
assert!(text.contains("left") && text.contains("right"));
}
#[test]
fn an_image_pastes_and_copies_back() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.paste(&doc, "image/png", &red_png())
.expect("the image pastes");
let text = saved(&dir, &mut worker, &doc, "out.fodt");
assert!(text.contains("<draw:image"), "the image lands: {text}");
let flavors = worker.copy(&doc).expect("copy runs");
let png = flavors
.iter()
.find(|(mime, _)| mime == "image/png")
.map(|(_, data)| data.clone())
.expect("the selected image copies as png");
let back = image::load_from_memory(&png)
.expect("the png decodes")
.to_rgba8();
assert_eq!(back.get_pixel(0, 0).0, [255, 0, 0, 255], "red comes back");
}
#[test]
fn a_foreign_paste_flavor_is_refused() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(FODT);
assert!(worker.paste(&doc, "application/x-evil", b"x").is_err());
worker.post_key(&doc, 0, 1027).expect("the worker lives");
}
/// HTML carrying `png` as an inline image.
fn inline_html(png: &[u8]) -> String {
use base64::Engine;
let data = base64::engine::general_purpose::STANDARD.encode(png);
format!(r#"<html><body><img src="data:image/png;base64,{data}"></body></html>"#)
}
#[test]
fn inline_images_paste_only_when_they_decode() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let broken = inline_html(b"this is not a png");
assert!(worker.paste(&doc, "text/html", broken.as_bytes()).is_err());
assert!(
!worker.copy(&doc).expect("copy runs").is_empty(),
"the selection stays"
);
let text = saved(&dir, &mut worker, &doc, "kept.fodt");
assert_eq!(paragraphs(&text), ["Hello 世界"], "the text stays");
worker
.post_key(&doc, 0, 1029)
.expect("End drops the selection");
worker
.paste(&doc, "text/html", inline_html(&red_png()).as_bytes())
.expect("a real inline image pastes");
let text = saved(&dir, &mut worker, &doc, "image.fodt");
assert_eq!(text.matches("<draw:image").count(), 1, "the image lands");
}
#[test]
fn pastes_keep_working_past_the_undo_cap() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
for n in 1..=105 {
worker
.paste(
&doc,
"text/plain;charset=utf-8",
format!("p{n} ").as_bytes(),
)
.unwrap_or_else(|error| panic!("paste {n} failed: {error}"));
}
let text = paragraphs(&saved(&dir, &mut worker, &doc, "out.fodt"));
assert!(
text[0].contains("p105 ") && text[0].contains("p1 "),
"every paste landed"
);
}
@@ -0,0 +1,52 @@
use super::input::FODS;
use super::*;
/// Keys never queue behind a view's event watch.
#[test]
fn keys_never_wait_behind_the_event_watch() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().unwrap();
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).unwrap();
let source = dir.path().join("in.fods");
write(&source, FODS);
let doc = worker
.load(&format!("file://{}", source.display()))
.unwrap();
let feed = worker.feed();
let shared = std::sync::Arc::new(std::sync::Mutex::new(worker));
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let poller = {
let (feed, doc, stop) = (feed.clone(), doc.clone(), stop.clone());
std::thread::spawn(move || {
let mut known = 0;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
known = feed.wait(&doc, known, 50).unwrap().seq;
}
})
};
let mut waits = Vec::new();
let mut calls = Vec::new();
for c in "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz".chars() {
let start = std::time::Instant::now();
let mut worker = shared.lock().unwrap();
let locked = start.elapsed();
worker.post_key(&doc, c as u32, 0).unwrap();
drop(worker);
waits.push(locked.as_secs_f64() * 1000.0);
calls.push((start.elapsed() - locked).as_secs_f64() * 1000.0);
std::thread::sleep(std::time::Duration::from_millis(30));
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
poller.join().unwrap();
let stat = |v: &mut Vec<f64>| {
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
(v[v.len() / 2], v[v.len() * 95 / 100], v[v.len() - 1])
};
let (waited, called) = (stat(&mut waits), stat(&mut calls));
log::info!("keys: lock wait {waited:?} ms, call {called:?} ms");
assert!(waited.1 < 2.0, "keys wait for the lock: {waited:?} ms");
assert!(called.1 < 30.0, "a key round trip is slow: {called:?} ms");
}
+404
View File
@@ -0,0 +1,404 @@
use super::input::{open, saved};
use super::*;
const SETTLE: std::time::Duration = std::time::Duration::from_secs(10);
/// The latest value of `uno` seen so far.
fn state<'a>(seen: &'a Events, uno: &str) -> Option<&'a str> {
seen.states
.iter()
.rev()
.find(|(name, _)| name == uno)
.map(|(_, value)| value.as_str())
}
fn run(worker: &mut Worker, doc: &Doc, id: &str, values: &[&str]) {
worker
.run(doc, id, values)
.unwrap_or_else(|error| panic!("{id}: {error}"));
}
/// Lets the kernel settle a selection, as a person does.
fn pause(worker: &mut Worker, doc: &Doc) {
poll_until(
worker,
doc,
&Events::default(),
std::time::Duration::from_millis(500),
|_| false,
);
}
/// A solid PNG on disk, as a file URL.
pub(super) fn png(dir: &std::path::Path, name: &str, rgba: [u8; 4]) -> String {
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(300, 200, image::Rgba(rgba))
.write_to(
&mut std::io::Cursor::new(&mut bytes),
image::ImageFormat::Png,
)
.expect("the png encodes");
let path = dir.join(name);
std::fs::write(&path, bytes).expect("the png writes");
crate::file_url(&path)
}
#[test]
fn page_setup_lands_and_reports() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "page.margins_lr", &["1270", "2540"]);
run(&mut worker, &doc, "page.margins_ul", &["2540", "1270"]);
run(&mut worker, &doc, "page.columns", &["2"]);
run(&mut worker, &doc, "page.size", &["21000", "29700"]);
run(
&mut worker,
&doc,
"page.orientation",
&["29700", "21000", "true", "0", "4"],
);
let want = [
(".uno:PageLRMargin", "1270,2540"),
(".uno:PageULMargin", "2540,1270"),
(".uno:PageColumnType", "2"),
(".uno:AttributePage", "true,0,4"),
(".uno:AttributePageSize", "29700 x 21001"),
];
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
want.iter()
.all(|(uno, value)| state(seen, uno) == Some(*value))
});
for (uno, value) in want {
assert_eq!(state(&seen, uno), Some(value), "{uno}");
}
let text = saved(&dir, &mut worker, &doc, "page.fodt");
for mark in [
"fo:page-width=\"11.6929in\" fo:page-height=\"8.2681in\"",
"style:print-orientation=\"landscape\"",
"fo:margin-top=\"1in\" fo:margin-bottom=\"0.5in\" fo:margin-left=\"0.5in\" fo:margin-right=\"1in\"",
"fo:column-count=\"2\"",
] {
assert!(text.contains(mark), "{mark} lands");
}
}
#[test]
fn headers_footers_and_sections_land() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "header.on", &["true"]);
run(&mut worker, &doc, "footer.on", &["true"]);
run(&mut worker, &doc, "header.layout", &["3"]);
run(&mut worker, &doc, "field.page", &[]);
run(&mut worker, &doc, "field.pages", &[]);
let want = [
(".uno:SwPageHeaderItem", "true"),
(".uno:SwPageFooterItem", "true"),
(".uno:SwPageHeaderLayout", "3"),
];
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
want.iter()
.all(|(uno, value)| state(seen, uno) == Some(*value))
});
for (uno, value) in want {
assert_eq!(state(&seen, uno), Some(value), "{uno}");
}
run(&mut worker, &doc, "page.section", &["3", "Landscape"]);
let section = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
state(seen, ".uno:PageStyleName") == Some("Landscape")
});
assert_eq!(state(&section, ".uno:PageStyleName"), Some("Landscape"));
run(&mut worker, &doc, "header.on", &["false"]);
let text = saved(&dir, &mut worker, &doc, "header.fodt");
for mark in [
"<style:header>",
"<style:header-left>",
"<style:header-first>",
"<style:footer>",
"style:master-page-name=\"Landscape\"",
"<text:page-number",
"<text:page-count",
] {
assert!(text.contains(mark), "{mark} lands");
}
let landscape = text
.split("<style:master-page style:name=\"Landscape\"")
.nth(1)
.and_then(|rest| rest.split("</office:master-styles>").next())
.expect("the section's page style");
assert!(
!landscape.contains("<style:header>"),
"the section's header is off"
);
}
#[test]
fn tables_edit_and_land() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 0, 1029).expect("end");
worker.post_key(&doc, 13, 1280).expect("enter");
run(&mut worker, &doc, "table.insert", &["3", "2"]);
let inside = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
state(seen, ".uno:DeleteTable") == Some("enabled")
});
assert_eq!(
state(&inside, ".uno:DeleteTable"),
Some("enabled"),
"in a table"
);
run(&mut worker, &doc, "table.repeat_heading", &[]);
for (id, values) in [
("table.row_below", vec![]),
("table.row_above", vec![]),
("table.delete_rows", vec![]),
("table.column_right", vec![]),
("table.column_left", vec![]),
("table.delete_columns", vec![]),
("table.shading", vec!["16776960"]),
("table.row_split", vec!["false"]),
("table.split", vec!["2", "false"]),
("table.select", vec![]),
("table.borders_all", vec![]),
("table.even_columns", vec![]),
("table.optimal_height", vec![]),
("table.even_rows", vec![]),
] {
run(&mut worker, &doc, id, &values);
}
let repeated = poll_until(&mut worker, &doc, &inside, SETTLE, |seen| {
state(seen, ".uno:HeadingRowsRepeat") == Some("true")
});
assert_eq!(state(&repeated, ".uno:HeadingRowsRepeat"), Some("true"));
let text = saved(&dir, &mut worker, &doc, "table.fodt");
for mark in [
"<table:table-header-rows>",
"fo:background-color=\"#ffff00\"",
"fo:keep-together=\"always\"",
"fo:border=\"0.5pt solid #000000\"",
"table:number-columns-spanned=\"2\"",
] {
assert!(text.contains(mark), "{mark} lands");
}
run(&mut worker, &doc, "table.borders_none", &[]);
run(&mut worker, &doc, "table.merge", &[]);
run(&mut worker, &doc, "table.delete", &[]);
let text = saved(&dir, &mut worker, &doc, "gone.fodt");
assert!(!text.contains("<table:table "), "the table is gone");
}
#[test]
fn images_insert_scale_wrap_crop_and_stack() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
let (blue, red, green) = (
png(dir.path(), "blue.png", [0, 0, 255, 255]),
png(dir.path(), "red.png", [255, 0, 0, 255]),
png(dir.path(), "green.png", [0, 255, 0, 255]),
);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "image.insert", &[&blue]);
run(&mut worker, &doc, "image.insert", &[&red]);
pause(&mut worker, &doc);
run(&mut worker, &doc, "image.size", &["2835", "1890"]);
run(&mut worker, &doc, "image.anchor_paragraph", &[]);
run(&mut worker, &doc, "image.wrap_through", &[]);
let want = [
(".uno:SetAnchorToPara", "true"),
(".uno:WrapThrough", "true"),
];
let framed = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
want.iter()
.all(|(uno, value)| state(seen, uno) == Some(*value))
});
for (uno, value) in want {
assert_eq!(state(&framed, uno), Some(value), "{uno}");
}
let (x, y, w, h) = framed.graphic.expect("the image is selected");
worker.post_key(&doc, 0, 1281).expect("escape");
let cleared = poll_until(&mut worker, &doc, &framed, SETTLE, |seen| {
seen.graphic.is_none()
});
click(&mut worker, &doc, x + w / 2, y + h / 2);
let picked = poll_until(&mut worker, &doc, &cleared, SETTLE, |seen| {
seen.graphic.is_some()
});
assert!(picked.graphic.is_some(), "the click selects the image");
pause(&mut worker, &doc);
run(&mut worker, &doc, "image.crop", &[]);
pause(&mut worker, &doc);
worker
.drag_graphic(&doc, (x + w, y + h), (x + w - w / 3, y + h - h / 3))
.expect("the handle drags");
let text = saved(&dir, &mut worker, &doc, "image.fodt");
assert_eq!(
text.matches("<draw:frame").count(),
1,
"the insert replaced it"
);
assert!(text.contains("style:wrap=\"run-through\""), "wrap lands");
assert!(
text.contains("text:anchor-type=\"paragraph\""),
"anchor lands"
);
assert!(
!text.contains("fo:clip=\"rect(0in, 0in, 0in, 0in)\""),
"the drag crops"
);
worker.post_key(&doc, 0, 1281).expect("escape");
click(&mut worker, &doc, 150, 150);
poll_until(&mut worker, &doc, &framed, SETTLE, |_| false);
run(&mut worker, &doc, "image.insert", &[&green]);
pause(&mut worker, &doc);
run(&mut worker, &doc, "image.wrap_through", &[]);
run(&mut worker, &doc, "image.back", &[]);
let text = saved(&dir, &mut worker, &doc, "stack.fodt");
let frames: Vec<&str> = text.split("<draw:frame").skip(1).collect();
assert_eq!(frames.len(), 2, "two images");
let back = frames
.iter()
.find(|frame| frame.contains("draw:z-index=\"0\""))
.expect("one at the back");
assert!(back.contains("Image2"), "the new image went back");
}
#[test]
fn the_remaining_layout_rows_reach_the_kernel() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
let (blue, green) = (
png(dir.path(), "blue.png", [0, 0, 255, 255]),
png(dir.path(), "green.png", [0, 255, 0, 255]),
);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "page.break", &[]);
run(&mut worker, &doc, "image.insert", &[&blue]);
pause(&mut worker, &doc);
for id in [
"image.anchor_page",
"image.anchor_char",
"image.wrap_off",
"image.wrap_on",
"image.wrap_ideal",
"image.wrap_left",
"image.wrap_right",
] {
run(&mut worker, &doc, id, &[]);
}
worker.post_key(&doc, 0, 1281).expect("escape");
click(&mut worker, &doc, 150, 150);
pause(&mut worker, &doc);
run(&mut worker, &doc, "image.insert", &[&green]);
pause(&mut worker, &doc);
run(&mut worker, &doc, "image.wrap_through", &[]);
for id in [
"image.backward",
"image.forward",
"image.back",
"image.front",
] {
run(&mut worker, &doc, id, &[]);
}
run(&mut worker, &doc, "image.anchor_as_char", &[]);
let text = saved(&dir, &mut worker, &doc, "rest.fodt");
assert!(
text.contains("fo:break-before=\"page\""),
"the page break lands"
);
assert_eq!(text.matches("<draw:frame").count(), 2, "both images stay");
assert!(
text.contains("text:anchor-type=\"as-char\""),
"as-char lands"
);
}
#[test]
fn turning_the_page_undoes_in_one_step() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(
&mut worker,
&doc,
"page.orientation",
&["27940", "21590", "true", "0", "4"],
);
let text = saved(&dir, &mut worker, &doc, "turned.fodt");
assert!(text.contains("fo:page-width=\"11in\" fo:page-height=\"8.5in\""));
assert!(text.contains("style:print-orientation=\"landscape\""));
run(&mut worker, &doc, "edit.undo", &[]);
let text = saved(&dir, &mut worker, &doc, "back.fodt");
assert!(
text.contains("fo:page-width=\"8.5in\" fo:page-height=\"11in\""),
"size back"
);
assert!(
text.contains("style:print-orientation=\"portrait\""),
"flag back"
);
}
#[test]
fn a_section_keeps_its_own_page_style() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 0, 1029).expect("end");
run(&mut worker, &doc, "style.new", &["Section 2", "8"]);
run(&mut worker, &doc, "page.section", &["3", "Section 2"]);
run(&mut worker, &doc, "page.columns", &["2"]);
run(&mut worker, &doc, "footer.on", &["true"]);
run(&mut worker, &doc, "footer.layout", &["2"]);
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
state(seen, ".uno:SwPageFooterLayout") == Some("2")
});
assert_eq!(state(&seen, ".uno:PageStyleName"), Some("Section 2"));
let text = saved(&dir, &mut worker, &doc, "section.fodt");
assert_eq!(
text.matches("fo:column-count=\"2\"").count(),
1,
"one section has columns"
);
let section = text
.split("style:display-name=\"Section 2\"")
.nth(1)
.and_then(|rest| rest.split("</style:master-page>").next())
.expect("the section's master page");
assert!(
section.contains("<style:footer-left>"),
"its footer differs on even pages"
);
let standard = text
.split("<style:master-page style:name=\"Standard\"")
.nth(1)
.and_then(|rest| rest.split("<style:master-page").next())
.expect("the first section's master page");
assert!(
!standard.contains("<style:footer"),
"the first section keeps no footer"
);
}
Binary file not shown.
+79
View File
@@ -0,0 +1,79 @@
use super::analysis::steps;
use super::show::open_deck;
use super::*;
use crate::show;
fn clip() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/media/clip.mp4")
}
fn media(worker: &mut Worker, doc: &Doc) -> Vec<show::Media> {
show::media(&worker.values(doc, show::MEDIA).expect("reads")).expect("parses")
}
fn insert(worker: &mut Worker, doc: &Doc, path: &std::path::Path, link: bool) -> io::Result<()> {
let url = crate::file_url(path);
worker.run(
doc,
"media.insert",
&[&url, &link.to_string(), "8000", "4500"],
)
}
#[test]
fn embedded_media_goes_in_mid_slide_and_survives_a_save() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let before = steps(&mut worker, &doc);
insert(&mut worker, &doc, &clip(), false).expect("inserts");
assert_eq!(steps(&mut worker, &doc), before + 1);
let list = media(&mut worker, &doc);
assert_eq!(list.len(), 1);
assert!(!list[0].link && !list[0].missing, "{:?}", list[0]);
assert!(
list[0].url.starts_with("vnd.sun.star.Package:"),
"{}",
list[0].url
);
let objects =
show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
let object = &objects.objects[list[0].index];
assert_eq!(object.kind, "media");
let out = dir.path().join("media.odp");
doc.save_as(&mut worker, &crate::file_url(&out), "odp")
.expect("saves");
let again = worker.load(&crate::file_url(&out)).expect("loads");
let list = media(&mut worker, &again);
assert_eq!(list.len(), 1);
assert!(
!list[0].link && !list[0].missing,
"the copy plays after a reload: {:?}",
list[0]
);
}
#[test]
fn a_linked_file_that_goes_away_reads_as_missing() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let copy = dir.path().join("linked.mp4");
std::fs::copy(clip(), &copy).expect("copies");
insert(&mut worker, &doc, &copy, true).expect("inserts");
let list = media(&mut worker, &doc);
assert!(list[0].link && !list[0].missing, "{:?}", list[0]);
std::fs::remove_file(&copy).expect("removes");
assert!(media(&mut worker, &doc)[0].missing);
let before = steps(&mut worker, &doc);
let gone = dir.path().join("never.mp4");
assert!(
insert(&mut worker, &doc, &gone, false).is_err(),
"nothing to embed"
);
assert_eq!(steps(&mut worker, &doc), before);
}
+222
View File
@@ -0,0 +1,222 @@
use super::analysis::steps;
use super::show::open_deck;
use super::*;
use crate::show::{self, Transition};
fn transition(worker: &mut Worker, doc: &Doc) -> Transition {
let read = worker.values(doc, show::TRANSITION).expect("reads");
show::transition(&read).expect("parses")
}
fn effects(worker: &mut Worker, doc: &Doc) -> Vec<show::Effect> {
let read = worker.values(doc, show::ANIMATIONS).expect("reads");
show::effects(&read).expect("parses")
}
fn fade() -> Transition {
Transition {
preset: "fade-smoothly".into(),
duration: 1.5,
auto: true,
time: 4.0,
}
}
#[test]
fn transitions_set_read_and_undo_as_one_step() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
assert_eq!(transition(&mut worker, &doc).preset, "");
let before = steps(&mut worker, &doc);
let json = show::transition_json(&fade(), false);
worker
.run(&doc, "slide.transition", &[&json])
.expect("sets");
assert_eq!(transition(&mut worker, &doc), fade());
assert_eq!(steps(&mut worker, &doc), before + 1);
worker.run(&doc, "edit.undo", &[]).expect("undoes");
assert_eq!(transition(&mut worker, &doc).preset, "");
// Every offered preset goes in and reads back.
for preset in show::TRANSITIONS {
let one = Transition {
preset: preset.into(),
..fade()
};
let json = show::transition_json(&one, false);
worker
.run(&doc, "slide.transition", &[&json])
.expect("sets");
assert_eq!(transition(&mut worker, &doc).preset, preset);
}
let push = Transition {
preset: "push-left".into(),
..fade()
};
let json = show::transition_json(&push, true);
worker
.run(&doc, "slide.transition", &[&json])
.expect("sets all");
doc.show_sheet(&mut worker, 1).expect("the second slide");
assert_eq!(transition(&mut worker, &doc).preset, "push-left");
let before = steps(&mut worker, &doc);
for bad in [
r#"{"preset":"no-such-thing"}"#,
r#"{"preset":"dissolve","duration":0}"#,
r#"{"preset":"dissolve","advance":"later"}"#,
r#"{"preset":"dissolve","duration":"2"}"#,
r#"{"preset":"dissolve","all":"yes"}"#,
] {
assert!(
worker.run(&doc, "slide.transition", &[bad]).is_err(),
"{bad}"
);
}
assert_eq!(steps(&mut worker, &doc), before);
}
#[test]
fn effects_add_change_move_and_go_as_single_steps() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker
.run(&doc, "draw.shape", &["rectangle", "true"])
.expect("draws");
let objects =
show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
let rect = objects
.objects
.iter()
.position(|o| o.selected)
.expect("the new shape");
let add = |worker: &mut Worker, preset: &str| {
let json = serde_json::json!({ "preset": preset }).to_string();
worker.run(&doc, "animation.add", &[&json]).expect("adds");
};
let before = steps(&mut worker, &doc);
add(&mut worker, "ooo-entrance-fade-in");
assert_eq!(steps(&mut worker, &doc), before + 1);
let list = effects(&mut worker, &doc);
assert_eq!(list.len(), 1);
let first = &list[0];
assert_eq!(
(
first.preset.as_str(),
first.class.as_str(),
first.target,
first.start.as_str()
),
("ooo-entrance-fade-in", "entrance", Some(rect), "click")
);
assert!(!first.hash.is_empty());
add(&mut worker, "ooo-entrance-fly-in");
let change = r#"{"index":1,"start":"after","duration":1.25,"delay":0.5}"#;
let before = steps(&mut worker, &doc);
worker
.run(&doc, "animation.change", &[change])
.expect("changes");
assert_eq!(steps(&mut worker, &doc), before + 1);
let second = effects(&mut worker, &doc)[1].clone();
assert_eq!(
(second.start.as_str(), second.duration, second.delay),
("after", 1.25, 0.5)
);
worker
.run(&doc, "animation.change", &[r#"{"index":1,"move":-1}"#])
.expect("moves");
let order: Vec<String> = effects(&mut worker, &doc)
.into_iter()
.map(|e| e.preset)
.collect();
assert_eq!(order, ["ooo-entrance-fly-in", "ooo-entrance-fade-in"]);
worker
.run(&doc, "animation.change", &[r#"{"index":0,"remove":true}"#])
.expect("removes");
assert_eq!(effects(&mut worker, &doc).len(), 1);
worker.run(&doc, "edit.undo", &[]).expect("undoes");
assert_eq!(
effects(&mut worker, &doc).len(),
2,
"the removal comes back"
);
// Every offered effect goes in.
for preset in show::EFFECTS {
add(&mut worker, preset);
assert_eq!(
effects(&mut worker, &doc).last().expect("one").preset,
preset
);
}
let before = steps(&mut worker, &doc);
for (id, bad) in [
("animation.add", r#"{"preset":"no-such-effect"}"#),
(
"animation.add",
r#"{"preset":"ooo-entrance-fade-in","duration":0}"#,
),
("animation.change", r#"{"index":99,"duration":1}"#),
("animation.change", r#"{"index":0,"start":"later"}"#),
("animation.change", r#"{"index":0,"move":-1}"#),
("animation.change", r#"{"index":0,"remove":"yes"}"#),
] {
assert!(worker.run(&doc, id, &[bad]).is_err(), "{bad}");
}
assert_eq!(steps(&mut worker, &doc), before);
}
#[test]
fn an_animated_object_is_its_own_layer_under_its_effect_hash() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker
.run(&doc, "draw.shape", &["rectangle", "true"])
.expect("draws");
let json = serde_json::json!({ "preset": "ooo-entrance-fade-in" }).to_string();
worker.run(&doc, "animation.add", &[&json]).expect("adds");
let hash = effects(&mut worker, &doc)[0].hash.clone();
let layers = doc
.slide_layers(&mut worker, 0, (480, 270))
.expect("layers");
assert_eq!(layers.size, (480, 270));
let moving: Vec<(&str, bool, i64)> = (layers.list.iter())
.filter_map(|layer| match &layer.part {
show::Part::Moving {
hash,
visible,
bounds,
} => Some((hash.as_str(), *visible, bounds.2)),
_ => None,
})
.collect();
assert_eq!(moving.len(), 1);
assert_eq!(
(moving[0].0, moving[0].1),
(hash.as_str(), false),
"an entrance starts hidden"
);
assert!(moving[0].2 > 0, "it has a width");
let still = layers
.list
.iter()
.filter(|l| l.part == show::Part::Still)
.count();
assert!(still >= 2, "background and the rest");
let bytes = 480 * 270 * 4;
assert!(
layers
.list
.iter()
.all(|l| l.pixels.len() == bytes)
);
}
+194
View File
@@ -0,0 +1,194 @@
use super::input::open;
use super::*;
use crate::review;
/// Three pages, two headings, fonts the system lacks.
const LONG: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:font-face-decls><style:font-face style:name="Nowhere Sans" svg:font-family="&apos;Nowhere Sans&apos;" style:font-family-generic="swiss"/><style:font-face style:name="Nowhere Pair" svg:font-family="&apos;Nowhere Sans;Nowhere Serif&apos;"/></office:font-face-decls>
<office:automatic-styles>
<style:style style:name="P1" style:family="paragraph"><style:paragraph-properties fo:break-before="page"/></style:style>
<style:style style:name="T1" style:family="text"><style:text-properties style:font-name="Nowhere Sans"/></style:style>
<style:style style:name="T2" style:family="text"><style:text-properties style:font-name="Nowhere Pair"/></style:style>
</office:automatic-styles>
<office:body><office:text>
<text:h text:outline-level="1">First part</text:h><text:p>alpha <text:span text:style-name="T1">odd font</text:span> <text:span text:style-name="T2">pair</text:span></text:p>
<text:h text:style-name="P1" text:outline-level="2">Second part</text:h><text:p>bravo</text:p>
<text:p text:style-name="P1">charlie</text:p>
</office:text></office:body>
</office:document>"#;
/// The text of a PDF, if pdftotext is present.
pub(super) fn pdf_text(path: &std::path::Path) -> Option<String> {
let out = std::process::Command::new("pdftotext")
.arg(path)
.arg("-")
.output()
.ok()?;
assert!(out.status.success(), "pdftotext reads {}", path.display());
Some(String::from_utf8_lossy(&out.stdout).into_owned())
}
#[test]
fn a_locked_document_asks_for_its_password() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker =
Worker::spawn(&install().expect("lok"), &dir.path().join("profile")).expect("the worker");
let locked =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/client/tests/locked.odt");
let url = crate::file_url(&locked);
for password in ["", "wrong"] {
let error = worker
.unlock(&url, password)
.err()
.expect("a locked load fails");
assert_eq!(
error.kind(),
std::io::ErrorKind::PermissionDenied,
"{password}: {error}"
);
}
let doc = worker
.unlock(&url, "secret")
.expect("the right password opens it");
let out = dir.path().join("open.fodt");
doc.save_as(&mut worker, &crate::file_url(&out), "fodt")
.expect("saves");
assert!(
std::fs::read_to_string(&out)
.expect("reads")
.contains("Teh cat")
);
}
#[test]
fn pdfs_take_pages_and_the_outline_has_places() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(LONG);
let seen = poll_until(
&mut worker,
&doc,
&Events::default(),
std::time::Duration::from_secs(5),
|seen| !seen.fonts.is_empty(),
);
let mut fonts = seen.fonts.clone();
fonts.sort();
assert_eq!(
fonts,
["Nowhere Sans", "Nowhere Sans;Nowhere Serif"],
"a declared list is named too"
);
let outline = review::outline(&worker.values(&doc, ".uno:Outline").expect("the outline"))
.expect("the outline parses");
let texts: Vec<_> = outline
.iter()
.map(|heading| (heading.text.as_str(), heading.level))
.collect();
assert_eq!(texts, [("First part", 0), ("Second part", 1)]);
assert!(
outline[0].current && !outline[1].current,
"the cursor sits under the first"
);
assert!(
outline[1].rect.1 > outline[0].rect.1,
"the second heading sits lower"
);
let pdf = dir.path().join("two.pdf");
let only_two = crate::Pdf {
pages: Some((2, 2)),
..crate::Pdf::default()
};
doc.export_pdf(&mut worker, &crate::file_url(&pdf), &only_two)
.expect("the export works");
let backwards = crate::Pdf {
pages: Some((3, 2)),
..crate::Pdf::default()
};
assert!(
doc.export_pdf(&mut worker, &crate::file_url(&pdf), &backwards)
.is_err()
);
let Some(text) = pdf_text(&pdf) else {
eprintln!("SKIP: no pdftotext to read the PDF");
return;
};
assert!(
text.contains("bravo") && !text.contains("alpha") && !text.contains("charlie"),
"{text}"
);
}
#[test]
fn comments_and_changes_print_as_chosen() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "comment.insert", &["Marginal"])
.expect("a comment");
worker.run(&doc, "track.toggle", &[]).expect("tracking");
for _ in 0.."Hello".len() {
worker.post_key(&doc, 0, 1286).expect("delete");
}
let mut texts = Vec::new();
for (n, (comments, changes)) in [(false, false), (true, true)].into_iter().enumerate() {
let pdf = dir.path().join(format!("{n}.pdf"));
let options = crate::Pdf {
pages: None,
comments,
changes,
handouts: 0,
};
doc.export_pdf(&mut worker, &crate::file_url(&pdf), &options)
.expect("the export works");
let Some(text) = pdf_text(&pdf) else {
eprintln!("SKIP: no pdftotext to read the PDF");
return;
};
texts.push(text);
}
assert!(
!texts[0].contains("Marginal"),
"comments stay out: {}",
texts[0]
);
assert!(
texts[1].contains("Marginal"),
"comments go in the margin: {}",
texts[1]
);
assert!(
!texts[0].contains("Hello"),
"the final text drops the deletion"
);
assert!(texts[1].contains("Hello"), "marked changes keep it");
}
#[test]
fn a_bookmark_knows_its_place() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open(LONG);
let pages = doc.pages(&mut worker).expect("pages");
click(&mut worker, &doc, pages[2].0 + 1500, pages[2].1 + 1500);
worker
.run(&doc, "bookmark.insert", &["Far"])
.expect("a mark");
let marks = review::bookmarks(&worker.values(&doc, ".uno:Bookmarks").expect("the marks"))
.expect("the marks parse");
let place = marks[0].rect.expect("the mark has a place");
assert!(place.1 > pages[2].1, "the mark sits on page three");
}
+385
View File
@@ -0,0 +1,385 @@
use super::*;
/// How long an edit may take to show.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
/// How long a quiet document is watched.
const QUIET: std::time::Duration = std::time::Duration::from_millis(600);
#[test]
fn a_tile_paints_real_pixels() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let tile = doc
.paint_tile(&mut worker, (0, 0, 960, 960), (64, 64))
.expect("the tile paints");
assert_eq!(tile.pixels.len(), 64 * 64 * 4, "a 64x64 BGRA tile");
let ink = |px: &[u8]| u32::from(px[0]) + u32::from(px[1]) + u32::from(px[2]);
let dark = tile
.pixels
.chunks_exact(4)
.filter(|px| ink(px) < 720)
.count();
let light = tile
.pixels
.chunks_exact(4)
.filter(|px| ink(px) > 720)
.count();
assert!(
dark > 0 && light > 0,
"a text tile has dark and light pixels: {dark}/{light}"
);
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn an_edit_bumps_the_generation_and_invalidates() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
let before = doc
.paint_tile(&mut worker, (0, 960, 4000, 2000), (64, 64))
.expect("the tile paints");
assert_eq!(before.generation, base.generation, "idle: no bump");
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 0, 1280).expect("Return posts");
let batch = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.generation > base.generation
});
assert!(
batch.generation > before.generation,
"the edit bumps the generation: {} -to {}",
before.generation,
batch.generation
);
assert!(
!batch.all && !batch.rects.is_empty(),
"the edit invalidates precisely: {batch:?}"
);
let after = doc
.paint_tile(&mut worker, (0, 960, 4000, 2000), (64, 64))
.expect("the tile repaints");
assert!(
after.generation >= batch.generation,
"a fresh tile matches the new generation"
);
assert_ne!(before.pixels, after.pixels, "the edit changes the picture");
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn uno_commands_invalidate_and_repaint() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
let before = doc
.paint_tile(&mut worker, (0, 960, 4000, 2000), (64, 64))
.expect("the tile paints");
click(&mut worker, &doc, 150, 150);
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
worker.cut(&doc).expect("the cut runs");
let batch = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.generation > base.generation
});
assert!(
batch.generation > base.generation,
"a deleting command bumps the generation"
);
let after = doc
.paint_tile(&mut worker, (0, 960, 4000, 2000), (64, 64))
.expect("the tile repaints");
assert_ne!(
before.pixels, after.pixels,
"the delete changes the picture"
);
worker.close_doc(doc).expect("the document closes");
}
const RED_HTML: &str =
"<html><body><p><span style=\"color:#FF0000\">red red red red</span></p></body></html>";
#[test]
fn a_red_span_paints_red_bytes() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("red.html");
write(&source, RED_HTML);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let tile = doc
.paint_tile(&mut worker, (0, 0, 2000, 1000), (64, 64))
.expect("the tile paints");
let red = tile
.pixels
.chunks_exact(4)
.filter(|px| px[2] > 200 && px[0] < 80 && px[1] < 80)
.count();
assert!(red > 0, "BGRA red bytes paint red: {red}");
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn a_key_press_edits_the_document() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 0, 1280).expect("Return posts");
let out = dir.path().join("after.fodt");
doc.save_as(&mut worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
let before = std::fs::read_to_string(&source).expect("the source reads");
let after = std::fs::read_to_string(&out).expect("the save reads");
let count = |text: &str| text.matches("<text:p").count();
assert_eq!(count(&before) + 1, count(&after), "Return adds a paragraph");
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn selection_only_requests_keep_the_generation() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
click(&mut worker, &doc, 150, 150);
worker.post_key(&doc, 0, 1027).expect("Right posts");
let quiet = poll_until(&mut worker, &doc, &base, QUIET, |_| false);
assert_eq!(
quiet.generation, base.generation,
"selection moves stay quiet"
);
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn bad_tile_geometry_is_an_error_and_the_worker_lives() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
for (x, y, w, h, pw, ph) in [
(0, 0, 0, 960, 64, 64),
(0, 0, -15, 960, 64, 64),
(0, 0, 960, 960, 0, 64),
(0, 0, 960, 960, 100_000, 100_000),
] {
assert!(
doc.paint_tile(&mut worker, (x, y, w, h), (pw, ph)).is_err(),
"geometry {x},{y},{w},{h},{pw},{ph} is refused"
);
}
let (width, height) = doc.size(&mut worker).expect("the worker still answers");
assert!(
width > 0 && height > 0,
"the document outlives bad requests"
);
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn a_long_wait_is_clamped_and_requests_flow() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let started = std::time::Instant::now();
let batch = worker
.poll_events(&doc, u64::MAX, u64::MAX)
.expect("the long wait returns");
assert_eq!(batch.generation, 0, "nothing to drain");
assert!(
started.elapsed() < std::time::Duration::from_secs(4),
"the wait is clamped"
);
worker.post_key(&doc, 0, 1027).expect("Right posts");
worker.close_doc(doc).expect("the document closes");
worker.shutdown().expect("the worker shuts down");
}
#[test]
fn polling_times_out_with_the_same_generation() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
let again = poll_until(&mut worker, &doc, &base, QUIET, |_| false);
assert_eq!(again.generation, base.generation, "no edit, no bump");
assert!(again.rects.is_empty() && !again.all, "nothing invalidated");
worker.close_doc(doc).expect("the document closes");
}
#[test]
fn uno_commands_reach_their_own_document() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let (first, second) = (dir.path().join("a.fodt"), dir.path().join("b.fodt"));
write(&first, FODT);
write(&second, FODT);
let a = worker
.load(&format!("file://{}", first.display()))
.expect("a loads");
let b = worker
.load(&format!("file://{}", second.display()))
.expect("b loads");
worker.run(&a, "edit.select_all", &[]).expect("select all");
worker.cut(&a).expect("the cut runs");
let saved = |doc: &Doc, worker: &mut Worker, name: &str| {
let out = dir.path().join(name);
doc.save_as(worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
std::fs::read_to_string(&out).expect("the save reads")
};
assert!(
!saved(&a, &mut worker, "a-out.fodt").contains("Hello"),
"a lost its text"
);
assert!(
saved(&b, &mut worker, "b-out.fodt").contains("Hello"),
"b kept its text"
);
worker.close_doc(b).expect("b closes");
worker.close_doc(a).expect("a closes");
}
#[test]
fn writer_reports_its_page_rects() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("note.fodt");
write(&source, FODT);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let pages = doc.pages(&mut worker).expect("the page rects");
let (width, height) = doc.size(&mut worker).expect("the size");
assert_eq!(pages.len(), 1, "one page: {pages:?}");
let (x, y, w, h) = pages[0];
assert!(
x > 0 && y > 0 && x + w < width as i32 && y + h <= height as i32,
"inside the document: {pages:?}"
);
}
/// A tile's mean channel value, 0 to 255.
fn brightness(tile: &Tile) -> u32 {
let sum: u64 = tile
.pixels
.chunks_exact(4)
.map(|px| u64::from(px[0]) + u64::from(px[1]) + u64::from(px[2]))
.sum();
(sum / (tile.pixels.len() as u64 / 4 * 3)) as u32
}
#[test]
fn the_page_follows_a_dark_theme_and_back() {
let Some(install) = install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
for (name, text) in [("note.fodt", FODT), ("book.fods", super::input::FODS)] {
let source = dir.path().join(name);
write(&source, text);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
let area = (1440, 1440, 3840, 3840);
let seen = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
let light = brightness(&doc.paint_tile(&mut worker, area, (64, 64)).expect("a tile"));
let paint = |worker: &mut Worker, scheme: &str, seen: &Events| {
worker.run(&doc, "view.theme", &[scheme]).expect("a theme");
let repainted = poll_until(worker, &doc, seen, SETTLE, |seen| seen.all);
assert!(repainted.all, "{name}: {scheme} repaints the view");
let tile = doc.paint_tile(worker, area, (64, 64)).expect("a tile");
(brightness(&tile), repainted)
};
let (dark, seen) = paint(&mut worker, "COLOR_SCHEME_ELY_DARK", &seen);
let (back, _) = paint(&mut worker, "COLOR_SCHEME_ELY_LIGHT", &seen);
eprintln!("THEME {name} light {light} dark {dark} back {back}");
assert!(
light > 200 && dark < 100 && back > 200,
"{name}: {light} {dark} {back}"
);
worker.close_doc(doc).expect("the document closes");
}
}
+128
View File
@@ -0,0 +1,128 @@
use super::*;
use crate::show;
/// Footer and number on; slide three hidden.
const FIELDS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"
xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.presentation">
<office:automatic-styles>
<style:style style:name="dp1" style:family="drawing-page">
<style:drawing-page-properties presentation:display-footer="true" presentation:display-page-number="true" presentation:display-date-time="false"/>
</style:style>
<style:style style:name="dp2" style:family="drawing-page">
<style:drawing-page-properties presentation:visibility="hidden"/>
</style:style>
</office:automatic-styles>
<office:master-styles>
<style:master-page style:name="Plain">
<draw:frame presentation:class="footer" svg:x="1cm" svg:y="13.5cm" svg:width="10cm" svg:height="1.5cm"><draw:text-box><text:p><presentation:footer/></text:p></draw:text-box></draw:frame>
<draw:frame presentation:class="page-number" svg:x="20cm" svg:y="13.5cm" svg:width="6cm" svg:height="1.5cm"><draw:text-box><text:p><text:page-number>&lt;number&gt;</text:page-number></text:p></draw:text-box></draw:frame>
</style:master-page>
</office:master-styles>
<office:body><office:presentation>
<presentation:footer-decl presentation:name="ftr1">Ely footer</presentation:footer-decl>
<draw:page draw:name="One" draw:style-name="dp1" draw:master-page-name="Plain" presentation:use-footer-name="ftr1"/>
<draw:page draw:name="Two" draw:style-name="dp1" draw:master-page-name="Plain" presentation:use-footer-name="ftr1"/>
<draw:page draw:name="Three" draw:style-name="dp2" draw:master-page-name="Plain"/>
</office:presentation></office:body>
</office:document>"#;
fn open_fields() -> (tempfile::TempDir, Worker, Doc) {
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let path = dir.path().join("fields.fodp");
std::fs::write(&path, FIELDS).expect("writes");
let doc = worker.load(&crate::file_url(&path)).expect("loads");
(dir, worker, doc)
}
#[test]
fn the_show_reads_every_slide_with_notes_and_hidden() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_fields();
let now = worker.now(&doc).expect("the state");
worker.run(&now, "notes.set", &["Say hello", "1"]).expect("sets");
let json = worker.values(&doc, show::SLIDE_SHOW).expect("reads");
let slides = show::slide_show(&json).expect("parses");
let seen: Vec<(bool, &str)> = slides.iter().map(|s| (s.hidden, s.notes.as_str())).collect();
assert_eq!(seen, [(false, ""), (false, "Say hello"), (true, "")]);
assert!(slides.iter().all(|s| s.effects.is_empty() && s.media.is_empty()));
assert_eq!(slides[0].transition.preset, "");
}
#[test]
fn field_text_lands_where_its_placeholder_is() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_fields();
// Rows with ink, not white, per layer.
let inked_rows = |part: usize, worker: &mut Worker| {
let layers = doc.slide_layers(worker, part, (480, 270)).expect("layers");
assert!(layers.list.iter().all(|l| l.part == show::Part::Still));
(layers.list.iter())
.map(|layer| {
(0..270)
.filter(|y| {
(0..480).any(|x| {
let at = (y * 480 + x) * 4;
layer.pixels[at + 3] > 0 && layer.pixels[at..at + 3] != [255, 255, 255]
})
})
.collect::<Vec<usize>>()
})
.collect::<Vec<_>>()
};
let shown = inked_rows(1, &mut worker);
assert_eq!(shown.len(), 3, "background, then footer and number");
assert!(
shown[1..].iter().all(|rows| !rows.is_empty() && rows.iter().all(|y| *y > 230)),
"both sit at the bottom: {shown:?}"
);
assert_eq!(inked_rows(2, &mut worker).len(), 1, "fields off, none drawn");
}
#[test]
fn a_pptx_keeps_notes_motion_and_media_editable() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = super::show::open_deck();
let fade = r#"{"preset":"fade-smoothly","duration":1.5,"advance":"click","time":0,"all":false}"#;
worker.run(&doc, "slide.transition", &[fade]).expect("a transition");
worker.run(&doc, "draw.shape", &["rectangle", "true"]).expect("a shape");
let add = serde_json::json!({ "preset": "ooo-entrance-fly-in" }).to_string();
worker.run(&doc, "animation.add", &[&add]).expect("an effect");
let now = worker.now(&doc).expect("the state");
worker.run(&now, "notes.set", &["Speak slowly", "0"]).expect("notes");
let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/media/clip.mp4");
let url = crate::file_url(&clip);
worker.run(&doc, "media.insert", &[&url, "false", "8000", "4500"]).expect("media");
let out = dir.path().join("kept.pptx");
doc.save_as(&mut worker, &crate::file_url(&out), "pptx").expect("saves");
let again = worker.load(&crate::file_url(&out)).expect("loads");
let slides = show::slide_show(&worker.values(&again, show::SLIDE_SHOW).expect("reads")).expect("parses");
let first = &slides[0];
assert_eq!((first.transition.preset.as_str(), first.notes.as_str()), ("fade-smoothly", "Speak slowly"));
assert_eq!(first.effects.iter().map(|e| e.preset.as_str()).collect::<Vec<_>>(), ["ooo-entrance-fly-in"]);
assert_eq!(first.media.len(), 1);
assert!(!first.media[0].missing, "{:?}", first.media[0]);
// Still editable: effect and notes change.
let change = serde_json::json!({ "index": 0, "duration": 3.0 }).to_string();
worker.run(&again, "animation.change", &[&change]).expect("changes");
let now = worker.now(&again).expect("the state");
worker.run(&now, "notes.set", &["Louder", "0"]).expect("edits notes");
let slides = show::slide_show(&worker.values(&again, show::SLIDE_SHOW).expect("reads")).expect("parses");
assert_eq!((slides[0].effects[0].duration, slides[0].notes.as_str()), (3.0, "Louder"));
}
+348
View File
@@ -0,0 +1,348 @@
use super::analysis::{cells, skip, steps};
use super::rules::row;
use super::sheet::open_book;
use super::*;
use crate::sheet::{
self, Scale,
csv::{Column, Encoding, Import},
};
/// Two sheets: S1 heads a sum, S2 holds a list.
fn book() -> String {
let first = [row(&["Name", "Total"]), row(&["Sum"])].concat();
let second: String = [["Item", "Note"], ["Pen", "a;b"], ["Ink", "2"]]
.iter()
.map(|cells| row(cells))
.collect();
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet>
<table:table table:name="S1">{first}</table:table>
<table:table table:name="S2">{second}</table:table>
</office:spreadsheet></office:body>
</office:document>"#
)
}
fn import(dir: &Path, worker: &mut Worker, bytes: &[u8], how: &Import) -> Doc {
import_as("in.csv", dir, worker, bytes, how)
}
fn import_as(name: &str, dir: &Path, worker: &mut Worker, bytes: &[u8], how: &Import) -> Doc {
let path = dir.join(name);
std::fs::write(&path, bytes).expect("writes");
worker
.import(&crate::file_url(&path), how)
.expect("imports")
}
fn flat(worker: &mut Worker, doc: &Doc, dir: &Path) -> String {
let out = dir.join("out.fods");
doc.save_as(worker, &crate::file_url(&out), "fods")
.expect("saves");
std::fs::read_to_string(out).expect("reads")
}
#[test]
fn csv_imports_keep_codes_and_leave_formulas_as_text() {
if skip() {
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let text = "Account,Code,Amount,Formula,When\n00123,12345678901234567890,1.5,=1+1,2026-03-04\n";
let how = Import {
separator: ',',
quote: Some('"'),
encoding: Encoding::Utf8,
columns: vec![
Column::Text,
Column::Text,
Column::Standard,
Column::Standard,
Column::DateYmd,
],
};
let doc = import(dir.path(), &mut worker, text.as_bytes(), &how);
let xml = flat(&mut worker, &doc, dir.path());
assert!(xml.contains("<text:p>00123</text:p>"), "the zero stays");
assert!(
xml.contains("<text:p>12345678901234567890</text:p>"),
"the long code stays text"
);
assert!(
xml.contains(r#"office:value="1.5""#),
"the amount is a number"
);
assert!(!xml.contains("table:formula"), "no text ran as a formula");
assert!(
xml.contains("<text:p>=1+1</text:p>"),
"the formula text stays"
);
assert!(
xml.contains(r#"office:date-value="2026-03-04""#),
"the date column reads year first"
);
}
#[test]
fn csv_imports_take_the_encoding_separator_and_quote() {
if skip() {
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
// 名称<TAB>值 / '苹果<TAB>x'<TAB>3 in GB18030.
let mut bytes = vec![0xC3, 0xFB, 0xB3, 0xC6, b'\t', 0xD6, 0xB5, b'\n', b'\''];
bytes.extend([0xC6, 0xBB, 0xB9, 0xFB]);
bytes.extend(b"\tx'\t3\n");
let how = Import {
separator: '\t',
quote: Some('\''),
encoding: Encoding::Gb18030,
columns: Vec::new(),
};
let doc = import(dir.path(), &mut worker, &bytes, &how);
let xml = flat(&mut worker, &doc, dir.path());
assert!(xml.contains("<text:p>名称</text:p>") && xml.contains("<text:p>值</text:p>"));
assert!(
xml.contains("<text:p>苹果<text:tab/>x</text:p>"),
"the quote holds the tab"
);
assert!(xml.contains(r#"office:value="3""#), "the number reads");
}
#[test]
fn a_txt_file_imports_as_a_sheet() {
if skip() {
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let how = Import {
separator: ',',
quote: Some('"'),
encoding: Encoding::Utf8,
columns: vec![Column::Text],
};
let doc = import_as(
"notes.txt",
dir.path(),
&mut worker,
b"Account,Value\n00123,1.5\n",
&how,
);
assert_eq!(
doc.sheets(&mut worker).expect("sheets").list.len(),
1,
"a sheet, not a page"
);
assert_eq!(cells(&mut worker, &doc, "A2"), "00123");
}
#[test]
fn text_exports_write_the_shown_sheet_as_values() {
if skip() {
return;
}
let (dir, mut worker, doc) = open_book(&book());
worker.run(&doc, "cell.goto", &["B2"]).expect("B2");
worker.run(&doc, "cell.enter", &["=1+2"]).expect("the sum");
let out = dir.path().join("out.csv");
doc.export_text(&mut worker, &crate::file_url(&out), ';')
.expect("exports S1");
let first = std::fs::read_to_string(&out).expect("reads");
assert_eq!(first, "Name;Total\nSum;3\n", "values, not formulas");
doc.show_sheet(&mut worker, 1).expect("S2");
doc.export_text(&mut worker, &crate::file_url(&out), ';')
.expect("exports S2");
let second = std::fs::read_to_string(&out).expect("reads");
assert_eq!(second, "Item;Note\nPen;\"a;b\"\nInk;2\n", "only S2");
}
fn layout(worker: &mut Worker, doc: &Doc) -> sheet::PrintLayout {
let json = worker.values(doc, sheet::LAYOUT).expect("the layout");
sheet::print_layout(&json).expect("parses")
}
#[test]
fn print_layouts_set_areas_titles_page_and_breaks() {
if skip() {
return;
}
let (dir, mut worker, doc) = open_book(&book());
let fresh = layout(&mut worker, &doc);
assert_eq!(fresh.areas, Vec::<String>::new());
assert_eq!(fresh.scale, Scale::Percent(100));
assert_eq!(fresh.sheets, ["S1", "S2"], "one page style");
let before = steps(&mut worker, &doc);
worker
.run(&doc, "print.area", &["$A$1:$B$2", "$1:$1", "$A:$A"])
.expect("sets the area");
let page = sheet::page_json(true, Scale::Fit(1, 0));
worker
.run(&doc, "page.setup", &[&page])
.expect("sets the page");
assert_eq!(steps(&mut worker, &doc), before + 2, "two undo steps");
let set = layout(&mut worker, &doc);
assert_eq!(set.areas, ["$A$1:$B$2"]);
assert_eq!((set.rows, set.columns), (Some((1, 1)), Some((1, 1))));
assert_eq!((set.landscape, set.scale), (true, Scale::Fit(1, 0)));
let wide = sheet::page_json(true, Scale::Percent(500));
assert!(
worker.run(&doc, "page.setup", &[&wide]).is_err(),
"500% is refused"
);
worker.run(&doc, "cell.goto", &["B3"]).expect("B3");
worker.run(&doc, "break.row", &[]).expect("a row break");
assert!(layout(&mut worker, &doc).row_break);
worker.run(&doc, "break.row_remove", &[]).expect("removed");
assert!(!layout(&mut worker, &doc).row_break);
let xlsx = dir.path().join("out.xlsx");
doc.save_as(&mut worker, &crate::file_url(&xlsx), "xlsx")
.expect("saves");
let again = worker.load(&crate::file_url(&xlsx)).expect("reloads");
let kept = layout(&mut worker, &again);
assert_eq!(kept.areas, ["$A$1:$B$2"], "the area survives XLSX");
assert_eq!((kept.rows, kept.columns), (Some((1, 1)), Some((1, 1))));
assert_eq!((kept.landscape, kept.scale), (true, Scale::Fit(1, 0)));
}
fn protection(worker: &mut Worker, doc: &Doc) -> sheet::Protection {
let json = worker
.values(doc, sheet::PROTECTION)
.expect("the protection");
sheet::protection(&json).expect("parses")
}
#[test]
fn protection_guards_locked_cells_and_keeps_its_password() {
if skip() {
return;
}
let (_dir, mut worker, doc) = open_book(&book());
worker.run(&doc, "cell.goto", &["B1"]).expect("B1");
worker
.run(&doc, "cells.lock", &["false"])
.expect("unlocks B1");
let allow = vec!["selectLocked".to_string(), "selectUnlocked".to_string()];
let on = sheet::protect_json("pw", &allow);
worker.run(&doc, "sheet.protect", &[&on]).expect("protects");
let read = protection(&mut worker, &doc);
assert!(read.protected && read.password);
assert_eq!(read.allow, allow);
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
let _ = worker.run(&doc, "cell.enter", &["x"]);
assert_eq!(cells(&mut worker, &doc, "A1"), "Name", "A1 is locked");
worker.run(&doc, "cell.goto", &["B1"]).expect("B1");
worker
.run(&doc, "cell.enter", &["y"])
.expect("B1 takes text");
assert_eq!(cells(&mut worker, &doc, "B1"), "y");
let wrong = sheet::unprotect_json("nope");
assert!(worker.run(&doc, "sheet.protect", &[&wrong]).is_err());
assert!(protection(&mut worker, &doc).protected, "still protected");
let right = sheet::unprotect_json("pw");
worker
.run(&doc, "sheet.protect", &[&right])
.expect("unprotects");
assert!(!protection(&mut worker, &doc).protected);
}
/// A cell's formula and value in an OOXML sheet.
fn ooxml_cell(column: &str, formula: &str, value: &str) -> String {
format!(r#"<c r="{column}1"><f>{formula}</f><v>{value}</v></c>"#)
}
#[test]
fn excel_caches_recompute_and_unknown_functions_show_errors() {
if skip() {
return;
}
let (dir, mut worker, doc) = open_book(&book());
let xlsx = dir.path().join("saved.xlsx");
doc.save_as(&mut worker, &crate::file_url(&xlsx), "xlsx")
.expect("saves");
let unpacked = dir.path().join("x");
let unzip = std::process::Command::new("unzip")
.args(["-q", "-o"])
.arg(&xlsx)
.arg("-d")
.arg(&unpacked)
.status()
.expect("unzip runs");
assert!(unzip.success());
// Excel caches: an unknown function's and a stale one.
let sheet = unpacked.join("xl/worksheets/sheet1.xml");
let xml = std::fs::read_to_string(&sheet).expect("the sheet");
let at = xml.find("<sheetData>").expect("sheet data") + "<sheetData>".len();
let both = ooxml_cell("A", "FUTUREFN(1)", "42") + &ooxml_cell("B", "1+1", "7");
let row = format!(r#"<row r="1">{both}</row>"#);
let end = xml[at..].find("</row>").expect("row one") + at + "</row>".len();
std::fs::write(&sheet, format!("{}{row}{}", &xml[..at], &xml[end..])).expect("writes");
let excel = dir.path().join("excel.xlsx");
let zip = std::process::Command::new("zip")
.current_dir(&unpacked)
.args(["-q", "-r"])
.arg(&excel)
.arg(".")
.status()
.expect("zip runs");
assert!(zip.success());
let opened = worker.load(&crate::file_url(&excel)).expect("loads");
assert_eq!(
cells(&mut worker, &opened, "A1"),
"#NAME?",
"no fake result"
);
assert_eq!(
cells(&mut worker, &opened, "B1"),
"2",
"a stale cache recomputes"
);
let again = dir.path().join("again.fods");
opened
.save_as(&mut worker, &crate::file_url(&again), "fods")
.expect("saves");
let kept = std::fs::read_to_string(again).expect("reads");
assert!(kept.contains("of:=futurefn(1)"), "the formula stays");
}
#[test]
fn linked_values_stay_as_saved_and_are_named() {
if skip() {
return;
}
let (dir, mut worker, doc) = open_book(&book());
let source = dir.path().join("source.ods");
doc.save_as(&mut worker, &crate::file_url(&source), "ods")
.expect("saves the source");
let reader = worker
.load(&crate::file_url(&dir.path().join("book.fods")))
.expect("a second copy");
let formula = format!("='{}/[source.ods]S1'!A1", dir.path().display());
worker.run(&reader, "cell.goto", &["D1"]).expect("D1");
worker
.run(&reader, "cell.enter", &[&formula])
.expect("the link");
assert_eq!(cells(&mut worker, &reader, "D1"), "Name");
let saved = dir.path().join("reader.xlsx");
reader
.save_as(&mut worker, &crate::file_url(&saved), "xlsx")
.expect("saves");
std::fs::remove_file(&source).expect("the source goes");
let offline = worker.load(&crate::file_url(&saved)).expect("reloads");
assert_eq!(
cells(&mut worker, &offline, "D1"),
"Name",
"the old value stays"
);
let links =
sheet::links(&worker.values(&offline, sheet::LINKS).expect("reads")).expect("parses");
assert_eq!(links, [crate::file_url(&source)], "the source is named");
let plain = sheet::links(&worker.values(&doc, sheet::LINKS).expect("reads")).expect("parses");
assert!(plain.is_empty());
}
+281
View File
@@ -0,0 +1,281 @@
use super::input::{open, saved};
use super::*;
use crate::review;
fn run(worker: &mut Worker, doc: &Doc, id: &str, values: &[&str]) {
worker
.run(doc, id, values)
.unwrap_or_else(|error| panic!("{id}: {error}"));
}
fn values(worker: &mut Worker, doc: &Doc, command: &str) -> String {
worker
.values(doc, command)
.unwrap_or_else(|error| panic!("{command}: {error}"))
}
fn type_in(worker: &mut Worker, doc: &Doc, text: &str) {
for key in text.chars() {
worker.post_key(doc, key as u32, 0).expect("a key");
}
}
/// Reads until `done`: the kernel lists comments after layout.
fn awaited<T>(mut read: impl FnMut() -> T, done: impl Fn(&T) -> bool) -> T {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let value = read();
if done(&value) || std::time::Instant::now() > deadline {
return value;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
#[test]
fn references_land() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(
&mut worker,
&doc,
"format.style",
&["Heading 1", "ParagraphStyles"],
);
run(&mut worker, &doc, "bookmark.insert", &["Start"]);
let marks = review::bookmarks(&values(&mut worker, &doc, ".uno:Bookmarks"))
.expect("the bookmarks parse");
assert_eq!(marks.len(), 1);
assert_eq!(marks[0].name, "Start");
assert!(marks[0].rect.is_some(), "the mark has a place");
run(
&mut worker,
&doc,
"reference.insert",
&["13", "2", "Start", "2"],
);
run(
&mut worker,
&doc,
"link.insert",
&["Ely", "https://example.org/"],
);
run(&mut worker, &doc, "note.footnote", &[]);
type_in(&mut worker, &doc, "Foot");
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "note.endnote", &[]);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "index.insert", &["Contents"]);
run(&mut worker, &doc, "index.update", &[]);
let text = saved(&dir, &mut worker, &doc, "refs.fodt");
for mark in [
"<text:table-of-content ",
">Contents<",
"<text:note text:id=\"ftn",
"text:note-class=\"endnote\"",
"<text:bookmark text:name=\"Start\"",
"<text:bookmark-ref ",
"xlink:href=\"https://example.org/\"",
] {
assert!(text.contains(mark), "{mark} lands");
}
}
#[test]
fn formulas_insert_edit_and_take_captions() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
let formula = |worker: &mut Worker| {
review::formula(&values(worker, &doc, ".uno:Formula")).expect("the formula parses")
};
assert_eq!(formula(&mut worker), None, "no formula yet");
run(&mut worker, &doc, "formula.insert", &["a over b"]);
assert_eq!(formula(&mut worker).as_deref(), Some("a over b"));
run(&mut worker, &doc, "formula.insert", &["c over d"]);
assert_eq!(formula(&mut worker).as_deref(), Some("c over d"));
run(&mut worker, &doc, "caption.insert", &["Figure", "ratio"]);
let text = saved(&dir, &mut worker, &doc, "formula.fodt");
assert_eq!(text.matches("<draw:object").count(), 1, "the edit replaces");
assert!(text.contains("c over d"), "the edit lands");
let caption = super::input::paragraphs(&text)
.into_iter()
.find(|line| line.contains("Figure"));
assert!(
caption
.as_deref()
.is_some_and(|line| line.ends_with("Figure 1: ratio")),
"the caption numbers: {caption:?}"
);
}
#[test]
fn formula_edits_keep_the_text_and_the_place() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
type_in(&mut worker, &doc, "PREFIX");
let wide = "\u{1d465} + e\u{301}";
run(&mut worker, &doc, "formula.insert", &[wide]);
let formula = |worker: &mut Worker| {
review::formula(&values(worker, &doc, ".uno:Formula")).expect("the formula parses")
};
assert_eq!(formula(&mut worker).as_deref(), Some(wide));
run(&mut worker, &doc, "image.anchor_page", &[]);
let placed = spot(&saved(&dir, &mut worker, &doc, "placed.fodt"));
assert!(placed.is_some(), "the formula sits on the page");
run(&mut worker, &doc, "formula.insert", &["c over d"]);
assert_eq!(formula(&mut worker).as_deref(), Some("c over d"));
let text = saved(&dir, &mut worker, &doc, "edited.fodt");
assert!(text.contains("PREFIX"), "the text before stays");
assert_eq!(spot(&text), placed, "the page position stays");
assert!(
text.contains("text:anchor-type=\"page\""),
"the place stays"
);
run(&mut worker, &doc, "edit.undo", &[]);
let text = saved(&dir, &mut worker, &doc, "undone.fodt");
assert!(text.contains(wide), "one undo restores the formula");
assert!(text.contains("text:anchor-type=\"page\""), "and its place");
}
/// The page-anchored frame's svg:x and svg:y.
fn spot(text: &str) -> Option<(String, String)> {
let frame = text.split("<draw:frame ").find(|frame| {
frame
.split('>')
.next()
.is_some_and(|head| head.contains("text:anchor-type=\"page\""))
})?;
let head = frame.split('>').next()?;
let value = |name: &str| {
let rest = head.split(&format!("{name}=\"")).nth(1)?;
rest.split('"').next().map(str::to_string)
};
Some((value("svg:x")?, value("svg:y")?))
}
/// An inline formula with its own spacing.
const INLINE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:automatic-styles><style:style style:name="fr1" style:family="graphic"><style:graphic-properties fo:margin-left="0.25in" fo:margin-right="0.5in" style:vertical-pos="top" style:vertical-rel="line"/></style:style></office:automatic-styles>
<office:body><office:text><text:p>Lead <draw:frame draw:style-name="fr1" draw:name="Formula1" text:anchor-type="as-char" svg:width="0.5in" svg:height="0.4in"><draw:object><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mfrac><mi>a</mi><mi>b</mi></mfrac><annotation encoding="StarMath 5.0">a over b</annotation></semantics></math></draw:object></draw:frame> tail</text:p></office:text></office:body>
</office:document>"#;
#[test]
fn an_inline_formula_keeps_its_spacing_and_alignment() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(INLINE);
let mut seen = Events::default();
for x in (1500..4000).step_by(100) {
click(&mut worker, &doc, x, 1600);
seen = poll_until(
&mut worker,
&doc,
&seen,
std::time::Duration::from_millis(400),
|seen| seen.graphic.is_some(),
);
if seen.graphic.is_some() {
break;
}
}
assert!(seen.graphic.is_some(), "a click selects the formula");
let formula = |worker: &mut Worker| {
review::formula(&values(worker, &doc, ".uno:Formula")).expect("the formula parses")
};
assert_eq!(formula(&mut worker).as_deref(), Some("a over b"));
run(&mut worker, &doc, "formula.insert", &["c over d"]);
assert_eq!(formula(&mut worker).as_deref(), Some("c over d"));
let text = saved(&dir, &mut worker, &doc, "inline.fodt");
for mark in [
"fo:margin-left=\"0.25in\"",
"fo:margin-right=\"0.5in\"",
"style:vertical-pos=\"top\"",
"style:vertical-rel=\"line\"",
"text:anchor-type=\"as-char\"",
] {
assert!(text.contains(mark), "{mark} stays");
}
let line = super::input::paragraphs(&text).join("");
assert!(
line.starts_with("Lead ") && line.ends_with(" tail"),
"{line:?}"
);
run(&mut worker, &doc, "edit.undo", &[]);
let text = saved(&dir, &mut worker, &doc, "undone.fodt");
assert!(text.contains("a over b"), "one undo restores the formula");
}
#[test]
fn comments_and_changes_review() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
worker.set_author("Ada Lovelace").expect("the author");
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "comment.insert", &["First note"]);
let notes = |worker: &mut Worker| {
review::notes(&values(worker, &doc, ".uno:ViewAnnotations")).expect("the notes parse")
};
let first = awaited(|| notes(&mut worker), |notes| !notes.is_empty());
assert_eq!(first.len(), 1);
assert_eq!(first[0].text, "First note");
assert_eq!(first[0].author, "Ada Lovelace", "the set name signs");
assert!(first[0].anchor.0 > 0, "the note has an anchor");
let id = first[0].id.clone();
run(&mut worker, &doc, "comment.reply", &[&id, "An answer"]);
let thread = awaited(|| notes(&mut worker), |notes| notes.len() == 2);
assert_eq!(thread.len(), 2);
assert_eq!(thread[1].parent, id);
run(&mut worker, &doc, "comment.insert", &["a\n\nNext"]);
let both = awaited(|| notes(&mut worker), |notes| notes.len() == 3);
assert_eq!(both[2].text, "a\n\nNext", "empty paragraphs count once");
run(&mut worker, &doc, "comment.insert", &["a\n\n"]);
let all = awaited(|| notes(&mut worker), |notes| notes.len() == 4);
assert_eq!(all[3].text, "a\n\n", "trailing empty paragraphs stay");
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "track.toggle", &[]);
let changes = |worker: &mut Worker| {
review::changes(&values(worker, &doc, ".uno:AcceptTrackedChanges"))
.expect("the changes parse")
};
type_in(&mut worker, &doc, "Kept ");
let kept = awaited(|| changes(&mut worker), |list| !list.is_empty());
assert_eq!(kept.len(), 1, "typing is tracked: {kept:?}");
assert!(kept[0].anchor.is_some(), "the change has a place");
run(
&mut worker,
&doc,
"track.accept",
&[&kept[0].index.to_string()],
);
let left = awaited(|| changes(&mut worker), Vec::is_empty);
assert!(left.is_empty(), "the change is taken");
type_in(&mut worker, &doc, "Dropped ");
let dropped = awaited(|| changes(&mut worker), |list| !list.is_empty());
assert_eq!(dropped.len(), 1);
run(&mut worker, &doc, "track.reject_all", &[]);
let left = awaited(|| changes(&mut worker), Vec::is_empty);
assert!(left.is_empty(), "the change is dropped");
let text = saved(&dir, &mut worker, &doc, "review.fodt");
for mark in ["First note", "An answer", "<office:annotation ", "Kept "] {
assert!(text.contains(mark), "{mark} lands");
}
assert!(!text.contains("Dropped"), "the rejected words go");
}
@@ -0,0 +1,108 @@
//! QA-10: edit, save as DOCX, reopen, compare.
use super::input::{open, paragraphs};
use super::*;
/// Round-trips `doc` through DOCX to flat XML.
fn round(dir: &tempfile::TempDir, worker: &mut Worker, doc: &Doc, name: &str) -> String {
let docx = dir.path().join(format!("{name}.docx"));
doc.save_as(worker, &crate::file_url(&docx), "docx")
.expect("the DOCX saves");
let back = worker
.load(&crate::file_url(&docx))
.expect("the DOCX reopens");
let flat = dir.path().join(format!("{name}.fodt"));
back.save_as(worker, &crate::file_url(&flat), "fodt")
.expect("flattens");
worker.close_doc(back).expect("closes");
std::fs::read_to_string(&flat).expect("reads")
}
fn run(worker: &mut Worker, doc: &Doc, id: &str, values: &[&str]) {
worker
.run(doc, id, values)
.unwrap_or_else(|error| panic!("{id}: {error}"));
}
pub(super) fn type_in(worker: &mut Worker, doc: &Doc, text: &str) {
for key in text.chars() {
let code = if key == '\n' { 1280 } else { 0 };
let char_code = if key == '\n' { 13 } else { key as u32 };
worker.post_key(doc, char_code, code).expect("a key");
}
}
#[test]
fn a_contract_keeps_numbering_comments_and_changes() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "list.numbering", &[]);
type_in(&mut worker, &doc, "Term one\nTerm two\n");
run(&mut worker, &doc, "comment.insert", &["Check the term"]);
run(&mut worker, &doc, "track.toggle", &[]);
type_in(&mut worker, &doc, "Added clause");
let text = round(&dir, &mut worker, &doc, "contract");
for mark in [
"<text:list",
"Term one",
"Term two",
"Check the term",
"<text:changed-region",
"Added clause",
] {
assert!(text.contains(mark), "{mark} survives DOCX");
}
}
#[test]
fn a_long_report_keeps_headings_contents_and_a_split_table() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(FODT);
click(&mut worker, &doc, 150, 150);
run(
&mut worker,
&doc,
"format.style",
&["Heading 1", "ParagraphStyles"],
);
type_in(&mut worker, &doc, " report\n");
run(&mut worker, &doc, "table.insert", &["2", "80"]);
run(&mut worker, &doc, "table.repeat_heading", &[]);
click(&mut worker, &doc, 150, 150);
run(&mut worker, &doc, "index.insert", &["Contents"]);
let pages = doc.pages(&mut worker).expect("pages");
assert!(
pages.len() >= 3,
"the table runs over pages: {}",
pages.len()
);
let text = round(&dir, &mut worker, &doc, "report");
for mark in [
"<text:table-of-content",
"text:outline-level=\"1\"",
"<table:table-header-rows>",
] {
assert!(text.contains(mark), "{mark} survives DOCX");
}
assert_eq!(
text.matches("<table:table-row").count(),
80,
"every row survives"
);
let heading = paragraphs(
&text
.replace("<text:h", "<text:p")
.replace("</text:h>", "</text:p>"),
);
assert!(
heading.iter().any(|line| line == "Report"),
"the heading text survives"
);
}
+487
View File
@@ -0,0 +1,487 @@
use super::sheet::open_book;
use super::*;
use crate::sheet;
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
pub(super) fn row(cells: &[&str]) -> String {
let cells: String = cells
.iter()
.map(|cell| match cell.parse::<f64>() {
Ok(_) => format!(
r#"<table:table-cell office:value-type="float" office:value="{cell}"><text:p>{cell}</text:p></table:table-cell>"#
),
Err(_) => format!(r#"<table:table-cell><text:p>{cell}</text:p></table:table-cell>"#),
})
.collect();
format!("<table:table-row>{cells}</table:table-row>")
}
/// Name, Qty, City; one repeated row.
fn data() -> String {
let rows: String = [
["Name", "Qty", "City"],
["a", "3", "x"],
["b", "1", "y"],
["a", "3", "x"],
["c", "2", "y"],
]
.iter()
.map(|cells| row(cells))
.collect();
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S">{rows}</table:table></office:spreadsheet></office:body>
</office:document>"#
)
}
fn open() -> (tempfile::TempDir, Worker, Doc, Events) {
let (dir, mut worker, doc) = open_book(&data());
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cell.cursor.is_some()
});
(dir, worker, doc, seen)
}
/// The cells of `range`, as the kernel copies them.
fn cells(worker: &mut Worker, doc: &Doc, range: &str) -> String {
worker.run(doc, "cell.goto", &[range]).expect("the range");
doc.selection_text(worker).expect("the text")
}
/// The latest report of `name`.
fn state<'a>(seen: &'a Events, name: &str) -> Option<&'a str> {
seen.states
.iter()
.rfind(|(state, _)| state == name)
.map(|(_, value)| value.as_str())
}
fn skip() -> bool {
let missing = install().is_none();
if missing {
eprintln!("SKIP: no pinned LOK build");
}
missing
}
#[test]
fn number_formats_alignment_and_fills_apply() {
if skip() {
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.run(&doc, "cell.goto", &["B2:B5"]).expect("B2:B5");
let read = worker.values(&doc, sheet::NUMBER).expect("the format");
let kind = sheet::number_format(&read).expect("parses").1;
assert_eq!(kind, "general", "the standard format is general");
worker
.run(&doc, "number.code", &["0.00%"])
.expect("a format code");
let read = worker.values(&doc, sheet::NUMBER).expect("the format");
assert_eq!(
sheet::number_format(&read).expect("parses"),
("0.00%".to_string(), "percent".to_string())
);
worker.run(&doc, "number.currency", &[]).expect("currency");
let read = worker.values(&doc, sheet::NUMBER).expect("the format");
assert_eq!(sheet::number_format(&read).expect("parses").1, "currency");
let check = |worker: &mut Worker, code: &str| {
let json = worker
.values(&doc, &sheet::number_check_query(code))
.expect("the check");
sheet::number_valid(&json).expect("parses")
};
assert!(check(&mut worker, "#,##0.00 \"kg\""));
assert!(!check(&mut worker, "[ZZZ]0"), "an unknown keyword fails");
assert!(
worker.run(&doc, "number.code", &["[ZZZ]0"]).is_err(),
"the kernel refuses a broken code"
);
worker.run(&doc, "align.center", &[]).expect("center");
worker.run(&doc, "cells.wrap", &["true"]).expect("wrap");
let states = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
state(seen, ".uno:AlignHorizontalCenter") == Some("true")
&& state(seen, ".uno:WrapText") == Some("true")
});
assert_eq!(state(&states, ".uno:WrapText"), Some("true"));
// The cell properties of the document's own cell formats.
let saved = |worker: &mut Worker| {
let out = _dir.path().join("borders.fods");
doc.save_as(worker, &format!("file://{}", out.display()), "fods")
.expect("the save");
let xml = std::fs::read_to_string(&out).expect("the saved book");
let start = xml.find("<office:automatic-styles>").expect("cell formats");
xml[start..]
.split("<style:table-cell-properties")
.skip(1)
.map(|cell| cell.split("/>").next().expect("a closed element"))
.collect::<String>()
};
worker.run(&doc, "cells.borders_all", &[]).expect("all");
let all = saved(&mut worker);
assert!(
all.contains("solid") && !all.contains("fo:border-top=\"none\""),
"every line"
);
worker.run(&doc, "cells.borders_outer", &[]).expect("outer");
let outer = saved(&mut worker);
assert!(
outer.contains("solid") && outer.contains("fo:border-top=\"none\""),
"no inner lines"
);
worker.run(&doc, "cells.borders_none", &[]).expect("none");
assert!(!saved(&mut worker).contains("solid"), "no lines");
worker.run(&doc, "cells.fill", &["16711680"]).expect("red");
assert!(saved(&mut worker).contains("fo:background-color=\"#ff0000\""));
worker.run(&doc, "cells.fill", &["-1"]).expect("no fill");
assert!(!saved(&mut worker).contains("#ff0000"), "the fill clears");
}
#[test]
fn sorting_filtering_and_duplicates() {
if skip() {
return;
}
let (_dir, mut worker, doc, _seen) = open();
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
let sort = ["true", "2", "true", "0", "true", "0", "true"];
worker.run(&doc, "data.sort", &sort).expect("by Qty");
assert_eq!(cells(&mut worker, &doc, "A2:A5").trim(), "b\nc\na\na");
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
let query = r#"{"conditions":[{"field":2,"op":"equals","value":"x"}]}"#;
worker
.run(&doc, "data.filter", &[query])
.expect("City is x");
let dropped = |worker: &mut Worker, column: u32| -> Vec<String> {
let query = sheet::cell_query(sheet::FILTER, column, 0);
let json = worker.values(&doc, &query).expect("the entries");
sheet::filter_values(&json)
.expect("parses")
.entries
.into_iter()
.filter(|entry| !entry.selected)
.map(|entry| entry.text)
.collect()
};
assert_eq!(dropped(&mut worker, 2), ["y"]);
let picked = r#"{"column":0,"conditions":[{"op":"values","values":["c"]}]}"#;
worker
.run(&doc, "data.filter", &[picked])
.expect("Name is c");
assert_eq!(dropped(&mut worker, 0), ["a", "b"], "the column keeps c");
assert_eq!(dropped(&mut worker, 2), ["y"], "the City filter stays");
worker.run(&doc, "data.unfilter", &[]).expect("no filter");
assert!(dropped(&mut worker, 2).is_empty());
let bad = r#"{"conditions":[{"field":9,"op":"equals","value":"x"}]}"#;
assert!(
worker.run(&doc, "data.filter", &[bad]).is_err(),
"out of the data"
);
worker.run(&doc, "cell.goto", &["B3"]).expect("B3");
worker.run(&doc, "select.data", &[]).expect("the data area");
let json = worker.values(&doc, sheet::SELECTED).expect("the selection");
let picked = sheet::selected_range(&json)
.expect("parses")
.expect("one range");
assert_eq!(
(picked.top.as_slice(), picked.header),
(&["Name".to_string(), "Qty".into(), "City".into()][..], true)
);
let (c1, r1, c2, r2) = picked.area.expect("data");
assert_eq!((c1, r1, c2, r2), (0, 0, 2, 4), "{}", picked.range);
let corners = [c1, r1, c2, r2].map(|n| n.to_string());
let mut values = vec!["true", "true", "true"];
values.extend(corners.iter().map(String::as_str));
values.push("0");
let now = worker.now(&doc).expect("the state");
worker.run(&now, "data.dedupe", &values).expect("removes");
assert_eq!(cells(&mut worker, &doc, "A2:A5").trim(), "b\nc\na");
}
#[test]
fn a_filter_button_and_alt_down_ask_for_ely_menus() {
if skip() {
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
worker.run(&doc, "data.autofilter", &[]).expect("buttons");
let a1 = seen.cell.cursor.expect("the cursor");
click(&mut worker, &doc, a1.0 + a1.2 - 60, a1.1 + a1.3 / 2);
let asked = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.cell.request.is_some()
});
assert_eq!(
asked.cell.request,
Some(Request::Filter { column: 0, row: 0 })
);
worker.run(&doc, "cell.goto", &["E2"]).expect("E2");
let rule = crate::sheet::Validation {
kind: "list".into(),
operator: "equal".into(),
list: vec!["Red".into(), "Green \"G\"".into()],
dropdown: true,
ignore_blank: true,
show_input: true,
input_title: "Pick".into(),
input_message: "A color".into(),
show_error: true,
error_style: "stop".into(),
error_title: "Bad".into(),
error_message: "Red or green".into(),
..Default::default()
};
worker
.run(&doc, "rules.validation", &[&rule.to_json()])
.expect("a list");
let json = worker
.values(&doc, &sheet::cell_query(sheet::LIST, 4, 1))
.expect("the choices");
assert_eq!(
sheet::list_values(&json).expect("parses"),
["Red", "Green \"G\""]
);
let read = sheet::validation(&worker.values(&doc, sheet::VALIDATION).expect("the rule"))
.expect("parses");
assert_eq!(
(
read.kind.as_str(),
read.dropdown,
read.input_message.as_str()
),
("list", true, "A color")
);
worker.post_key(&doc, 0, 1024 | 0x4000).expect("Alt+Down");
let listed = poll_until(&mut worker, &doc, &asked, SETTLE, |seen| {
seen.cell.requests > asked.cell.requests
});
assert_eq!(
listed.cell.request,
Some(Request::Choices { column: 4, row: 1 })
);
for c in "Blue".chars() {
worker.post_key(&doc, c as u32, 0).expect("a key");
}
worker.post_key(&doc, 13, 1280).expect("Enter");
let refused = poll_until(&mut worker, &doc, &listed, SETTLE, |seen| {
seen.cell.requests > listed.cell.requests
});
assert!(
matches!(
&refused.cell.request,
Some(Request::Invalid { accepted: false, title, .. }) if title == "Bad"
),
"{:?}",
refused.cell.request
);
worker.run(&doc, "cell.goto", &["E3"]).expect("E3");
let away = poll_until(&mut worker, &doc, &refused, SETTLE, |seen| {
seen.cell.address == "E3"
});
worker.run(&doc, "cell.goto", &["E2"]).expect("E2");
let kept = poll_until(&mut worker, &doc, &away, SETTLE, |seen| {
seen.cell.address == "E2"
});
assert_eq!(kept.cell.formula, "", "a stop keeps it out");
}
#[test]
fn any_value_keeps_its_input_help() {
if skip() {
return;
}
let (_dir, mut worker, doc, _seen) = open();
worker.run(&doc, "cell.goto", &["D2"]).expect("D2");
let rule = crate::sheet::Validation {
kind: "any".into(),
operator: "between".into(),
show_input: true,
input_message: "An id".into(),
error_style: "stop".into(),
..Default::default()
};
worker
.run(&doc, "rules.validation", &[&rule.to_json()])
.expect("help alone");
let read = sheet::validation(&worker.values(&doc, sheet::VALIDATION).expect("the rule"))
.expect("parses");
assert_eq!(
(read.show_input, read.input_message.as_str()),
(true, "An id")
);
let none = crate::sheet::Validation {
kind: "any".into(),
operator: "between".into(),
error_style: "stop".into(),
..Default::default()
};
worker
.run(&doc, "rules.validation", &[&none.to_json()])
.expect("cleared");
let read = sheet::validation(&worker.values(&doc, sheet::VALIDATION).expect("the rule"))
.expect("parses");
assert!(!read.show_input, "the help is gone");
}
#[test]
fn whole_numbers_text_columns_and_value_pastes() {
if skip() {
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.run(&doc, "cell.goto", &["B2:B5"]).expect("B2:B5");
let rule = crate::sheet::Validation {
kind: "whole".into(),
operator: "between".into(),
value1: "1".into(),
value2: "10".into(),
ignore_blank: true,
show_error: true,
error_style: "info".into(),
..Default::default()
};
worker
.run(&doc, "rules.validation", &[&rule.to_json()])
.expect("whole numbers");
worker.run(&doc, "cell.goto", &["B2"]).expect("B2");
for c in "50".chars() {
worker.post_key(&doc, c as u32, 0).expect("a key");
}
worker.post_key(&doc, 13, 1280).expect("Enter");
let warned = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.cell.request.is_some()
});
assert!(
matches!(
warned.cell.request,
Some(Request::Invalid { accepted: true, .. })
),
"{:?}",
warned.cell.request
);
assert_eq!(
cells(&mut worker, &doc, "B2").trim(),
"50",
"a note lets it in"
);
worker.run(&doc, "cell.goto", &["A7"]).expect("A7");
worker.run(&doc, "cell.enter", &["p;q;r"]).expect("text");
worker.run(&doc, "cell.goto", &["A7"]).expect("A7");
worker
.run(&doc, "data.columns", &["59,34,76,1"])
.expect("split");
assert_eq!(cells(&mut worker, &doc, "A7:C7").trim(), "p\tq\tr");
worker.run(&doc, "cell.goto", &["E2"]).expect("E2");
worker
.run(&doc, "cell.enter", &["=B3*2"])
.expect("a formula");
worker.run(&doc, "cell.goto", &["E2"]).expect("E2");
worker.copy(&doc).expect("the copy");
worker.run(&doc, "cell.goto", &["F2"]).expect("F2");
worker.run(&doc, "paste.values", &[]).expect("values");
worker.run(&doc, "cell.goto", &["G2"]).expect("G2");
worker.run(&doc, "paste.formulas", &[]).expect("formulas");
worker.run(&doc, "cell.goto", &["F2"]).expect("F2");
let pasted = poll_until(&mut worker, &doc, &warned, SETTLE, |seen| {
seen.cell.address == "F2" && !seen.cell.formula.is_empty()
});
assert_eq!(pasted.cell.formula, "2", "the value alone");
worker.run(&doc, "cell.goto", &["G2"]).expect("G2");
let formula = poll_until(&mut worker, &doc, &pasted, SETTLE, |seen| {
seen.cell.address == "G2"
});
assert_eq!(formula.cell.formula, "=D3*2", "the reference moves along");
}
#[test]
fn conditional_formats_add_list_and_go() {
if skip() {
return;
}
let (_dir, mut worker, doc, _seen) = open();
worker.run(&doc, "cell.goto", &["B2:B5"]).expect("B2:B5");
let read = |worker: &mut Worker| {
sheet::formats(&worker.values(&doc, sheet::FORMATS).expect("the formats")).expect("parses")
};
for rule in [
r#"{"kind":"cell","operator":"greater","value1":"2","style":"Good"}"#,
r##"{"kind":"scale","colors":["#F8696B","#FFEB84","#63BE7B"]}"##,
r##"{"kind":"databar","color":"#638EC6"}"##,
] {
worker.run(&doc, "rules.conditional", &[rule]).expect(rule);
}
let formats = read(&mut worker);
let kinds: Vec<&str> = formats.iter().map(|format| format.kind.as_str()).collect();
assert_eq!(kinds, ["cell", "scale", "databar"]);
assert_eq!(
(
formats[0].style.as_str(),
formats[0].value.as_str(),
formats[0].range.as_str()
),
("Good", "2", "B2:B5")
);
let unknown = r#"{"kind":"cell","operator":"greater","value1":"2","style":"Nope"}"#;
assert!(worker.run(&doc, "rules.conditional", &[unknown]).is_err());
let remove = format!(r#"{{"remove":{}}}"#, formats[1].key);
worker
.run(&doc, "rules.conditional", &[&remove])
.expect("removes");
assert_eq!(read(&mut worker).len(), 2);
}
#[test]
fn search_counts_and_replaces_cells() {
if skip() {
return;
}
let (_dir, mut worker, doc, seen) = open();
let find = ["a", "false", "1", "256", "0", "1"];
worker.run(&doc, "find.run", &find).expect("find all");
let all = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| seen.searched > 0);
assert_eq!(all.found.len(), 3, "one per cell: {:?}", all.found);
let step = ["a", "false", "0", "256", "0", "1"];
worker.run(&doc, "find.run", &step).expect("find next");
let next = poll_until(&mut worker, &doc, &all, SETTLE, |seen| {
seen.searched > all.searched
});
let at = next.found.first().expect("a match");
assert!(all.found.contains(at), "{at:?} is one of {:?}", all.found);
let replace = ["a", "false", "3", "256", "0", "1", "z"];
worker
.run(&doc, "find.replace", &replace)
.expect("replace all");
assert_eq!(cells(&mut worker, &doc, "A1:A5").trim(), "Nzme\nz\nb\nz\nc");
}
#[test]
fn enter_and_tab_move_the_cell_cursor() {
if skip() {
return;
}
let (_dir, mut worker, doc, seen) = open();
worker.run(&doc, "cell.goto", &["F1"]).expect("F1");
let at = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| {
seen.cell.address == "F1"
});
worker.post_text(&doc, true, "7").expect("typed text");
worker.post_key(&doc, 0, 1280).expect("Enter");
let down = poll_until(&mut worker, &doc, &at, SETTLE, |seen| {
seen.cell.address == "F2"
});
assert_eq!(down.cell.address, "F2", "Enter moves down");
worker.post_key(&doc, '8' as u32, 0).expect("a key");
worker.post_key(&doc, 0, 1282).expect("Tab");
let right = poll_until(&mut worker, &doc, &down, SETTLE, |seen| {
seen.cell.address == "G2"
});
assert_eq!(right.cell.address, "G2", "Tab moves right");
}
+182
View File
@@ -0,0 +1,182 @@
use super::input::FODS;
use super::*;
/// How long a command may take to report.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
#[test]
fn a11y_follows_calc_cells() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_sheet();
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
worker.post_key(&doc, 0, 1027).expect("Right to B1");
let b1 = poll_until(&mut worker, &doc, &base, SETTLE, |_| false);
worker.post_key(&doc, 0, 1026).expect("Left to A1");
let a1 = poll_until(&mut worker, &doc, &b1, SETTLE, |seen| {
seen.a11y.text == "Hello 世界"
});
assert_eq!(
a1.a11y.text, "Hello 世界",
"the cell text bridges without editing"
);
worker.post_key(&doc, 0, 1027).expect("Right to B1 again");
let empty = poll_until(&mut worker, &doc, &a1, SETTLE, |seen| {
seen.a11y.text.is_empty()
});
assert_eq!(empty.a11y.text, "", "the empty B1 clears the bridge");
}
/// The FODS fixture in a fresh worker.
fn open_sheet() -> (tempfile::TempDir, Worker, Doc) {
let install = install().expect("the pinned LOK build");
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("in.fods");
write(&source, FODS);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the sheet loads");
(dir, worker, doc)
}
#[test]
fn a_cancelled_cell_edit_restores_the_cell_text() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_sheet();
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
worker.post_key(&doc, 0, 769).expect("F2 edits A1");
worker
.post_key(&doc, 'Z' as u32, 537 | 0x1000)
.expect("Z types");
let typed = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.a11y.text.ends_with('Z')
});
assert_eq!(typed.a11y.text, "Hello 世界Z", "the edit bridges");
worker.post_key(&doc, 0, 1281).expect("Escape cancels");
let back = poll_until(&mut worker, &doc, &typed, SETTLE, |seen| {
seen.a11y.text == "Hello 世界"
});
assert_eq!(back.a11y.text, "Hello 世界", "the cancel restores the cell");
}
#[test]
fn undo_and_redo_work_inside_a_cell_edit() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
for with_history in [false, true] {
let (_dir, mut worker, doc) = open_sheet();
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
if with_history {
worker
.run(&doc, "format.bold", &[])
.expect("a document step");
}
worker.post_key(&doc, 0, 769).expect("F2 edits A1");
worker
.post_key(&doc, 'Z' as u32, 537 | 0x1000)
.expect("Z types");
let typed = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
seen.a11y.text == "Hello 世界Z"
});
assert_eq!(typed.a11y.text, "Hello 世界Z");
worker
.run(&doc, "edit.undo", &[])
.expect("undo in the edit");
let undone = poll_until(&mut worker, &doc, &typed, SETTLE, |seen| {
seen.a11y.text == "Hello 世界"
});
assert_eq!(undone.a11y.text, "Hello 世界", "history {with_history}");
worker
.run(&doc, "edit.redo", &[])
.expect("redo in the edit");
let redone = poll_until(&mut worker, &doc, &undone, SETTLE, |seen| {
seen.a11y.text == "Hello 世界Z"
});
assert_eq!(redone.a11y.text, "Hello 世界Z", "history {with_history}");
}
}
/// Three sheets; T hides, U refers to S.
pub(super) const SHEETS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:automatic-styles><style:style style:name="ta2" style:family="table"><style:table-properties table:display="false"/></style:style></office:automatic-styles>
<office:body><office:spreadsheet>
<table:table table:name="S"><table:table-row><table:table-cell><text:p>Hello 世界</text:p></table:table-cell></table:table-row></table:table>
<table:table table:name="T" table:style-name="ta2"><table:table-row><table:table-cell/></table:table-row></table:table>
<table:table table:name="U"><table:table-row><table:table-cell table:formula="of:=[S.A1]"/><table:table-cell table:formula="of:=INDIRECT(&quot;S.A1&quot;)"/></table:table-row></table:table>
</office:spreadsheet></office:body>
</office:document>"#;
#[test]
fn sheets_list_switch_and_the_cell_reports() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_book(SHEETS);
let sheets = doc.sheets(&mut worker).expect("the sheets");
let names: Vec<_> = sheets
.list
.iter()
.map(|sheet| (sheet.name.as_str(), sheet.visible))
.collect();
assert_eq!(names, [("S", true), ("T", false), ("U", true)]);
assert_eq!(sheets.current, 0);
let first = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cell.address == "A1" && seen.cell.formula == "Hello 世界" && seen.cell.cursor.is_some()
});
assert!(first.cell.cursor.is_some(), "the cell cursor shows on load");
let geometry = crate::sheet::geometry(
&worker
.values(&doc, crate::sheet::GEOMETRY)
.expect("the geometry"),
)
.expect("the geometry parses");
worker.post_key(&doc, 0, 1027).expect("Right to B1");
worker.post_key(&doc, 0, 1024).expect("Down to B2");
worker.post_key(&doc, 0, 1024).expect("Down to B3");
let b3 = poll_until(&mut worker, &doc, &first, SETTLE, |seen| {
seen.cell.address == "B3"
});
let (x, y, _, _) = b3.cell.cursor.expect("the cell cursor");
assert_eq!(
(x, y),
(geometry.columns.start(1), geometry.rows.start(2)),
"the geometry places B3 where the kernel does"
);
let first = b3;
doc.show_sheet(&mut worker, 2).expect("U shows");
assert_eq!(doc.sheets(&mut worker).expect("the sheets").current, 2);
let third = poll_until(&mut worker, &doc, &first, SETTLE, |seen| {
seen.cell.formula.starts_with('=')
});
assert!(
third.cell.formula.contains("S!A1"),
"U's formula shows: {}",
third.cell.formula
);
assert!(third.cell.sheets > first.cell.sheets, "the switch reports");
}
/// `text` loaded as a spreadsheet the view shows.
pub(super) fn open_book(text: &str) -> (tempfile::TempDir, Worker, Doc) {
let install = install().expect("the pinned LOK build");
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("book.fods");
write(&source, text);
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the book loads");
doc.visible_area(&mut worker, (0, 0, 15000, 10000))
.expect("the area");
(dir, worker, doc)
}
+322
View File
@@ -0,0 +1,322 @@
use super::analysis::steps;
use super::*;
use crate::show;
/// Two slides on the default master.
pub(crate) const DECK: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.presentation">
<office:body><office:presentation>
<draw:page draw:name="One"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>First</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="Two"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Second</text:p></draw:text-box></draw:frame></draw:page>
</office:presentation></office:body>
</office:document>"#;
pub(super) fn open_deck() -> (tempfile::TempDir, Worker, Doc) {
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let path = dir.path().join("deck.fodp");
std::fs::write(&path, DECK).expect("writes");
let doc = worker.load(&crate::file_url(&path)).expect("loads");
(dir, worker, doc)
}
fn slides(worker: &mut Worker, doc: &Doc) -> Vec<(String, bool)> {
let sheets = doc.sheets(worker).expect("the slides");
sheets
.list
.into_iter()
.map(|slide| (slide.name, slide.visible))
.collect()
}
fn design(worker: &mut Worker, doc: &Doc) -> show::Design {
show::design(&worker.values(doc, show::DESIGN).expect("reads")).expect("parses")
}
/// Runs `id`; the kernel's history gains one step.
fn one_step(worker: &mut Worker, doc: &Doc, id: &str, values: &[&str]) {
let before = steps(worker, doc);
worker.run(doc, id, values).expect(id);
assert_eq!(steps(worker, doc), before + 1, "{id} is one undo step");
}
#[test]
fn slides_insert_copy_hide_move_and_delete() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
one_step(&mut worker, &doc, "slide.insert", &[]);
one_step(&mut worker, &doc, "slide.duplicate", &[]);
assert_eq!(slides(&mut worker, &doc).len(), 4);
one_step(&mut worker, &doc, "slide.hide", &[]);
assert!(!slides(&mut worker, &doc)[2].1, "the copy hides");
one_step(&mut worker, &doc, "slide.show", &[]);
one_step(&mut worker, &doc, "slide.last", &[]);
assert_eq!(slides(&mut worker, &doc)[2].0, "Two", "Two moved up one");
one_step(&mut worker, &doc, "slide.first", &[]);
assert_eq!(doc.sheets(&mut worker).expect("slides").current, 0);
one_step(&mut worker, &doc, "slide.delete", &[]);
assert_eq!(slides(&mut worker, &doc).len(), 3);
}
#[test]
fn size_layout_master_and_theme_change_in_one_step() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
one_step(&mut worker, &doc, "slide.size", &["25400", "19050", "true"]);
let (w, h) = doc.size(&mut worker).expect("the size");
assert!(
(w - 14400).abs() <= 2 && (h - 10800).abs() <= 2,
"4:3 in twips: {w} x {h}"
);
one_step(&mut worker, &doc, "slide.layout", &["1"]);
assert_eq!(design(&mut worker, &doc).layout, 1);
worker
.run(&doc, "master.edit", &[])
.expect("the master view");
worker.run(&doc, "master.insert", &[]).expect("a master");
worker.run(&doc, "master.close", &[]).expect("back");
let read = design(&mut worker, &doc);
assert_eq!(read.masters, ["Default", "Default 1"]);
assert_eq!(read.master, "Default");
one_step(&mut worker, &doc, "slide.master", &["Default 1"]);
assert_eq!(design(&mut worker, &doc).master, "Default 1");
assert!(
worker.run(&doc, "slide.master", &["Nope"]).is_err(),
"no such master"
);
let theme = read.themes.first().expect("a color set").clone();
one_step(&mut worker, &doc, "slide.theme", &[&theme]);
assert_eq!(design(&mut worker, &doc).theme, theme);
assert!(
worker.run(&doc, "slide.theme", &["Nope"]).is_err(),
"no such set"
);
}
#[test]
fn a_master_edit_shows_on_its_slides() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let side = (160, 90);
let before = doc
.paint_part(&mut worker, (1, false), side)
.expect("paints");
assert_eq!(before.len(), 160 * 90 * 4);
worker
.run(&doc, "master.edit", &[])
.expect("the master view");
assert_eq!(slides(&mut worker, &doc).len(), 1, "the parts are masters");
let master = doc
.paint_part(&mut worker, (0, true), side)
.expect("paints");
assert_ne!(master, before, "a master paints as a master");
worker
.paste(&doc, "text/plain;charset=utf-8", b"Brand")
.expect("pastes onto the master");
worker
.run(&doc, "master.close", &[])
.expect("back to slides");
assert_eq!(slides(&mut worker, &doc).len(), 2, "slides again");
let after = doc
.paint_part(&mut worker, (1, false), side)
.expect("paints");
assert_ne!(before, after, "slide two shows the master's change");
let out = dir.path().join("out.fodp");
doc.save_as(&mut worker, &crate::file_url(&out), "fodp")
.expect("saves");
let xml = std::fs::read_to_string(out).expect("reads");
let master = &xml[xml.find("<style:master-page").expect("a master")..];
assert!(master.contains("Brand"), "the master holds the edit");
}
#[test]
fn tiles_keep_their_picture_during_text_edit() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let far = (8000, 6000, 3000, 2000);
let before = doc.paint_tile(&mut worker, far, (64, 64)).unwrap().pixels;
click(&mut worker, &doc, 2500, 1500);
for c in "Hey".chars() {
worker.post_key(&doc, c as u32, 0).unwrap();
}
let during = doc.paint_tile(&mut worker, far, (64, 64)).unwrap().pixels;
assert!(before == during, "a tile away from the edit changed");
}
fn objects(worker: &mut Worker, doc: &Doc) -> show::Objects {
show::objects(&worker.values(doc, show::OBJECTS).expect("reads")).expect("parses")
}
#[test]
fn objects_read_select_move_and_guide() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker
.run(&doc, "draw.shape", &["rectangle", "true"])
.expect("draws");
let read = objects(&mut worker, &doc);
assert_eq!(read.objects.len(), 2);
assert_eq!(read.objects[1].kind, "shape");
assert!(read.objects[1].selected && !read.objects[0].selected);
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["0", "false"])
.expect("selects");
let read = objects(&mut worker, &doc);
assert_eq!(read.selection.expect("one").kind, "text");
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["1", "true"])
.expect("adds");
let selection = objects(&mut worker, &doc).selection.expect("two");
assert!(selection.count == 2 && selection.can_group);
worker
.run(&doc, "object.deselect", &["false"])
.expect("deselects");
assert!(
objects(&mut worker, &doc).selection.is_none(),
"Add alone picks none"
);
// Transform arguments are twips: 1701 twips is 3 cm.
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["1", "false"])
.expect("selects");
worker.run(&doc, "object.x", &["1701"]).expect("moves");
let rect = objects(&mut worker, &doc).selection.expect("one").rect;
assert!((rect.0 - 3000).abs() <= 1, "{rect:?}");
worker
.run(&doc, "guide.add", &["0", "0", "4000"])
.expect("adds");
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "guide.move", &["0", "0", "5000"])
.expect("moves");
let guides = objects(&mut worker, &doc).guides;
assert_eq!(guides.len(), 1);
assert_eq!(
(guides[0].kind, guides[0].at.1),
(show::GuideKind::Horizontal, 5000)
);
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "guide.delete", &["0", "true"])
.expect("deletes");
assert!(objects(&mut worker, &doc).guides.is_empty());
}
#[test]
fn pictures_land_mid_slide_and_replace_in_place() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
let red = super::layout::png(dir.path(), "red.png", [255, 0, 0, 255]);
let blue = super::layout::png(dir.path(), "blue.png", [0, 0, 255, 255]);
worker.run(&doc, "image.insert", &[&red]).expect("inserts");
let first = objects(&mut worker, &doc).selection.expect("the picture");
let (w, h) = doc.size(&mut worker).expect("the slide");
let mid = |(x, y, width, height): (i64, i64, i64, i64)| (x + width / 2, y + height / 2);
let (cx, cy) = mid(first.rect);
let (sw, sh) = (w * 127 / 72, h * 127 / 72);
assert!(
(cx - sw / 2).abs() < 20 && (cy - sh / 2).abs() < 20,
"{first:?}"
);
worker
.run(&doc, "image.replace", &[&blue])
.expect("replaces");
let read = objects(&mut worker, &doc);
assert_eq!(read.objects.len(), 2, "replaced, not added");
assert_eq!(mid(read.selection.expect("the picture").rect), (cx, cy));
}
/// A sideways-growing box and a small 20 pt box.
const FITS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.presentation">
<office:automatic-styles>
<style:style style:name="wide" style:family="graphic"><style:graphic-properties draw:auto-grow-width="true" draw:auto-grow-height="false"/></style:style>
<style:style style:name="small" style:family="graphic"><style:graphic-properties draw:auto-grow-width="false" draw:auto-grow-height="false"/><style:text-properties fo:font-size="20pt"/></style:style>
</office:automatic-styles>
<office:body><office:presentation>
<draw:page draw:name="One">
<draw:frame draw:style-name="wide" svg:x="1cm" svg:y="1cm" svg:width="10cm" svg:height="1cm"><draw:text-box><text:p>Grows</text:p></draw:text-box></draw:frame>
<draw:frame draw:style-name="small" svg:x="1cm" svg:y="5cm" svg:width="2cm" svg:height="0.5cm"><draw:text-box><text:p>A long sentence that does not fit in this small box.</text:p></draw:text-box></draw:frame>
</draw:page>
</office:presentation></office:body>
</office:document>"#;
#[test]
fn fit_rules_set_both_growths_and_undo_keeps_the_text() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install().expect("LOK"), &dir.path().join("p")).expect("up");
let path = dir.path().join("fits.fodp");
std::fs::write(&path, FITS).expect("writes");
let doc = worker.load(&crate::file_url(&path)).expect("loads");
let saved = |worker: &mut Worker, name: &str| {
let out = dir.path().join(name);
doc.save_as(worker, &crate::file_url(&out), "fodp")
.expect("saves");
std::fs::read_to_string(out).expect("reads")
};
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["0", "false"])
.expect("selects");
worker.run(&doc, "text.fit", &["off"]).expect("fits");
let xml = saved(&mut worker, "off.fodp");
assert!(
!xml.contains(r#"draw:auto-grow-width="true""#),
"off stops sideways growth"
);
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["1", "false"])
.expect("selects");
let before = doc
.paint_part(&mut worker, (0, false), (320, 180))
.expect("paints");
let body = |xml: &str| xml[xml.find("A long sentence").expect("the text") - 80..].to_string();
let body_before = body(&saved(&mut worker, "before.fodp"));
worker.run(&doc, "text.fit", &["shrink"]).expect("shrinks");
worker.run(&doc, "edit.undo", &[]).expect("undoes");
let after = doc
.paint_part(&mut worker, (0, false), (320, 180))
.expect("paints");
assert!(before == after, "undo brings the picture back");
assert_eq!(
body(&saved(&mut worker, "after.fodp")),
body_before,
"and the paragraph"
);
}
+362
View File
@@ -0,0 +1,362 @@
use super::analysis::steps;
use super::show::open_deck;
use super::*;
use crate::show::{self, ChartData};
fn chart(worker: &mut Worker, doc: &Doc) -> Option<show::SlideChart> {
show::slide_chart(&worker.values(doc, crate::sheet::CHART).expect("reads")).expect("parses")
}
fn data(series: &[(&str, [f64; 2])]) -> ChartData {
ChartData {
categories: vec!["Q1".into(), "Q2".into()],
series: series
.iter()
.map(|(name, values)| (name.to_string(), values.iter().map(|v| Some(*v)).collect()))
.collect(),
}
}
#[test]
fn charts_insert_change_and_undo_with_their_data() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let look = crate::sheet::Look {
kind: "column".into(),
title: "Sales".into(),
legend: true,
..Default::default()
};
let first = data(&[("North", [1.0, 2.0]), ("South", [3.0, 4.0])]);
worker
.run(
&doc,
"show.chart",
&[&show::chart_json(&look, Some(&first))],
)
.expect("inserts");
let read = chart(&mut worker, &doc).expect("the new chart is selected");
assert_eq!(
(read.look.kind.as_str(), read.look.title.as_str()),
("column", "Sales")
);
assert_eq!(read.data.as_ref(), Some(&first));
let pie = crate::sheet::Look {
kind: "pie".into(),
..look
};
let second = data(&[("West", [5.0, 6.0])]);
worker
.run(
&doc,
"show.chart",
&[&show::chart_json(&pie, Some(&second))],
)
.expect("changes");
let read = chart(&mut worker, &doc).expect("still selected");
assert_eq!(
(read.look.kind.as_str(), read.data.as_ref()),
("pie", Some(&second))
);
let objects =
show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
assert_eq!(objects.objects.len(), 2, "changed in place, not added");
worker.run(&doc, "edit.undo", &[]).expect("undoes");
let state = worker.now(&doc).expect("the state");
worker
.run(&state, "object.select", &["1", "false"])
.expect("selects");
assert_eq!(
chart(&mut worker, &doc).expect("the chart").data,
Some(first)
);
// A ragged table is refused and nothing changes.
let bad = r#"{"type":"column","title":"","legend":true,"xtitle":"","ytitle":"","data":{"categories":["A"],"series":[{"name":"S","values":[1,2]}]}}"#;
let before = steps(&mut worker, &doc);
assert!(worker.run(&doc, "show.chart", &[bad]).is_err());
assert_eq!(steps(&mut worker, &doc), before);
}
#[test]
fn notes_set_read_and_undo_as_one_step() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let notes = |worker: &mut Worker| {
show::notes(&worker.values(&doc, show::NOTES).expect("reads")).expect("parses")
};
let blank = notes(&mut worker);
assert!(
blank.editable && blank.text.is_empty() && !blank.rich,
"{blank:?}"
);
let before = steps(&mut worker, &doc);
notes_set(&mut worker, &doc, &["Say hello\nThen the plan", "0"])
.expect("sets");
let set = notes(&mut worker);
assert_eq!(
(set.text.as_str(), set.rich),
("Say hello\nThen the plan", false)
);
assert_eq!(steps(&mut worker, &doc), before + 1);
notes_set(&mut worker, &doc, &["", "0"]).expect("clears");
assert_eq!(notes(&mut worker).text, "");
worker.run(&doc, "edit.undo", &[]).expect("undoes");
assert_eq!(notes(&mut worker).text, "Say hello\nThen the plan");
// Notes go to the slide named, not the one shown.
notes_set(&mut worker, &doc, &["For two", "1"])
.expect("sets");
assert_eq!(notes(&mut worker).part, Some(0));
assert_eq!(notes(&mut worker).text, "Say hello\nThen the plan");
doc.show_sheet(&mut worker, 1).expect("the second slide");
let second = notes(&mut worker);
assert_eq!((second.part, second.text.as_str()), (Some(1), "For two"));
}
/// Sets notes as an app does, at a fresh read.
fn notes_set(worker: &mut Worker, doc: &Doc, values: &[&str]) -> io::Result<()> {
let at = worker.now(doc)?;
worker.run(&at, "notes.set", values)
}
#[test]
fn notes_for_a_slide_number_need_the_state_it_was_read_in() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
doc.show_sheet(&mut worker, 0).expect("the first slide");
let read = worker.now(&doc).expect("the state");
worker.run(&doc, "slide.delete", &[]).expect("deletes the first");
// Slide 0 was the deleted one when read.
let stale = worker.run(&read, "notes.set", &["Late", "0"]).expect_err("an older state");
assert!(crate::is_stale(&stale), "{stale}");
let kept = show::notes(&worker.values(&doc, show::NOTES).expect("reads")).expect("parses");
assert_eq!(kept.text, "", "the next slide keeps its notes");
}
#[test]
fn comments_carry_their_slide_author_edits_and_deletes() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let remarks = |worker: &mut Worker| {
show::remarks(&worker.values(&doc, ".uno:ViewAnnotations").expect("reads")).expect("parses")
};
let count = |worker: &mut Worker| {
let read = worker.values(&doc, show::OBJECTS).expect("reads");
show::objects(&read).expect("parses").objects.len()
};
worker.set_author("Ada Lovelace").expect("the author");
doc.show_sheet(&mut worker, 1).expect("the second slide");
let shapes = count(&mut worker);
worker
.run(&doc, "comment.insert", &["Check the numbers"])
.expect("inserts");
let list = remarks(&mut worker);
assert_eq!(list.len(), 1);
assert_eq!(count(&mut worker), shapes, "comments are not objects");
assert_eq!(
(list[0].part, list[0].text.as_str(), list[0].author.as_str()),
(1, "Check the numbers", "Ada Lovelace")
);
let id = list[0].id.clone();
worker
.run(&doc, "remark.edit", &[&id, "Check the totals"])
.expect("edits");
assert_eq!(remarks(&mut worker)[0].text, "Check the totals");
let ids: Vec<String> = remarks(&mut worker).into_iter().map(|r| r.id).collect();
for id in ids {
worker.run(&doc, "remark.delete", &[&id]).expect("deletes");
}
assert!(remarks(&mut worker).is_empty());
}
#[test]
fn tables_insert_and_grow_on_a_slide() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker
.run(&doc, "table.insert", &["3", "2"])
.expect("inserts");
let read = show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
let table = read.selection.expect("the new table is selected");
assert_eq!(table.kind, "table");
let (w, h) = doc.size(&mut worker).expect("the slide");
let (sw, sh) = (w * 127 / 72, h * 127 / 72);
let (x, y, tw, th) = table.rect;
// Centred across; rows grow down from the middle.
assert!((x + tw / 2 - sw / 2).abs() < 50, "{table:?}");
assert!(y > 0 && y + th < sh, "on the slide: {table:?}");
let tall = table.rect.3;
for id in ["table.row_below", "table.column_right"] {
let before = steps(&mut worker, &doc);
worker.run(&doc, id, &[]).expect(id);
assert_eq!(steps(&mut worker, &doc), before + 1, "{id} is one step");
}
let now = show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
let table = now
.objects
.iter()
.find(|o| o.kind == "table")
.expect("the table");
assert!(table.rect.3 > tall, "a row more: {table:?}");
}
#[test]
fn notes_keep_one_look_and_refuse_varied_ones() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
notes_set(&mut worker, &doc, &["Say this first", "0"])
.expect("sets");
let out = dir.path().join("plain.fodp");
doc.save_as(&mut worker, &crate::file_url(&out), "fodp")
.expect("saves");
for kind in ["odp", "pptx"] {
let copy = dir.path().join(format!("plain.{kind}"));
doc.save_as(&mut worker, &crate::file_url(&copy), kind)
.expect("saves");
}
for name in ["plain.fodp", "plain.odp", "plain.pptx"] {
let doc = worker
.load(&crate::file_url(&dir.path().join(name)))
.expect("loads");
let read = show::notes(&worker.values(&doc, show::NOTES).expect("reads")).expect("parses");
assert_eq!(
(read.text.as_str(), read.rich),
("Say this first", false),
"{name}"
);
}
// PowerPoint styles every run; new text keeps the look.
let deck = worker
.load(&crate::file_url(&dir.path().join("plain.pptx")))
.expect("loads");
worker
.run(&deck, "notes.set", &["Then the plan", "0"])
.expect("sets");
let again = dir.path().join("again.fodp");
deck.save_as(&mut worker, &crate::file_url(&again), "fodp")
.expect("saves");
let xml = std::fs::read_to_string(&again).expect("reads");
let span = xml
.split("Then the plan")
.next()
.expect("text")
.rsplit("<text:span text:style-name=\"")
.next();
let style = span
.and_then(|s| s.split('"').next())
.expect("a styled span");
let def = xml
.split(&format!("<style:style style:name=\"{style}\""))
.nth(1)
.expect("its style");
let def = def.split("</style:style>").next().expect("ends");
assert!(
def.contains(r#"fo:font-size="20pt""#) && def.contains("Arial"),
"{def}"
);
// Make one word bold, as another editor would.
let bold = r#"<style:style style:name="Bold" style:family="text"><style:text-properties fo:font-weight="bold"/></style:style>"#;
let xml = std::fs::read_to_string(&out)
.expect("reads")
.replacen(
"<office:automatic-styles>",
&format!("<office:automatic-styles>{bold}"),
1,
)
.replacen(
"<text:p>Say this first</text:p>",
r#"<text:p>Say <text:span text:style-name="Bold">this</text:span> first</text:p>"#,
1,
);
let rich = dir.path().join("rich.fodp");
std::fs::write(&rich, xml).expect("writes");
let doc = worker.load(&crate::file_url(&rich)).expect("loads");
let read = show::notes(&worker.values(&doc, show::NOTES).expect("reads")).expect("parses");
assert_eq!((read.text.as_str(), read.rich), ("Say this first", true));
notes_set(&mut worker, &doc, &["Plain", "0"])
.expect_err("refuses");
let kept = show::notes(&worker.values(&doc, show::NOTES).expect("reads")).expect("parses");
assert_eq!(
kept.text, "Say this first",
"varied formatting is not overwritten"
);
}
#[test]
fn notes_keep_one_paragraph_look_and_refuse_two() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_deck();
notes_set(&mut worker, &doc, &["One\nTwo", "0"])
.expect("sets");
let out = dir.path().join("two.fodp");
doc.save_as(&mut worker, &crate::file_url(&out), "fodp")
.expect("saves");
let end = r#"<style:style style:name="End" style:family="paragraph"><style:paragraph-properties fo:text-align="end"/></style:style>"#;
let styled = |one: &str, two: &str| {
std::fs::read_to_string(&out)
.expect("reads")
.replacen(
"<office:automatic-styles>",
&format!("<office:automatic-styles>{end}"),
1,
)
.replacen("<text:p>One</text:p>", one, 1)
.replacen("<text:p>Two</text:p>", two, 1)
};
let both = r#"<text:p text:style-name="End">One</text:p>"#;
let both = styled(both, &both.replace("One", "Two"));
let path = dir.path().join("both.fodp");
std::fs::write(&path, both).expect("writes");
let deck = worker.load(&crate::file_url(&path)).expect("loads");
let read = show::notes(&worker.values(&deck, show::NOTES).expect("reads")).expect("parses");
assert!(!read.rich, "one look throughout");
worker
.run(&deck, "notes.set", &["Three", "0"])
.expect("sets");
let again = dir.path().join("again.fodp");
deck.save_as(&mut worker, &crate::file_url(&again), "fodp")
.expect("saves");
let xml = std::fs::read_to_string(&again).expect("reads");
let tag = xml.split(">Three<").next().expect("text");
let style = tag.rsplit("text:style-name=\"").next().expect("a style");
let style = style.split('"').next().expect("its name");
let def = xml
.split(&format!("<style:style style:name=\"{style}\""))
.nth(1)
.expect("its definition");
let def = def.split("</style:style>").next().expect("ends");
assert!(def.contains(r#"fo:text-align="end""#), "{def}");
// One paragraph aligned, one not: plain text would lose it.
let one = styled(
r#"<text:p text:style-name="End">One</text:p>"#,
"<text:p>Two</text:p>",
);
let path = dir.path().join("one.fodp");
std::fs::write(&path, one).expect("writes");
let deck = worker.load(&crate::file_url(&path)).expect("loads");
let read = show::notes(&worker.values(&deck, show::NOTES).expect("reads")).expect("parses");
assert!(read.rich, "the look varies");
worker
.run(&deck, "notes.set", &["Three", "0"])
.expect_err("refuses");
}
+192
View File
@@ -0,0 +1,192 @@
use super::input::{open, saved};
use super::*;
use crate::review;
const TEXT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
<office:body><office:text><text:p>The cat saw a Cat and a dog. Teh cat ran wiht cats.</text:p></office:text></office:body>
</office:document>"#;
const WAIT: std::time::Duration = std::time::Duration::from_secs(5);
/// Runs a search and returns its matches.
fn search(worker: &mut Worker, doc: &Doc, seen: &mut Events, id: &str, values: &[&str]) {
let before = seen.searched;
worker
.run(doc, id, values)
.unwrap_or_else(|error| panic!("{id}: {error}"));
*seen = poll_until(worker, doc, seen, WAIT, |seen| seen.searched > before);
assert!(seen.searched > before, "{id} reports an outcome");
}
/// Right-clicks at a point and returns the kernel's menu.
fn menu(worker: &mut Worker, doc: &Doc, seen: &mut Events, (x, y): (i32, i32)) -> Option<String> {
click(worker, doc, x, y);
for kind in [0, 1] {
let event = Mouse {
kind,
x,
y,
count: 1,
buttons: 4,
modifiers: 0,
};
worker.post_mouse(doc, event).expect("the click posts");
}
*seen = poll_until(worker, doc, seen, WAIT, |seen| seen.menu.is_some());
seen.menu.take()
}
#[test]
fn find_counts_steps_and_replaces() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(TEXT);
click(&mut worker, &doc, 150, 150);
let mut seen = Events::default();
let find = |all: &'static str, case: &'static str, word: &'static str| {
["cat", "false", all, case, word, "1"]
};
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&find("1", "256", "0"),
);
assert_eq!(seen.found.len(), 4, "any case, inside words too");
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&find("1", "0", "0"),
);
assert_eq!(seen.found.len(), 3, "match case");
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&find("1", "256", "16"),
);
assert_eq!(seen.found.len(), 3, "whole words");
let all = seen.found.clone();
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&find("0", "256", "16"),
);
assert_eq!(seen.found, all[..1], "next selects the first");
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&["zebra", "false", "0", "256", "0", "1"],
);
assert!(
seen.found.is_empty(),
"no match is an outcome, not an error"
);
let replace = ["Cat", "false", "3", "0", "16", "1", "Lion"];
worker
.run(&doc, "find.replace", &replace)
.expect("replace all");
let counts = review::counts(&worker.values(&doc, ".uno:WordCount").expect("counts"))
.expect("counts parse");
assert_eq!((counts.words, counts.selected_words), (13, 0));
let text = saved(&dir, &mut worker, &doc, "found.fodt");
assert!(
text.contains("The cat saw a Lion and a dog."),
"only the cased whole word goes"
);
}
#[test]
fn spelling_suggests_and_ignores() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(TEXT);
click(&mut worker, &doc, 150, 150);
let mut seen = Events::default();
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&["Teh", "false", "0", "0", "0", "1"],
);
let (x, y, _, h) = seen.found[0];
let json = menu(&mut worker, &doc, &mut seen, (x + 60, y + h / 2)).expect("a menu");
let spelling = review::spelling(&json)
.expect("the menu parses")
.expect("a spelling menu");
let (_, rule) = spelling
.suggestions
.iter()
.find(|(label, _)| label == "The")
.expect("The is offered");
worker
.run(&doc, "spell.apply", &[rule])
.expect("the suggestion applies");
search(
&mut worker,
&doc,
&mut seen,
"find.run",
&["wiht", "false", "0", "0", "0", "1"],
);
let (x, y, _, h) = seen.found[0];
let json = menu(&mut worker, &doc, &mut seen, (x + 60, y + h / 2)).expect("a menu");
assert!(review::spelling(&json).expect("parses").is_some());
worker
.run(&doc, "spell.ignore_all", &["Spelling"])
.expect("ignore all");
let json = menu(&mut worker, &doc, &mut seen, (x + 60, y + h / 2)).expect("a menu");
assert_eq!(
review::spelling(&json).expect("parses"),
None,
"an ignored word is no longer wrong"
);
let text = saved(&dir, &mut worker, &doc, "spelled.fodt");
assert!(text.contains("The cat ran wiht"), "the suggestion lands");
}
#[test]
fn compare_marks_changes_against_an_older_file() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open(TEXT);
let older = dir.path().join("older.fodt");
let before = TEXT.replace("a dog", "a bird");
std::fs::write(&older, &before).expect("the older file writes");
worker
.run(&doc, "doc.compare", &[&crate::file_url(&older), "true"])
.expect("the compare runs");
let changes = review::changes(
&worker
.values(&doc, ".uno:AcceptTrackedChanges")
.expect("changes"),
)
.expect("changes parse");
assert!(
changes
.iter()
.any(|change| change.description.contains("dog")),
"the newer words show as changes: {changes:?}"
);
assert_eq!(
std::fs::read_to_string(&older).expect("reads"),
before,
"the older file stays"
);
}
+258
View File
@@ -0,0 +1,258 @@
use super::sheet::{SHEETS, open_book};
use super::*;
use crate::sheet;
/// How long a command may take to report.
const SETTLE: std::time::Duration = std::time::Duration::from_secs(5);
fn names(worker: &mut Worker, doc: &Doc) -> Vec<(String, bool)> {
doc.sheets(worker)
.expect("the sheets")
.list
.into_iter()
.map(|sheet| (sheet.name, sheet.visible))
.collect()
}
/// Runs `id` as an app does, at a fresh read.
fn run(worker: &mut Worker, doc: &Doc, id: &str, values: &[&str]) {
let at = worker.now(doc).expect("the state");
worker
.run(&at, id, values)
.unwrap_or_else(|error| panic!("{id} {values:?}: {error}"));
}
fn geometry(worker: &mut Worker, doc: &Doc) -> sheet::Geometry {
sheet::geometry(&worker.values(doc, sheet::GEOMETRY).expect("the geometry"))
.expect("the geometry parses")
}
#[test]
fn sheets_insert_rename_move_hide_and_delete() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_book(SHEETS);
let owned = |list: &[(&str, bool)]| -> Vec<(String, bool)> {
list.iter()
.map(|&(name, shown)| (name.to_string(), shown))
.collect()
};
let refs = sheet::references(
&worker
.values(&doc, &sheet::references_query(0))
.expect("the references"),
)
.expect("they parse");
assert_eq!((refs.formulas, refs.names), (1, 0), "U refers to S");
assert_eq!(refs.dynamic, 1, "INDIRECT on U is counted apart");
assert!(
refs.first.contains("U"),
"the first is on U: {}",
refs.first
);
run(&mut worker, &doc, "sheet.insert", &["New", "2"]);
run(&mut worker, &doc, "sheet.rename", &["Data", "2"]);
assert_eq!(
names(&mut worker, &doc),
owned(&[("S", true), ("Data", true), ("T", false), ("U", true)])
);
doc.show_sheet(&mut worker, 1).expect("Data shows");
run(&mut worker, &doc, "sheet.move", &["5", "false", "true"]);
run(&mut worker, &doc, "sheet.move", &["5", "true", "true"]);
let list = names(&mut worker, &doc);
assert_eq!(list[..3], owned(&[("S", true), ("T", false), ("U", true)]));
assert_eq!(list[3].0, "Data");
assert!(list[4].0.starts_with("Data"), "a copy: {}", list[4].0);
doc.show_sheet(&mut worker, 0).expect("S shows");
run(&mut worker, &doc, "sheet.move", &["2", "false", "true"]);
let order = |worker: &mut Worker| -> Vec<String> {
names(worker, &doc)
.into_iter()
.map(|(name, _)| name)
.collect()
};
assert_eq!(
order(&mut worker)[..3],
["T", "S", "U"],
"Index i+2 moves right"
);
run(&mut worker, &doc, "sheet.move", &["1", "false", "true"]);
assert_eq!(
order(&mut worker)[..3],
["S", "T", "U"],
"Index i moves left"
);
run(&mut worker, &doc, "sheet.hide", &["2"]);
run(&mut worker, &doc, "sheet.show", &["T"]);
let list = names(&mut worker, &doc);
assert_eq!(list[1], ("T".to_string(), true), "T shows");
assert_eq!(list[2], ("U".to_string(), false), "U hides");
run(&mut worker, &doc, "sheet.delete", &["1"]);
assert_eq!(names(&mut worker, &doc)[0].0, "T", "S is gone");
}
/// A 1, 2 column to fill, and cells to merge.
const GRID: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="G">
<table:table-row><table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell><table:table-cell><text:p>b</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:table-cell></table:table-row>
</table:table></office:spreadsheet></office:body>
</office:document>"#;
#[test]
fn ranges_fill_size_hide_merge_and_take_formulas() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_book(GRID);
run(&mut worker, &doc, "cell.goto", &["A1:A2"]);
run(&mut worker, &doc, "fill.auto", &["A5"]);
run(&mut worker, &doc, "cell.goto", &["C1"]);
run(&mut worker, &doc, "cell.enter", &["=SUM(A1:A5)"]);
run(&mut worker, &doc, "cell.goto", &["C1"]);
let summed = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
seen.cell.address == "C1" && seen.cell.formula == "=SUM(A1:A5)"
});
assert_eq!(summed.cell.formula, "=SUM(A1:A5)");
run(&mut worker, &doc, "cell.goto", &["F1:H1"]);
run(&mut worker, &doc, "columns.width_selected", &["3000"]);
run(&mut worker, &doc, "columns.width", &["2540", "4"]);
run(&mut worker, &doc, "cell.goto", &["E1"]);
run(&mut worker, &doc, "columns.hide", &[]);
let sizes = geometry(&mut worker, &doc);
assert_eq!(sizes.columns.size(3), 1440, "D is 1 inch wide");
assert_eq!(sizes.columns.size(4), 0, "E hides");
assert_eq!(
(5..8)
.map(|column| sizes.columns.size(column))
.collect::<Vec<_>>(),
[1701, 1701, 1701],
"F to H all take 3 cm"
);
run(&mut worker, &doc, "select.column", &["1", "0"]);
run(&mut worker, &doc, "select.row", &["2", "4096"]);
run(&mut worker, &doc, "cell.goto", &["B2"]);
run(&mut worker, &doc, "view.freeze", &[]);
let frozen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
let state = |uno: &str| {
seen.states
.iter()
.rev()
.find(|(name, _)| name == uno)
.map(|(_, state)| state.clone())
};
state(".uno:FreezePanesColumn").as_deref() == Some("1 / 0")
&& state(".uno:FreezePanesRow").as_deref() == Some("1 / 0")
});
assert!(
frozen
.states
.iter()
.any(|(name, state)| name == ".uno:FreezePanesRow" && state == "1 / 0"),
"B2 freezes one row and one column: {:?}",
frozen.states
);
run(&mut worker, &doc, "cell.goto", &["A1"]);
run(&mut worker, &doc, "rows.insert_above", &[]);
run(&mut worker, &doc, "cell.goto", &["A2:B2"]);
assert_eq!(
doc.selection_text(&mut worker)
.expect("the text")
.trim_end(),
"1\tb",
"two cells hold data"
);
run(&mut worker, &doc, "cells.merge", &["true"]);
let out = dir.path().join("out.fods");
doc.save_as(&mut worker, &crate::file_url(&out), "fods")
.expect("the save");
let xml = std::fs::read_to_string(&out).expect("the save reads");
assert!(
xml.contains("table:number-columns-spanned=\"2\""),
"A2:B2 merges"
);
assert!(
xml.contains("of:=SUM([.A2:.A6])"),
"the formula follows the inserted row"
);
assert!(
xml.contains("office:value=\"14\""),
"the fill reaches 5; the merged text drops out of the sum"
);
assert!(xml.contains("<text:p>1 b</text:p>"), "the contents move");
}
#[test]
fn two_workbooks_keep_their_own_sheets() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, first) = open_book(SHEETS);
first.show_sheet(&mut worker, 2).expect("U shows");
let grid = dir.path().join("grid.fods");
std::fs::write(&grid, GRID).expect("the grid writes");
let second = worker
.load(&crate::file_url(&grid))
.expect("the second book loads");
first.show_sheet(&mut worker, 0).expect("S shows");
assert_eq!(first.sheets(&mut worker).expect("sheets").current, 0);
assert_eq!(second.sheets(&mut worker).expect("sheets").current, 0);
run(&mut worker, &first, "cell.goto", &["C1"]);
run(&mut worker, &first, "cell.enter", &["123456"]);
let out = dir.path().join("first.fods");
first
.save_as(&mut worker, &crate::file_url(&out), "fods")
.expect("the save");
let xml = std::fs::read_to_string(&out).expect("the save reads");
let on_s = &xml[..xml.find("table:name=\"T\"").expect("sheet T")];
assert!(
on_s.contains("office:value=\"123456\""),
"the entry lands on S"
);
}
#[test]
fn a_sheet_by_number_needs_the_state_it_was_read_in() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_book(SHEETS);
let read = worker.now(&doc).expect("the state");
worker.run(&read, "sheet.delete", &["1"]).expect("deletes S");
// Sheet 2 was T when read; it is U now.
let stale = worker.run(&read, "sheet.rename", &["Renamed", "2"]).expect_err("an older state");
assert!(crate::is_stale(&stale), "{stale}");
let only = |worker: &mut Worker| names(worker, &doc).into_iter().map(|(name, _)| name).collect::<Vec<_>>();
assert_eq!(only(&mut worker), ["T", "U"], "nothing was renamed");
run(&mut worker, &doc, "sheet.rename", &["Renamed", "2"]);
assert_eq!(only(&mut worker), ["T", "Renamed"]);
// A loaded handle never names a sheet after edits.
assert!(worker.run(&doc, "sheet.delete", &["1"]).is_err());
}
#[test]
fn commands_from_one_read_run_together_and_hovering_changes_nothing() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_book(SHEETS);
let read = worker.now(&doc).expect("the state");
let hover = crate::Mouse { kind: 2, x: 500, y: 500, count: 0, buttons: 0, modifiers: 0 };
worker.post_mouse(&read, hover).expect("hovers");
assert_eq!(worker.now(&doc).expect("the state"), read, "a hover is no change");
// Both numbers come from one read.
let renames: [(&str, &[&str]); 2] = [("sheet.rename", &["One", "1"]), ("sheet.rename", &["Two", "2"])];
worker.run_all(&read, &renames).expect("renames both");
let only = |worker: &mut Worker| names(worker, &doc).into_iter().map(|(name, _)| name).collect::<Vec<_>>();
assert_eq!(only(&mut worker), ["One", "Two", "U"]);
let stale = worker.run(&read, "sheet.rename", &["Three", "3"]).expect_err("an older state");
assert!(crate::is_stale(&stale), "{stale}");
assert_eq!(only(&mut worker), ["One", "Two", "U"], "nothing else was renamed");
}
+387
View File
@@ -0,0 +1,387 @@
//! UI operations mapped to kernel commands (LOK-02, LOK-12).
use std::io;
mod analysis;
mod calc;
mod data;
mod draw;
mod layout;
mod page;
mod refs;
mod sheet;
mod show;
mod text;
mod tools;
/// One argument: its LOK name and what values it takes.
#[derive(Debug, PartialEq)]
pub enum Arg {
Text(&'static str),
/// Text that may be empty.
Loose(&'static str),
/// A family the kernel lists under `.uno:CharFontName`.
Font(&'static str),
/// Points, 1 to 999, in the kernel's 0.05 steps.
Points(&'static str),
/// A whole number of LOK type `kind` within `min..=max`.
Int(&'static str, &'static str, i64, i64),
Bool(&'static str),
/// A fixed border line, solid or none; takes no value.
Line(&'static str, bool),
}
/// How the worker confirms the kernel did the command.
#[derive(Debug, PartialEq)]
pub enum Check {
/// The completion result reports success.
Result,
/// The kernel's `<uno>Count` history drops by one.
History,
/// The command's state then equals the first value.
Reports,
/// The undo history gains a step.
Undoable,
/// The second value's style family then lists the first.
Listed,
/// The selected image then reports crop mode.
Cropping,
/// The kernel finished; the outcome shows elsewhere.
Finished,
}
/// One UI operation: kernel command, arguments, confirmation.
#[derive(Debug, PartialEq)]
pub struct Command {
pub id: &'static str,
pub uno: &'static str,
pub args: &'static [Arg],
pub check: Check,
}
/// Arguments that count things as a read saw them.
const NUMBERED: &[&str] = &[
"Index", "nTabNumber", "TabNo", "Part", "Row", "Col", "Column", "StartColumn", "StartRow", "EndColumn", "EndRow",
];
impl Command {
/// Names something the document numbers, as read.
pub fn addressed(&self, values: &[&str]) -> bool {
// An index of -1 names nothing: a new tab stop.
self.args.iter().zip(values).any(|(arg, value)| matches!(arg, Arg::Int(name, ..) if NUMBERED.contains(name)) && *value != "-1")
}
/// This command with `values`, checked now (LOK-02).
#[cfg(feature = "view")]
pub(crate) fn owned(&self, values: &[&str]) -> io::Result<(&'static str, Vec<String>)> {
self.args_json(values)?;
Ok((self.id, values.iter().map(|value| value.to_string()).collect()))
}
}
pub(crate) const fn command(
id: &'static str,
uno: &'static str,
args: &'static [Arg],
check: Check,
) -> Command {
Command {
id,
uno,
args,
check,
}
}
/// The command table, in groups.
pub const COMMANDS: &[&[Command]] = &[
text::ROWS,
layout::ROWS,
refs::ROWS,
tools::ROWS,
sheet::ROWS,
calc::ROWS,
data::ROWS,
analysis::ROWS,
page::ROWS,
show::ROWS,
draw::ROWS,
];
/// Every row of the table.
pub fn all() -> impl Iterator<Item = &'static Command> {
COMMANDS.iter().flat_map(|group| group.iter())
}
/// Kernel lists Ely reads: fonts, styles, undo history.
pub const VALUES: &[&str] = &[
".uno:CharFontName",
".uno:StyleApply",
".uno:Undo",
".uno:Redo",
".uno:ViewAnnotations",
".uno:AcceptTrackedChanges",
".uno:Bookmarks",
".uno:Formula",
".uno:WordCount",
".uno:Outline",
crate::sheet::GEOMETRY,
crate::sheet::NAMES,
crate::sheet::SELECTED,
crate::sheet::VALIDATION,
crate::sheet::FORMATS,
crate::sheet::NUMBER,
crate::sheet::CHART,
crate::sheet::PIVOT,
crate::sheet::LAYOUT,
crate::sheet::PROTECTION,
crate::sheet::LINKS,
crate::show::DESIGN,
crate::show::OBJECTS,
crate::show::NOTES,
crate::show::TRANSITION,
crate::show::ANIMATIONS,
crate::show::MEDIA,
crate::show::SLIDE_SHOW,
crate::show::SLIDE_CHECK,
];
/// Reads that take `?key=value` arguments.
pub const QUERIES: &[&str] = &[
".uno:SheetReferences",
crate::sheet::NAMES,
crate::sheet::NUMBER,
crate::sheet::FILTER,
crate::sheet::LIST,
];
/// The kernel's font families, from `.uno:CharFontName`.
pub fn fonts(json: &str) -> io::Result<Vec<String>> {
let list = parse(json)?;
let fonts = list["commandValues"]
.as_object()
.ok_or_else(|| invalid("the font list has no families".into()))?;
Ok(fonts.keys().cloned().collect())
}
/// One style family: 1 character, 2 paragraph, 8 page.
pub fn styles(json: &str, family: &str) -> io::Result<Vec<String>> {
let key = match family {
"1" => "CharacterStyles",
"2" => "ParagraphStyles",
"8" => "PageStyles",
_ => return Err(invalid(format!("no style family {family}"))),
};
let list = parse(json)?;
list["commandValues"][key]
.as_array()
.ok_or_else(|| invalid(format!("the style list has no {key}")))?
.iter()
.map(|name| {
name.as_str()
.map(str::to_string)
.ok_or_else(|| invalid(format!("a bad {key} entry: {name}")))
})
.collect()
}
fn parse(json: &str) -> io::Result<serde_json::Value> {
serde_json::from_str(json).map_err(|error| invalid(format!("a bad kernel list: {error}")))
}
/// The command for a UI id.
pub fn find(id: &str) -> io::Result<&'static Command> {
all()
.find(|command| command.id == id)
.ok_or_else(|| invalid(format!("no command {id}")))
}
fn invalid(message: String) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
impl Command {
/// The LOK argument JSON for `values`, checked by kind.
pub fn args_json(&self, values: &[&str]) -> io::Result<Option<String>> {
let (lines, taking): (Vec<&Arg>, Vec<&Arg>) = self
.args
.iter()
.partition(|arg| matches!(arg, Arg::Line(..)));
if values.len() != taking.len() {
return Err(invalid(format!(
"{} takes {} values",
self.id,
taking.len()
)));
}
if self.args.is_empty() {
return Ok(None);
}
let mut json = serde_json::Map::new();
for arg in lines {
if let Arg::Line(name, solid) = arg {
json.insert((*name).to_string(), line_json(*solid));
}
}
for (arg, value) in taking.into_iter().zip(values) {
let (name, kind) = match arg {
Arg::Text(name) | Arg::Font(name) | Arg::Loose(name) => (name, "string"),
Arg::Points(name) => (name, "float"),
Arg::Int(name, kind, _, _) => (name, *kind),
Arg::Bool(name) => (name, "boolean"),
Arg::Line(..) => unreachable!("lines take no value"),
};
if value.trim().is_empty() && !matches!(arg, Arg::Loose(_)) {
return Err(invalid(format!("{} needs {name}", self.id)));
}
match arg {
Arg::Points(_) => check_points(name, value)?,
Arg::Int(_, _, min, max) => {
let number: i64 = value
.parse()
.map_err(|_| invalid(format!("{name} is not a whole number: {value}")))?;
if !(*min..=*max).contains(&number) {
return Err(invalid(format!("{name} is out of {min}..{max}: {value}")));
}
}
Arg::Bool(_) if !matches!(*value, "true" | "false") => {
return Err(invalid(format!("{name} is not true or false: {value}")));
}
_ => {}
}
json.insert(
(*name).to_string(),
serde_json::json!({ "type": kind, "value": value }),
);
}
Ok(Some(serde_json::Value::Object(json).to_string()))
}
}
/// A border line as LOK takes it: color, widths, style.
fn line_json(solid: bool) -> serde_json::Value {
let width = if solid { "18" } else { "0" };
let parts = ["0", "0", width, "0", "0", width];
let value: Vec<_> = parts
.iter()
.map(|part| serde_json::json!({ "type": "long", "value": part }))
.collect();
serde_json::json!({ "type": "[]any", "value": value })
}
/// A plain decimal in 0.05 steps from 1 to 999.
fn check_points(name: &str, value: &str) -> io::Result<()> {
let (whole, fraction) = value.split_once('.').unwrap_or((value, "0"));
let digits = |text: &str| text.bytes().all(|byte| byte.is_ascii_digit());
if whole.is_empty()
|| whole.len() > 3
|| !digits(whole)
|| fraction.is_empty()
|| fraction.len() > 2
|| !digits(fraction)
{
return Err(invalid(format!("{name} is not a plain decimal: {value}")));
}
let hundredths: u32 = format!("{whole}{fraction:0<2}")
.parse()
.map_err(|_| invalid(format!("{name} is not a number: {value}")))?;
if !(100..=99_900).contains(&hundredths) {
return Err(invalid(format!("{name} is out of 1..999: {value}")));
}
if !hundredths.is_multiple_of(5) {
return Err(invalid(format!("{name} takes 0.05 steps: {value}")));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_real_number_needs_the_read_state() {
let tab = find("paragraph.tab").expect("the tab stop row");
assert!(!tab.addressed(&["-1", "1134", "false"]), "a new stop names nothing");
assert!(tab.addressed(&["0", "0", "true"]), "removing stop 0 does");
assert!(find("sheet.delete").expect("the row").addressed(&["1"]));
assert!(!find("cell.enter").expect("the row").addressed(&["1"]));
assert!(find("notes.set").expect("the row").addressed(&["text", "1"]), "a slide by number");
assert!(find("select.row").expect("the row").addressed(&["3", "0"]), "a row by number");
assert!(!find("rows.height_selected").expect("the row").addressed(&["500"]), "a size names nothing");
}
#[test]
fn ids_are_unique_and_reported_names_too() {
let rows: Vec<&Command> = all().collect();
for (i, a) in rows.iter().enumerate() {
for b in &rows[i + 1..] {
assert_ne!(a.id, b.id);
if a.check == Check::Reports || b.check == Check::Reports {
assert_ne!(a.uno, b.uno, "a reported state names one row");
}
}
}
}
#[test]
fn border_lines_take_no_values() {
let all = find("table.borders_all").expect("mapped");
let json = all.args_json(&[]).expect("no values").expect("lines");
let parsed: serde_json::Value = serde_json::from_str(&json).expect("json");
assert_eq!(parsed["OuterBorder.LeftBorder"]["type"], "[]any");
assert_eq!(parsed["InnerBorder.Vertical"]["value"][2]["value"], "18");
let none = find("table.borders_none").expect("mapped");
let json = none.args_json(&[]).expect("no values").expect("lines");
assert!(json.contains("\"value\":\"0\""), "none is width 0");
assert!(all.args_json(&["x"]).is_err(), "lines refuse values");
}
#[test]
fn args_fill_in_order_and_check_kinds() {
let size = find("format.size").expect("mapped");
assert_eq!(
size.args_json(&["14"]).expect("one value").as_deref(),
Some(r#"{"FontHeight.Height":{"type":"float","value":"14"}}"#)
);
assert!(size.args_json(&[]).is_err(), "a missing value is refused");
assert!(
size.args_json(&["junk"]).is_err(),
"a non-number is refused"
);
assert!(size.args_json(&["0"]).is_err(), "out of range is refused");
assert!(
size.args_json(&["18.01"]).is_err(),
"finer than 0.05 is refused"
);
assert!(size.args_json(&["18.05"]).is_ok(), "0.05 steps pass");
for bad in ["18.05000001", "18.051", "1e1", "-5", "18.", ".5", "18.5x"] {
assert!(size.args_json(&[bad]).is_err(), "{bad} is refused");
}
assert!(size.args_json(&["999"]).is_ok() && size.args_json(&["1.5"]).is_ok());
assert!(
find("format.font")
.expect("mapped")
.args_json(&[" "])
.is_err()
);
let bold = find("format.bold").expect("mapped");
assert_eq!(bold.args_json(&[]).expect("none"), None);
assert!(find("format.dialog").is_err());
}
#[test]
fn kernel_lists_read_by_family() {
let fonts = r#"{"commandName":".uno:CharFontName","commandValues":{"Arial":["10"],"Noto Sans":[]}}"#;
assert_eq!(super::fonts(fonts).expect("fonts"), ["Arial", "Noto Sans"]);
let styles = r#"{"commandValues":{"CharacterStyles":["Emphasis"],"ParagraphStyles":["Title","Heading 1"]}}"#;
assert_eq!(styles_of(styles, "2"), ["Title", "Heading 1"]);
assert_eq!(styles_of(styles, "1"), ["Emphasis"]);
assert!(super::styles(styles, "3").is_err(), "no third family");
assert!(super::styles("{}", "2").is_err(), "a missing family fails");
assert!(super::fonts("not json").is_err());
}
fn styles_of(json: &str, family: &str) -> Vec<String> {
super::styles(json, family).expect("styles")
}
}
+47
View File
@@ -0,0 +1,47 @@
//! Spreadsheet rows: pivot tables and charts.
use super::{Arg, Check, Command, command};
/// Pivot tables and charts (TABLE-10, 11).
pub(super) const ROWS: &[Command] = &[
command(
"pivot.make",
".uno:DataPilotExec",
&[Arg::Text("Pivot")],
Check::Undoable,
),
command(
"pivot.refresh",
".uno:RecalcPivotTable",
&[],
Check::Finished,
),
command(
"pivot.delete",
".uno:DeletePivotTable",
&[],
Check::Undoable,
),
command(
"chart.insert",
".uno:InsertObjectChart",
&[
Arg::Text("RangeList"),
Arg::Bool("InNewTable"),
Arg::Text("Chart"),
],
Check::Undoable,
),
command(
"chart.change",
".uno:ChangeChartData",
&[
Arg::Text("Name"),
Arg::Text("Range"),
Arg::Bool("ColHeaders"),
Arg::Bool("RowHeaders"),
Arg::Text("Chart"),
],
Check::Undoable,
),
];
+41
View File
@@ -0,0 +1,41 @@
//! Spreadsheet rows: calculation, names, error tracing.
use super::{Arg, Check, Command, command};
/// Calculation, named ranges and tracing (TABLE-03..06).
pub(super) const ROWS: &[Command] = &[
command(
"calc.auto",
".uno:AutomaticCalculation",
&[Arg::Bool("AutomaticCalculation")],
Check::Finished,
),
command("calc.now", ".uno:Calculate", &[], Check::Finished),
command("calc.all", ".uno:CalculateHard", &[], Check::Finished),
command(
"names.define",
".uno:DefineName",
&[Arg::Text("Name"), Arg::Text("Symbol"), Arg::Loose("Scope")],
Check::Undoable,
),
command(
"names.remove",
".uno:DefineName",
&[Arg::Text("Name"), Arg::Loose("Scope")],
Check::Undoable,
),
command("trace.error", ".uno:ShowErrors", &[], Check::Undoable),
command(
"trace.precedents",
".uno:ShowPrecedents",
&[],
Check::Undoable,
),
command(
"trace.dependents",
".uno:ShowDependents",
&[],
Check::Undoable,
),
command("trace.clear", ".uno:ClearArrows", &[], Check::Undoable),
];
+185
View File
@@ -0,0 +1,185 @@
//! Spreadsheet rows: formats, data, rules.
use super::{Arg, Check, Command, command};
/// A column for sorting, from 1; 0 for none.
const fn key(name: &'static str) -> Arg {
Arg::Int(name, "long", 0, 16_384)
}
/// A row or column index, from 0.
const fn index(name: &'static str) -> Arg {
Arg::Int(name, "long", 0, 1_048_575)
}
/// Cell borders: the outer, the inner lines, or none.
const fn borders(id: &'static str, outer: bool, inner: bool) -> Command {
command(
id,
".uno:SetBorderStyle",
if inner {
&[
Arg::Line("OuterBorder.LeftBorder", true),
Arg::Line("OuterBorder.RightBorder", true),
Arg::Line("OuterBorder.TopBorder", true),
Arg::Line("OuterBorder.BottomBorder", true),
Arg::Line("InnerBorder.Horizontal", true),
Arg::Line("InnerBorder.Vertical", true),
]
} else if outer {
&[
Arg::Line("OuterBorder.LeftBorder", true),
Arg::Line("OuterBorder.RightBorder", true),
Arg::Line("OuterBorder.TopBorder", true),
Arg::Line("OuterBorder.BottomBorder", true),
Arg::Line("InnerBorder.Horizontal", false),
Arg::Line("InnerBorder.Vertical", false),
]
} else {
&[
Arg::Line("OuterBorder.LeftBorder", false),
Arg::Line("OuterBorder.RightBorder", false),
Arg::Line("OuterBorder.TopBorder", false),
Arg::Line("OuterBorder.BottomBorder", false),
Arg::Line("InnerBorder.Horizontal", false),
Arg::Line("InnerBorder.Vertical", false),
]
},
Check::Undoable,
)
}
/// Formats, sorting, filtering and rules (TABLE-07..09).
pub(super) const ROWS: &[Command] = &[
command(
"number.general",
".uno:NumberFormatStandard",
&[],
Check::Undoable,
),
command(
"number.decimal",
".uno:NumberFormatDecimal",
&[],
Check::Undoable,
),
command(
"number.currency",
".uno:NumberFormatCurrency",
&[],
Check::Undoable,
),
command(
"number.percent",
".uno:NumberFormatPercent",
&[],
Check::Undoable,
),
command("number.date", ".uno:NumberFormatDate", &[], Check::Undoable),
command(
"number.code",
".uno:NumberFormat",
&[Arg::Text("FormatCode")],
Check::Undoable,
),
command("align.left", ".uno:AlignLeft", &[], Check::Undoable),
command(
"align.center",
".uno:AlignHorizontalCenter",
&[],
Check::Undoable,
),
command("align.right", ".uno:AlignRight", &[], Check::Undoable),
command("align.justify", ".uno:AlignBlock", &[], Check::Undoable),
command("align.top", ".uno:AlignTop", &[], Check::Undoable),
command("align.middle", ".uno:AlignVCenter", &[], Check::Undoable),
command("align.bottom", ".uno:AlignBottom", &[], Check::Undoable),
command(
"cells.wrap",
".uno:WrapText",
&[Arg::Bool("WrapText")],
Check::Undoable,
),
borders("cells.borders_all", true, true),
borders("cells.borders_outer", true, false),
borders("cells.borders_none", false, false),
command(
"cells.fill",
".uno:BackgroundColor",
&[Arg::Int("BackgroundColor.Color", "long", -1, 0xFF_FFFF)],
Check::Undoable,
),
command(
"data.sort",
".uno:DataSort",
&[
Arg::Bool("HasHeader"),
key("Col1"),
Arg::Bool("Ascending1"),
key("Col2"),
Arg::Bool("Ascending2"),
key("Col3"),
Arg::Bool("Ascending3"),
],
Check::Undoable,
),
command(
"data.autofilter",
".uno:DataFilterAutoFilter",
&[],
Check::Undoable,
),
command(
"data.filter",
".uno:DataFilterStandardFilter",
&[Arg::Text("Query")],
Check::Undoable,
),
command(
"data.unfilter",
".uno:DataFilterRemoveFilter",
&[],
Check::Undoable,
),
command(
"data.dedupe",
".uno:HandleDuplicateRecords",
&[
Arg::Bool("Remove"),
Arg::Bool("IncludesHeaders"),
Arg::Bool("DuplicateRows"),
index("StartColumn"),
index("StartRow"),
index("EndColumn"),
index("EndRow"),
Arg::Int("TabNo", "long", 0, 9_999),
],
Check::Undoable,
),
command(
"data.columns",
".uno:TextToColumns",
&[Arg::Text("Options")],
Check::Undoable,
),
command("select.data", ".uno:SelectData", &[], Check::Finished),
command("paste.values", ".uno:PasteOnlyValue", &[], Check::Undoable),
command(
"paste.formulas",
".uno:PasteOnlyFormula",
&[],
Check::Undoable,
),
command(
"rules.validation",
".uno:Validation",
&[Arg::Text("Rule")],
Check::Undoable,
),
command(
"rules.conditional",
".uno:ConditionalFormatEasy",
&[Arg::Text("Rule")],
Check::Undoable,
),
];
+176
View File
@@ -0,0 +1,176 @@
//! Drawing rows: shapes, lines, fill, outline, arrangement.
use super::{Arg, Check, Command, command};
/// Slide objects (SHOW-03 to 06).
pub(super) const ROWS: &[Command] = &[
command(
"draw.text",
".uno:Text",
&[Arg::Bool("CreateDirectly")],
Check::Undoable,
),
command(
"draw.shape",
".uno:BasicShapes",
&[Arg::Text("BasicShapes"), Arg::Bool("CreateDirectly")],
Check::Undoable,
),
command("draw.line", ".uno:Line", &[], Check::Undoable),
command("draw.arrow", ".uno:LineArrowEnd", &[], Check::Undoable),
command("draw.connector", ".uno:Connector", &[], Check::Undoable),
command(
"object.fill",
".uno:FillColor",
&[Arg::Int("FillColor", "long", 0, 0xFF_FFFF)],
Check::Undoable,
),
command(
"object.fill_none",
".uno:FillStyle",
&[Arg::Int("FillStyle", "long", 0, 0)],
Check::Undoable,
),
command(
"object.line_none",
".uno:XLineStyle",
&[Arg::Int("XLineStyle", "long", 0, 0)],
Check::Undoable,
),
command(
"object.line_color",
".uno:XLineColor",
&[Arg::Int("XLineColor", "long", 0, 0xFF_FFFF)],
Check::Undoable,
),
command(
"object.line_width",
".uno:LineWidth",
&[Arg::Int("LineWidth", "long", 0, 5_000)],
Check::Undoable,
),
command(
"object.transparency",
".uno:FillTransparence",
&[Arg::Int("FillTransparence", "unsigned short", 0, 100)],
Check::Undoable,
),
command(
"object.shadow",
".uno:FillShadow",
&[Arg::Bool("FillShadow")],
Check::Undoable,
),
command(
"object.x",
".uno:TransformDialog",
&[Arg::Int("TransformPosX", "long", -1_000_000, 1_000_000)],
Check::Undoable,
),
command(
"object.y",
".uno:TransformDialog",
&[Arg::Int("TransformPosY", "long", -1_000_000, 1_000_000)],
Check::Undoable,
),
command(
"object.width",
".uno:TransformDialog",
&[Arg::Int("TransformWidth", "long", 1, 1_000_000)],
Check::Undoable,
),
command(
"object.height",
".uno:TransformDialog",
&[Arg::Int("TransformHeight", "long", 1, 1_000_000)],
Check::Undoable,
),
command(
"object.rotate",
".uno:TransformDialog",
&[
Arg::Int("TransformRotationAngle", "long", 0, 35_999),
Arg::Int("TransformRotationX", "long", -1_000_000, 1_000_000),
Arg::Int("TransformRotationY", "long", -1_000_000, 1_000_000),
],
Check::Undoable,
),
command(
"object.lock",
".uno:TransformDialog",
&[Arg::Bool("ProtectPos"), Arg::Bool("ProtectSize")],
Check::Finished,
),
command(
"object.select",
".uno:SelectObject",
&[Arg::Int("Index", "long", 0, 9_999), Arg::Bool("Add")],
Check::Finished,
),
command(
"object.deselect",
".uno:SelectObject",
&[Arg::Bool("Add")],
Check::Finished,
),
command(
"image.replace",
".uno:ChangePicture",
&[Arg::Text("FileName")],
Check::Undoable,
),
command("object.align_left", ".uno:ObjectAlignLeft", &[], Check::Undoable),
command("object.align_center", ".uno:AlignCenter", &[], Check::Undoable),
command("object.align_right", ".uno:ObjectAlignRight", &[], Check::Undoable),
command("object.align_top", ".uno:AlignUp", &[], Check::Undoable),
command("object.align_middle", ".uno:AlignMiddle", &[], Check::Undoable),
command("object.align_bottom", ".uno:AlignDown", &[], Check::Undoable),
command(
"object.spread_across",
".uno:DistributeHorzDistance",
&[],
Check::Undoable,
),
command(
"object.spread_down",
".uno:DistributeVertDistance",
&[],
Check::Undoable,
),
command("object.group", ".uno:FormatGroup", &[], Check::Undoable),
command("object.ungroup", ".uno:FormatUngroup", &[], Check::Undoable),
command(
"text.fit",
".uno:TextAutoFitToSize",
&[Arg::Text("Fit")],
Check::Undoable,
),
command("view.snap_grid", ".uno:GridUse", &[], Check::Finished),
command("view.snap_guides", ".uno:HelplinesUse", &[], Check::Finished),
command(
"guide.add",
".uno:CapturePoint",
&[
Arg::Int("Kind", "unsigned short", 0, 1),
Arg::Int("X", "long", -1_000_000, 1_000_000),
Arg::Int("Y", "long", -1_000_000, 1_000_000),
],
Check::Finished,
),
command(
"guide.move",
".uno:CapturePoint",
&[
Arg::Int("Index", "long", 0, 999),
Arg::Int("X", "long", -1_000_000, 1_000_000),
Arg::Int("Y", "long", -1_000_000, 1_000_000),
],
Check::Finished,
),
command(
"guide.delete",
".uno:CapturePoint",
&[Arg::Int("Index", "long", 0, 999), Arg::Bool("Delete")],
Check::Finished,
),
];
+271
View File
@@ -0,0 +1,271 @@
//! Layout rows: pages, headers, fields, tables, images.
use super::{Arg, Check, Command, command};
/// Page, table and object commands.
pub(super) const ROWS: &[Command] = &[
command(
"page.size",
".uno:AttributePageSize",
&[
Arg::Int("AttributePageSize.Width", "long", 1_000, 600_000),
Arg::Int("AttributePageSize.Height", "long", 1_000, 600_000),
],
Check::Undoable,
),
command(
"page.orientation",
".uno:AttributePageSize",
&[
Arg::Int("AttributePageSize.Width", "long", 1_000, 600_000),
Arg::Int("AttributePageSize.Height", "long", 1_000, 600_000),
Arg::Bool("AttributePage.Landscape"),
Arg::Int("AttributePage.Layout", "long", 0, 3),
Arg::Int("AttributePage.NumType", "long", 0, 99),
],
Check::Undoable,
),
command(
"page.margins_lr",
".uno:PageLRMargin",
&[
Arg::Int("Page.Left", "long", 0, 99_990),
Arg::Int("Page.Right", "long", 0, 99_990),
],
Check::Undoable,
),
command(
"page.margins_ul",
".uno:PageULMargin",
&[
Arg::Int("Page.Upper", "long", 0, 99_990),
Arg::Int("Page.Lower", "long", 0, 99_990),
],
Check::Undoable,
),
command(
"page.columns",
".uno:PageColumnType",
&[Arg::Int("PageColumnType", "short", 1, 3)],
Check::Undoable,
),
command("page.break", ".uno:InsertPagebreak", &[], Check::Undoable),
command(
"page.section",
".uno:InsertBreak",
&[Arg::Int("Kind", "short", 3, 3), Arg::Text("TemplateName")],
Check::Undoable,
),
command(
"header.on",
".uno:SwPageHeaderItem",
&[Arg::Bool("SwPageHeaderItem")],
Check::Undoable,
),
command(
"footer.on",
".uno:SwPageFooterItem",
&[Arg::Bool("SwPageFooterItem")],
Check::Undoable,
),
command(
"header.layout",
".uno:SwPageHeaderLayout",
&[Arg::Int("SwPageHeaderLayout", "short", 0, 3)],
Check::Undoable,
),
command(
"footer.layout",
".uno:SwPageFooterLayout",
&[Arg::Int("SwPageFooterLayout", "short", 0, 3)],
Check::Undoable,
),
command(
"field.page",
".uno:InsertPageNumberField",
&[],
Check::Undoable,
),
command(
"field.pages",
".uno:InsertPageCountField",
&[],
Check::Undoable,
),
command(
"table.insert",
".uno:InsertTable",
&[
Arg::Int("Columns", "unsigned short", 1, 99),
Arg::Int("Rows", "unsigned short", 1, 999),
],
Check::Undoable,
),
command(
"table.row_above",
".uno:InsertRowsBefore",
&[],
Check::Undoable,
),
command(
"table.row_below",
".uno:InsertRowsAfter",
&[],
Check::Undoable,
),
command(
"table.column_left",
".uno:InsertColumnsBefore",
&[],
Check::Undoable,
),
command(
"table.column_right",
".uno:InsertColumnsAfter",
&[],
Check::Undoable,
),
command("table.delete_rows", ".uno:DeleteRows", &[], Check::Undoable),
command(
"table.delete_columns",
".uno:DeleteColumns",
&[],
Check::Undoable,
),
command("table.delete", ".uno:DeleteTable", &[], Check::Undoable),
command("table.merge", ".uno:MergeCells", &[], Check::Undoable),
command("table.select", ".uno:SelectTable", &[], Check::Result),
command(
"table.split",
".uno:SplitCell",
&[Arg::Int("Amount", "long", 2, 9), Arg::Bool("Horizontal")],
Check::Undoable,
),
command(
"table.even_columns",
".uno:DistributeColumns",
&[],
Check::Undoable,
),
command(
"table.optimal_height",
".uno:SetOptimalRowHeight",
&[],
Check::Undoable,
),
command(
"table.even_rows",
".uno:DistributeRows",
&[],
Check::Undoable,
),
command(
"table.borders_all",
".uno:SetBorderStyle",
&[
Arg::Line("OuterBorder.LeftBorder", true),
Arg::Line("OuterBorder.RightBorder", true),
Arg::Line("OuterBorder.TopBorder", true),
Arg::Line("OuterBorder.BottomBorder", true),
Arg::Line("InnerBorder.Horizontal", true),
Arg::Line("InnerBorder.Vertical", true),
],
Check::Undoable,
),
command(
"table.borders_none",
".uno:SetBorderStyle",
&[
Arg::Line("OuterBorder.LeftBorder", false),
Arg::Line("OuterBorder.RightBorder", false),
Arg::Line("OuterBorder.TopBorder", false),
Arg::Line("OuterBorder.BottomBorder", false),
Arg::Line("InnerBorder.Horizontal", false),
Arg::Line("InnerBorder.Vertical", false),
],
Check::Undoable,
),
command(
"table.shading",
".uno:TableCellBackgroundColor",
&[Arg::Int(
"TableCellBackgroundColor.Color",
"long",
-1,
0xFF_FFFF,
)],
Check::Undoable,
),
command(
"table.repeat_heading",
".uno:HeadingRowsRepeat",
&[],
Check::Undoable,
),
command(
"table.row_split",
".uno:RowSplit",
&[Arg::Bool("RowSplit")],
Check::Undoable,
),
command(
"image.insert",
".uno:InsertGraphic",
&[Arg::Text("FileName")],
Check::Undoable,
),
command(
"image.anchor_page",
".uno:SetAnchorToPage",
&[],
Check::Undoable,
),
command(
"image.anchor_paragraph",
".uno:SetAnchorToPara",
&[],
Check::Undoable,
),
command(
"image.anchor_char",
".uno:SetAnchorAtChar",
&[],
Check::Undoable,
),
command(
"image.anchor_as_char",
".uno:SetAnchorToChar",
&[],
Check::Undoable,
),
command("image.wrap_off", ".uno:WrapOff", &[], Check::Undoable),
command("image.wrap_on", ".uno:WrapOn", &[], Check::Undoable),
command("image.wrap_ideal", ".uno:WrapIdeal", &[], Check::Undoable),
command("image.wrap_left", ".uno:WrapLeft", &[], Check::Undoable),
command("image.wrap_right", ".uno:WrapRight", &[], Check::Undoable),
command(
"image.wrap_through",
".uno:WrapThrough",
&[],
Check::Undoable,
),
command("image.front", ".uno:BringToFront", &[], Check::Undoable),
command("image.back", ".uno:SendToBack", &[], Check::Undoable),
command(
"image.forward",
".uno:ObjectForwardOne",
&[],
Check::Undoable,
),
command("image.backward", ".uno:ObjectBackOne", &[], Check::Undoable),
command("image.crop", ".uno:Crop", &[], Check::Cropping),
command(
"image.size",
".uno:TransformDialog",
&[
Arg::Int("TransformWidth", "uint32", 57, 340_000),
Arg::Int("TransformHeight", "uint32", 57, 340_000),
],
Check::Undoable,
),
];
+54
View File
@@ -0,0 +1,54 @@
//! Spreadsheet rows: printing and protection.
use super::{Arg, Check, Command, command};
/// Print layout, breaks and protection (TABLE-14, 15).
pub(super) const ROWS: &[Command] = &[
command(
"print.area",
".uno:ChangePrintArea",
&[
Arg::Loose("PrintArea"),
Arg::Loose("PrintRepeatRow"),
Arg::Loose("PrintRepeatCol"),
],
Check::Undoable,
),
command(
"page.setup",
".uno:PageFormatDialog",
&[Arg::Text("Page")],
Check::Undoable,
),
command("break.row", ".uno:InsertRowBreak", &[], Check::Undoable),
command(
"break.column",
".uno:InsertColumnBreak",
&[],
Check::Undoable,
),
command(
"break.row_remove",
".uno:DeleteRowbreak",
&[],
Check::Undoable,
),
command(
"break.column_remove",
".uno:DeleteColumnbreak",
&[],
Check::Undoable,
),
command(
"sheet.protect",
".uno:Protect",
&[Arg::Text("Protection")],
Check::Undoable,
),
command(
"cells.lock",
".uno:CellProtection",
&[Arg::Bool("CellProtection")],
Check::Reports,
),
];
+93
View File
@@ -0,0 +1,93 @@
//! Reference and review rows: notes, marks, formulas, comments.
use super::{Arg, Check, Command, command};
/// Reference, comment and tracked-change commands.
pub(super) const ROWS: &[Command] = &[
command("note.footnote", ".uno:InsertFootnote", &[], Check::Undoable),
command("note.endnote", ".uno:InsertEndnote", &[], Check::Undoable),
command(
"bookmark.insert",
".uno:InsertBookmark",
&[Arg::Text("Bookmark")],
Check::Undoable,
),
command(
"link.insert",
".uno:SetHyperlink",
&[Arg::Text("Hyperlink.Text"), Arg::Text("Hyperlink.URL")],
Check::Undoable,
),
command(
"reference.insert",
".uno:InsertField",
&[
Arg::Int("Type", "unsigned short", 13, 13),
Arg::Int("SubType", "unsigned short", 2, 2),
Arg::Text("Name"),
Arg::Int("Format", "uint32", 0, 3),
],
Check::Undoable,
),
command(
"index.insert",
".uno:InsertMultiIndex",
&[Arg::Text("Title")],
Check::Undoable,
),
command(
"index.update",
".uno:UpdateAllIndexes",
&[],
Check::Undoable,
),
command(
"caption.insert",
".uno:InsertCaptionDialog",
&[Arg::Text("Category"), Arg::Text("Text")],
Check::Undoable,
),
command(
"formula.insert",
".uno:InsertObjectStarMath",
&[Arg::Text("Formula")],
Check::Undoable,
),
command(
"comment.insert",
".uno:InsertAnnotation",
&[Arg::Text("Text")],
Check::Undoable,
),
command(
"comment.reply",
".uno:ReplyComment",
&[Arg::Text("Id"), Arg::Text("Text")],
Check::Undoable,
),
command("track.toggle", ".uno:TrackChanges", &[], Check::Result),
command(
"track.accept",
".uno:AcceptTrackedChange",
&[Arg::Int("AcceptTrackedChange", "uint32", 1, 4_294_967_295)],
Check::Undoable,
),
command(
"track.reject",
".uno:RejectTrackedChange",
&[Arg::Int("RejectTrackedChange", "uint32", 1, 4_294_967_295)],
Check::Undoable,
),
command(
"track.accept_all",
".uno:AcceptAllTrackedChanges",
&[],
Check::Undoable,
),
command(
"track.reject_all",
".uno:RejectAllTrackedChanges",
&[],
Check::Undoable,
),
];
+171
View File
@@ -0,0 +1,171 @@
//! Spreadsheet rows: sheets, cells, rows and columns.
use super::{Arg, Check, Command, command};
/// A sheet position, counted from 1.
const SHEET: Arg = Arg::Int("Index", "unsigned short", 1, 10000);
/// The selection modifier: none, Shift or the command key.
const MODIFIER: Arg = Arg::Int("Modifier", "short", 0, 0x3000);
/// Workbook and range editing commands (TABLE-01, TABLE-02).
pub(super) const ROWS: &[Command] = &[
command(
"sheet.insert",
".uno:Insert",
&[Arg::Text("Name"), SHEET],
Check::Undoable,
),
command(
"sheet.rename",
".uno:Name",
&[Arg::Text("Name"), SHEET],
Check::Undoable,
),
command(
"sheet.move",
".uno:Move",
&[SHEET, Arg::Bool("Copy"), Arg::Bool("UseCurrentDocument")],
Check::Undoable,
),
command(
"sheet.hide",
".uno:Hide",
&[Arg::Int("nTabNumber", "short", 0, 9999)],
Check::Undoable,
),
command(
"sheet.show",
".uno:Show",
&[Arg::Text("aTableName")],
Check::Undoable,
),
command("sheet.delete", ".uno:Remove", &[SHEET], Check::Undoable),
command(
"cell.goto",
".uno:GoToCell",
&[Arg::Text("ToPoint")],
Check::Result,
),
command(
"cell.enter",
".uno:EnterString",
&[Arg::Loose("StringName")],
Check::Undoable,
),
command(
"rows.insert_above",
".uno:InsertRowsBefore",
&[],
Check::Undoable,
),
command(
"rows.insert_below",
".uno:InsertRowsAfter",
&[],
Check::Undoable,
),
command(
"columns.insert_before",
".uno:InsertColumnsBefore",
&[],
Check::Undoable,
),
command(
"columns.insert_after",
".uno:InsertColumnsAfter",
&[],
Check::Undoable,
),
command("rows.delete", ".uno:DeleteRows", &[], Check::Undoable),
command("columns.delete", ".uno:DeleteColumns", &[], Check::Undoable),
// Flags: V shifts down, > shifts right.
command(
"cells.insert",
".uno:InsertCell",
&[Arg::Text("Flags")],
Check::Undoable,
),
// Flags: U shifts up, L shifts left.
command(
"cells.delete",
".uno:DeleteCell",
&[Arg::Text("Flags")],
Check::Undoable,
),
command(
"cells.merge",
".uno:MergeCells",
&[Arg::Bool("MoveContents")],
Check::Undoable,
),
command("cells.split", ".uno:SplitCell", &[], Check::Undoable),
command("view.freeze", ".uno:FreezePanes", &[], Check::Finished),
command("rows.hide", ".uno:HideRow", &[], Check::Undoable),
command("rows.show", ".uno:ShowRow", &[], Check::Undoable),
command("columns.hide", ".uno:HideColumn", &[], Check::Undoable),
command("columns.show", ".uno:ShowColumn", &[], Check::Undoable),
// Sizes in 1/100 mm; rows and columns from 1.
command(
"rows.height",
".uno:RowHeight",
&[
Arg::Int("RowHeight", "unsigned short", 1, 65535),
Arg::Int("Row", "long", 1, 1048576),
],
Check::Undoable,
),
command(
"columns.width",
".uno:ColumnWidth",
&[
Arg::Int("ColumnWidth", "unsigned short", 1, 65535),
Arg::Int("Column", "unsigned short", 1, 16384),
],
Check::Undoable,
),
// The same sizes for every selected row or column.
command(
"rows.height_selected",
".uno:RowHeight",
&[Arg::Int("RowHeight", "unsigned short", 1, 65535)],
Check::Undoable,
),
command(
"columns.width_selected",
".uno:ColumnWidth",
&[Arg::Int("ColumnWidth", "unsigned short", 1, 65535)],
Check::Undoable,
),
command(
"rows.optimal",
".uno:SetOptimalRowHeight",
&[Arg::Int("aExtraHeight", "unsigned short", 0, 0)],
Check::Undoable,
),
command(
"columns.optimal",
".uno:SetOptimalColumnWidth",
&[Arg::Int("aExtraWidth", "unsigned short", 0, 0)],
Check::Undoable,
),
// Rows and columns from 0.
command(
"select.column",
".uno:SelectColumn",
&[Arg::Int("Col", "long", 0, 16383), MODIFIER],
Check::Finished,
),
command(
"select.row",
".uno:SelectRow",
&[Arg::Int("Row", "long", 0, 1048575), MODIFIER],
Check::Finished,
),
command(
"fill.auto",
".uno:AutoFill",
&[Arg::Text("EndCell")],
Check::Undoable,
),
];
+110
View File
@@ -0,0 +1,110 @@
//! Presentation rows: slides, design, charts, notes, comments.
use super::{Arg, Check, Command, command};
/// Slide management and design (SHOW-01, 02).
pub(super) const ROWS: &[Command] = &[
command("slide.insert", ".uno:InsertPage", &[], Check::Undoable),
command(
"slide.duplicate",
".uno:DuplicatePage",
&[],
Check::Undoable,
),
command("slide.delete", ".uno:DeletePage", &[], Check::Undoable),
command("slide.hide", ".uno:HideSlide", &[], Check::Undoable),
command("slide.show", ".uno:ShowSlide", &[], Check::Undoable),
command("slide.up", ".uno:MovePageUp", &[], Check::Undoable),
command("slide.down", ".uno:MovePageDown", &[], Check::Undoable),
command("slide.first", ".uno:MovePageFirst", &[], Check::Undoable),
command("slide.last", ".uno:MovePageLast", &[], Check::Undoable),
command(
"slide.layout",
".uno:AssignLayout",
&[Arg::Int("WhatLayout", "long", 0, 34)],
Check::Undoable,
),
command(
"slide.size",
".uno:PageSize",
&[
Arg::Int("PageWidth", "long", 1000, 300_000),
Arg::Int("PageHeight", "long", 1000, 300_000),
Arg::Bool("ScaleObjects"),
],
Check::Undoable,
),
command(
"slide.master",
".uno:PresentationLayout",
&[Arg::Text("Master")],
Check::Undoable,
),
command(
"slide.theme",
".uno:ThemeDialog",
&[Arg::Text("ColorSet")],
Check::Undoable,
),
command("master.edit", ".uno:SlideMasterPage", &[], Check::Finished),
command(
"master.insert",
".uno:InsertMasterPage",
&[],
Check::Finished,
),
command("master.close", ".uno:CloseMasterView", &[], Check::Finished),
command(
"show.chart",
".uno:InsertObjectChart",
&[Arg::Text("Chart")],
Check::Undoable,
),
command(
"slide.transition",
".uno:SetSlideTransition",
&[Arg::Text("Transition")],
Check::Undoable,
),
command(
"animation.add",
".uno:AddAnimation",
&[Arg::Text("Animation")],
Check::Undoable,
),
command(
"animation.change",
".uno:ChangeAnimation",
&[Arg::Text("Animation")],
Check::Undoable,
),
command(
"media.insert",
".uno:InsertAVMedia",
&[
Arg::Text("URL"),
Arg::Bool("IsLink"),
Arg::Int("Width", "long", 1, 1_000_000),
Arg::Int("Height", "long", 1, 1_000_000),
],
Check::Undoable,
),
command(
"notes.set",
".uno:SlideNotes",
&[Arg::Loose("Text"), Arg::Int("Part", "long", 0, 9_999)],
Check::Undoable,
),
command(
"remark.edit",
".uno:EditAnnotation",
&[Arg::Text("Id"), Arg::Text("Text")],
Check::Undoable,
),
command(
"remark.delete",
".uno:DeleteAnnotation",
&[Arg::Text("Id")],
Check::Undoable,
),
];
+116
View File
@@ -0,0 +1,116 @@
//! Text rows: editing, characters, paragraphs, lists, styles.
use super::{Arg, Check, Command, command};
/// Editing, formatting and style commands.
pub(super) const ROWS: &[Command] = &[
command("edit.undo", ".uno:Undo", &[], Check::History),
command("edit.redo", ".uno:Redo", &[], Check::History),
command("edit.select_all", ".uno:SelectAll", &[], Check::Result),
command("format.bold", ".uno:Bold", &[], Check::Result),
command("format.italic", ".uno:Italic", &[], Check::Result),
command("format.underline", ".uno:Underline", &[], Check::Result),
command("format.strikeout", ".uno:Strikeout", &[], Check::Result),
command(
"format.font",
".uno:CharFontName",
&[Arg::Font("CharFontName.FamilyName")],
Check::Reports,
),
command(
"format.size",
".uno:FontHeight",
&[Arg::Points("FontHeight.Height")],
Check::Reports,
),
command(
"format.style",
".uno:StyleApply",
&[Arg::Text("Style"), Arg::Text("FamilyName")],
Check::Result,
),
command("format.superscript", ".uno:SuperScript", &[], Check::Result),
command("format.subscript", ".uno:SubScript", &[], Check::Result),
command(
"format.color",
".uno:FontColor",
&[Arg::Int("FontColor.Color", "long", 0, 0xFF_FFFF)],
Check::Reports,
),
command(
"format.highlight",
".uno:CharBackColor",
&[Arg::Int("CharBackColor.Color", "long", -1, 0xFF_FFFF)],
Check::Reports,
),
command("paragraph.left", ".uno:LeftPara", &[], Check::Result),
command("paragraph.center", ".uno:CenterPara", &[], Check::Result),
command("paragraph.right", ".uno:RightPara", &[], Check::Result),
command("paragraph.justify", ".uno:JustifyPara", &[], Check::Result),
command(
"paragraph.indent",
".uno:IncrementIndent",
&[],
Check::Result,
),
command(
"paragraph.outdent",
".uno:DecrementIndent",
&[],
Check::Result,
),
command("paragraph.spacing_1", ".uno:SpacePara1", &[], Check::Result),
command(
"paragraph.spacing_15",
".uno:SpacePara15",
&[],
Check::Result,
),
command("paragraph.spacing_2", ".uno:SpacePara2", &[], Check::Result),
command(
"paragraph.spacing",
".uno:ULSpacing",
&[
Arg::Int("ULSpacing.TopMargin", "long", 0, 10_000),
Arg::Int("ULSpacing.BottomMargin", "long", 0, 10_000),
],
Check::Undoable,
),
command(
"paragraph.tab",
".uno:ChangeTabStop",
&[
Arg::Int("Index", "long", -1, 99),
Arg::Int("Position", "long", 0, 31_680),
Arg::Bool("Remove"),
],
Check::Undoable,
),
command("list.bullets", ".uno:DefaultBullet", &[], Check::Result),
command(
"list.numbering",
".uno:DefaultNumbering",
&[],
Check::Result,
),
command("list.deeper", ".uno:DecrementLevel", &[], Check::Result),
command("list.higher", ".uno:IncrementLevel", &[], Check::Result),
command(
"style.new",
".uno:StyleNewByExample",
&[
Arg::Text("Param"),
Arg::Int("Family", "unsigned short", 1, 8),
],
Check::Listed,
),
command(
"style.update",
".uno:StyleUpdateByExample",
&[
Arg::Text("Param"),
Arg::Int("Family", "unsigned short", 1, 2),
],
Check::Undoable,
),
];
+59
View File
@@ -0,0 +1,59 @@
//! Tool rows: find and replace, spelling, compare.
use super::{Arg, Check, Command, command};
/// Find one (0) or all (1), with the options.
const FIND: [Arg; 6] = [
Arg::Loose("SearchItem.SearchString"),
Arg::Bool("SearchItem.Backward"),
Arg::Int("SearchItem.Command", "unsigned short", 0, 1),
Arg::Int("SearchItem.TransliterateFlags", "long", 0, 256),
Arg::Int("SearchItem.SearchFlags", "long", 0, 16),
Arg::Int("SearchItem.AlgorithmType2", "short", 1, 2),
];
/// Replace one (2) or all (3), with the replacement.
const REPLACE: [Arg; 7] = [
Arg::Loose("SearchItem.SearchString"),
Arg::Bool("SearchItem.Backward"),
Arg::Int("SearchItem.Command", "unsigned short", 2, 3),
Arg::Int("SearchItem.TransliterateFlags", "long", 0, 256),
Arg::Int("SearchItem.SearchFlags", "long", 0, 16),
Arg::Int("SearchItem.AlgorithmType2", "short", 1, 2),
Arg::Loose("SearchItem.ReplaceString"),
];
/// Find, replace, spelling and compare commands.
pub(super) const ROWS: &[Command] = &[
command("find.run", ".uno:ExecuteSearch", &FIND, Check::Finished),
command(
"find.replace",
".uno:ExecuteSearch",
&REPLACE,
Check::Finished,
),
command(
"spell.apply",
".uno:SpellCheckApplySuggestion",
&[Arg::Text("ApplyRule")],
Check::Undoable,
),
command(
"spell.ignore_all",
".uno:SpellCheckIgnoreAll",
&[Arg::Text("Type")],
Check::Finished,
),
command(
"view.theme",
".uno:ChangeTheme",
&[Arg::Text("NewTheme")],
Check::Finished,
),
command(
"doc.compare",
".uno:CompareDocuments",
&[Arg::Text("URL"), Arg::Bool("NoAcceptDialog")],
Check::Result,
),
];
+457
View File
@@ -0,0 +1,457 @@
//! Document events: tiles, cursor, state, dialogs, a11y (LOK-03..08).
use std::{
collections::{HashMap, HashSet},
ffi::{CStr, c_char, c_void},
sync::{Condvar, Mutex, OnceLock},
time::{Duration, Instant},
};
use crate::ffi::Document;
mod cell;
mod parse;
pub use cell::{Cell, Function, Mark, Request};
use cell::{functions_of, marks_of, request_of, usage_of};
pub use parse::A11y;
use parse::{
Dialog, a11y_update, dialog_of, fonts_of, formula_text, found_of, rect_of, result_of, state_of,
tabs_of,
};
/// LOK_CALLBACK kinds Ely reads.
const INVALIDATE_TILES: i32 = 0;
const CURSOR: i32 = 1;
const SELECTION: i32 = 2;
const CURSOR_VISIBLE: i32 = 5;
const GRAPHIC: i32 = 6;
const STATE: i32 = 8;
const RULER: i32 = 35;
const WINDOW: i32 = 36;
const JSDIALOG: i32 = 46;
const RESULT: i32 = 16;
const A11Y_FOCUS: i32 = 62;
const A11Y_CARET: i32 = 63;
const A11Y_SELECTION: i32 = 64;
const A11Y_CELL: i32 = 67;
const A11Y_EDITING: i32 = 68;
const A11Y_OBJECT: i32 = 69;
const REDLINES: i32 = 30;
const REDLINE: i32 = 31;
const COMMENT: i32 = 32;
const NOT_FOUND: i32 = 12;
const FOUND: i32 = 15;
const MENU: i32 = 23;
const FONTS: i32 = 57;
const SIZE_CHANGED: i32 = 13;
const SET_PART: i32 = 14;
const CELL_CURSOR: i32 = 17;
const CELL_FORMULA: i32 = 19;
const HEADER: i32 = 33;
const GEOMETRY: i32 = 50;
const CELL_ADDRESS: i32 = 34;
const REFERENCE_MARKS: i32 = 45;
const FUNCTION_LIST: i32 = 47;
const TOOLTIP: i32 = 71;
/// A mixed state; kernel values never hold NUL.
pub const MIXED: &str = "\u{0}mixed";
/// A rectangle in twips: x, y, width, height.
pub type Rect = (i32, i32, i32, i32);
/// One drained batch of document events.
#[derive(Clone, Debug, Default)]
pub struct Events {
/// Bumps on every event below.
pub seq: u64,
/// The document's revision when the batch was sent.
pub revision: u64,
/// Bumps on tile invalidations only.
pub generation: u64,
pub all: bool,
pub rects: Vec<Rect>,
pub cursor: Option<Rect>,
pub cursor_visible: bool,
pub selection: Vec<Rect>,
/// The selected object's frame, if any.
pub graphic: Option<Rect>,
/// The selected image is in crop mode.
pub cropping: bool,
/// Bumps on comment and tracked-change events.
pub review: u64,
/// Bumps on each search outcome.
pub searched: u64,
/// Bumps when the document's size changes.
pub resized: u64,
/// The last search's matches; empty when none.
pub found: Vec<Rect>,
/// A context menu the kernel offered, as JSON.
pub menu: Option<String>,
/// Kernel messages Ely could not read.
pub faults: Vec<String>,
/// Font families the document names and the system lacks.
pub fonts: Vec<String>,
/// Kernel states changed since the last drain (LOK-05).
pub states: Vec<(String, String)>,
/// Dialogs the kernel opened and Ely closed (LOK-08).
pub blocked: Vec<String>,
pub a11y: A11y,
/// The paragraph's own tab stops, in 1/100 mm.
pub tabs: Vec<i32>,
pub cell: Cell,
}
#[derive(Default)]
struct Slot {
batch: Events,
closed: HashSet<u32>,
titles: HashMap<u32, String>,
/// Every state the kernel reported, for the worker's checks.
known: HashMap<String, String>,
/// The last command completion: name and success.
result: Option<(String, bool)>,
/// The seq last pushed to the client.
pushed: u64,
}
impl Slot {
/// The batch so far; drains the one-shot parts.
fn drain(&mut self) -> Events {
let batch = self.batch.clone();
self.batch.all = false;
self.batch.rects.clear();
self.batch.states.clear();
self.batch.blocked.clear();
self.batch.menu = None;
self.batch.faults.clear();
batch
}
}
fn slots() -> &'static Mutex<HashMap<u64, Slot>> {
static SLOTS: OnceLock<Mutex<HashMap<u64, Slot>>> = OnceLock::new();
SLOTS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn signal() -> &'static Condvar {
static SIGNAL: OnceLock<Condvar> = OnceLock::new();
SIGNAL.get_or_init(Condvar::new)
}
const KINDS: [i32; 33] = [
REFERENCE_MARKS,
FUNCTION_LIST,
TOOLTIP,
GEOMETRY,
SIZE_CHANGED,
SET_PART,
CELL_CURSOR,
CELL_FORMULA,
HEADER,
CELL_ADDRESS,
FONTS,
NOT_FOUND,
FOUND,
MENU,
REDLINES,
REDLINE,
COMMENT,
RULER,
INVALIDATE_TILES,
CURSOR,
SELECTION,
CURSOR_VISIBLE,
GRAPHIC,
STATE,
RESULT,
WINDOW,
JSDIALOG,
A11Y_FOCUS,
A11Y_CARET,
A11Y_SELECTION,
A11Y_CELL,
A11Y_EDITING,
A11Y_OBJECT,
];
unsafe extern "C" fn on_event(kind: i32, payload: *const c_char, data: *mut c_void) {
if !KINDS.contains(&kind) || data.is_null() {
return;
}
let (id, raw) = unsafe { *data.cast::<(u64, crate::ffi::Raw)>() };
let text = if payload.is_null() {
String::new()
} else {
unsafe { CStr::from_ptr(payload) }
.to_string_lossy()
.into_owned()
};
let close = {
let mut slots = slots().lock().expect("the events lock");
let Some(slot) = slots.get_mut(&id) else {
return;
};
let close = record(slot, kind, &text);
slot.batch.seq += 1;
close
};
if let Some(window) = close {
// Outside the lock: closing calls back in.
crate::ffi::close_window(raw, window);
}
signal().notify_all();
}
/// Folds one callback in; returns a dialog to close.
fn record(slot: &mut Slot, kind: i32, text: &str) -> Option<u32> {
let batch = &mut slot.batch;
match kind {
INVALIDATE_TILES => {
batch.generation += 1;
match rect_of(text) {
Some(rect) => batch.rects.push(rect),
None => batch.all = true,
}
}
CURSOR => batch.cursor = rect_of(text),
SELECTION => batch.selection = text.split(';').filter_map(rect_of).collect(),
CURSOR_VISIBLE => batch.cursor_visible = text == "true",
GRAPHIC => {
batch.graphic = rect_of(text);
batch.cropping = batch.graphic.is_some() && text.contains("\"isCropMode\": true");
}
STATE => {
if let Some(state) = state_of(text) {
slot.known.insert(state.0.clone(), state.1.clone());
batch.states.retain(|(name, _)| *name != state.0);
batch.states.push(state);
}
}
RESULT => slot.result = result_of(text),
RULER => batch.tabs = tabs_of(text),
REDLINES | REDLINE | COMMENT => batch.review += 1,
NOT_FOUND => {
batch.searched += 1;
batch.found.clear();
}
FOUND => match found_of(text) {
Some(found) => {
batch.searched += 1;
batch.found = found;
}
None => batch
.faults
.push(format!("an unreadable search result: {text}")),
},
MENU => batch.menu = Some(text.to_string()),
CELL_CURSOR => batch.cell.cursor = rect_of(text),
CELL_FORMULA => batch.cell.formula = text.to_string(),
CELL_ADDRESS => batch.cell.address = text.to_string(),
REFERENCE_MARKS => match marks_of(text) {
Some(marks) => batch.cell.marks = marks,
None => batch.faults.push(format!("unreadable marks: {text}")),
},
FUNCTION_LIST => match functions_of(text) {
Some(functions) => {
// "hidetip" also ends the usage hint.
if functions.is_empty() {
batch.cell.usage.clear();
}
batch.cell.functions = functions;
}
None => batch.faults.push(format!("unreadable functions: {text}")),
},
TOOLTIP => {
if let Some(usage) = usage_of(text) {
batch.cell.usage = usage;
} else if let Some(request) = request_of(text) {
log::info!("lok: the kernel asks for {}", request.kind());
batch.cell.requests += 1;
batch.cell.request = Some(request);
}
}
SET_PART => batch.cell.sheets += 1,
SIZE_CHANGED => {
batch.cell.sheets += 1;
batch.resized += 1;
}
HEADER | GEOMETRY => batch.cell.headers += 1,
FONTS => match fonts_of(text) {
Some(fonts) => batch.fonts = fonts,
None => batch
.faults
.push(format!("an unreadable font list: {text}")),
},
JSDIALOG if formula_text(text).is_some() => {
// Calc's input line holds the current cell.
batch.a11y.text = formula_text(text).expect("checked above");
}
WINDOW | JSDIALOG => match dialog_of(kind == JSDIALOG, text)? {
Dialog::Titled { window, title } => {
slot.titles.insert(window, title);
}
Dialog::Opened { window, title } => {
if !slot.closed.insert(window) {
return None;
}
let title = title
.or_else(|| slot.titles.get(&window).cloned())
.unwrap_or_else(|| format!("window {window}"));
log::warn!("lok: closed kernel dialog {window} ({title})");
batch.blocked.push(title);
return Some(window);
}
},
_ => a11y_update(&mut batch.a11y, kind, text),
}
None
}
/// Registers the trampoline on `doc` (LOK-03).
pub fn watch(id: u64, doc: &Document) {
// The box leaks; a callback may still read it.
let data = Box::into_raw(Box::new((id, doc.raw())));
let mut slot = Slot::default();
slot.batch.cursor_visible = true;
slots().lock().expect("the events lock").insert(id, slot);
doc.initialize_for_rendering();
doc.set_callback(Some(on_event), data.cast());
}
/// Stops the trampoline and drops the slot.
pub fn unwatch(id: u64, doc: &Document) {
doc.set_callback(None, std::ptr::null_mut());
slots().lock().expect("the events lock").remove(&id);
signal().notify_all();
}
/// Stops every watch before the documents die.
pub fn stop_all(docs: &HashMap<u64, Document>) {
for doc in docs.values() {
doc.set_callback(None, std::ptr::null_mut());
}
slots().lock().expect("the events lock").clear();
signal().notify_all();
}
/// The current generation of `id`.
pub fn generation(id: u64) -> u64 {
slots()
.lock()
.expect("the events lock")
.get(&id)
.map_or(0, |slot| slot.batch.generation)
}
/// Blocks until documents have unpushed events.
pub fn wait_unpushed() {
let mut slots = slots().lock().expect("the events lock");
while !slots.values().any(|slot| slot.batch.seq > slot.pushed) {
slots = signal().wait(slots).expect("the events wait");
}
}
/// Drains the documents with unpushed events.
pub fn unpushed() -> Vec<(u64, Events)> {
let mut slots = slots().lock().expect("the events lock");
slots
.iter_mut()
.filter(|(_, slot)| slot.batch.seq > slot.pushed)
.map(|(id, slot)| {
slot.pushed = slot.batch.seq;
(*id, slot.drain())
})
.collect()
}
/// Forgets the last completion before a dispatch.
pub fn clear_result(id: u64) {
if let Some(slot) = slots().lock().expect("the events lock").get_mut(&id) {
slot.result = None;
}
}
/// The completion the last dispatch reported.
pub fn take_result(id: u64) -> Option<(String, bool)> {
slots()
.lock()
.expect("the events lock")
.get_mut(&id)?
.result
.take()
}
/// The bridged a11y text now.
pub fn a11y_text(id: u64) -> Option<String> {
Some(
slots()
.lock()
.expect("the events lock")
.get(&id)?
.batch
.a11y
.text
.clone(),
)
}
/// Waits for the a11y text to leave `before`.
pub fn wait_a11y_change(id: u64, before: &str, timeout: Duration) -> Option<String> {
let deadline = Instant::now() + timeout;
let mut slots = slots().lock().expect("the events lock");
loop {
let text = slots.get(&id)?.batch.a11y.text.clone();
let now = Instant::now();
if text != before || now >= deadline {
return Some(text);
}
slots = signal()
.wait_timeout(slots, deadline - now)
.expect("the events wait")
.0;
}
}
/// Waits for `uno` to read `want`; returns the last state.
pub fn wait_state(id: u64, uno: &str, want: &str, timeout: Duration) -> Option<String> {
let deadline = Instant::now() + timeout;
let mut slots = slots().lock().expect("the events lock");
loop {
let state = slots.get(&id)?.known.get(uno).cloned();
let now = Instant::now();
if state.as_deref() == Some(want) || now >= deadline {
return state;
}
slots = signal()
.wait_timeout(slots, deadline - now)
.expect("the events wait")
.0;
}
}
/// Waits until the selected image is in crop mode.
pub fn wait_cropping(id: u64, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
let mut slots = slots().lock().expect("the events lock");
loop {
let cropping = slots.get(&id).is_some_and(|slot| slot.batch.cropping);
let now = Instant::now();
if cropping || now >= deadline {
return cropping;
}
slots = signal()
.wait_timeout(slots, deadline - now)
.expect("the events wait")
.0;
}
}
/// Seeds the a11y text from the kernel's snapshot (§7 tail).
pub fn seed_a11y(id: u64, paragraph: &str) {
if let Some(slot) = slots().lock().expect("the events lock").get_mut(&id) {
a11y_update(&mut slot.batch.a11y, A11Y_FOCUS, paragraph);
slot.batch.seq += 1;
}
signal().notify_all();
}
+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");
}
}
+354
View File
@@ -0,0 +1,354 @@
use std::{
ffi::{CString, c_char, c_void},
io,
path::Path,
};
/// The kit vtable: nSize, then 26 slots in header order.
#[repr(C)]
struct KitClass {
n_size: usize,
entries: [*mut c_void; 26],
}
/// The document vtable: nSize, then 81 slots in header order.
#[repr(C)]
struct DocClass {
n_size: usize,
entries: [*mut c_void; 81],
}
#[repr(C)]
struct Kit {
class: *const KitClass,
}
#[repr(C)]
struct Doc {
class: *const DocClass,
}
type Hook2 = unsafe extern "C" fn(*const i8, *const i8) -> *mut Kit;
/// A loaded LibreOfficeKit instance.
pub struct Lok {
kit: *mut Kit,
_lib: Library,
}
/// A LOK event callback (LibreOfficeKitCallback).
pub type Callback = unsafe extern "C" fn(i32, *const c_char, *mut c_void);
/// Documents move between the registry and handlers on one thread.
unsafe impl Send for Document {}
/// A loaded document inside one Lok.
pub struct Document {
doc: *mut Doc,
/// The kernel view the load made.
view: i32,
}
/// Calls vtable slot `index` as `F`.
macro_rules! call {
($class:expr, $index:expr, $type:ty, $($arg:expr),*) => {{
unsafe {
let entry = (*$class).entries[$index];
let f: $type = std::mem::transmute(entry);
f($($arg),*)
}
}};
}
mod document;
mod slideshow;
pub use document::{Raw, close_window};
impl Lok {
/// LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK.
pub const PART_IN_INVALIDATION: u64 = 1 << 2;
/// LOK_FEATURE_NO_TILED_ANNOTATIONS: comments come as callbacks.
pub const NO_TILED_ANNOTATIONS: u64 = 1 << 3;
/// LOK_FEATURE_DOCUMENT_PASSWORD: the client answers.
pub const DOCUMENT_PASSWORD: u64 = 1 << 0;
/// dlopens the LOK library and hooks with the profile URL.
pub fn hook(install: &Path, profile_url: &str) -> io::Result<Self> {
let install = std::fs::canonicalize(install)?;
let install = install.as_path();
let install_str = install.to_string_lossy().into_owned();
let install_c = cstring(&install_str)?;
let profile_c = cstring(profile_url)?;
let lib = Library::open(install)?;
let hook: Hook2 = unsafe {
lib.symbol(b"libreofficekit_hook_2\0")
.or_else(|_| lib.symbol(b"libreofficekit_hook\0"))
.map_err(|error| io::Error::new(io::ErrorKind::NotFound, error))?
};
let kit = unsafe { hook(install_c.as_ptr(), profile_c.as_ptr()) };
if !kit.is_null() {
type F = unsafe extern "C" fn(*mut Kit, u64);
let features =
Self::PART_IN_INVALIDATION | Self::NO_TILED_ANNOTATIONS | Self::DOCUMENT_PASSWORD;
call!((*kit).class, 7, F, kit, features);
}
if kit.is_null() {
return Err(io::Error::other(format!(
"lok hook failed for {install_str}"
)));
}
log::info!("lok: hooked {}", install_str);
Ok(Self { kit, _lib: lib })
}
/// The BuildId string of the hooked library.
pub fn build_id(&self) -> String {
let class = unsafe { (*self.kit).class };
type F = unsafe extern "C" fn(*mut Kit) -> *mut i8;
let raw = call!(class, 9, F, self.kit);
unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned()
}
/// Loads a document; failures surface (LOK-09).
pub fn load(&self, url: &str, options: &str) -> io::Result<Document> {
let class = unsafe { (*self.kit).class };
let url_c = cstring(url)?;
let options_c = cstring(options)?;
type F = unsafe extern "C" fn(*mut Kit, *const i8, *const i8) -> *mut Doc;
let doc = call!(class, 3, F, self.kit, url_c.as_ptr(), options_c.as_ptr());
if doc.is_null() {
return Err(io::Error::other(self.error()));
}
type View = unsafe extern "C" fn(*mut Doc) -> i32;
let doc_class = unsafe { (*doc).class };
let view = call!(doc_class, 28, View, doc);
log::info!("lok: loaded into view {view}");
Ok(Document { doc, view })
}
/// The kit's current error text.
fn error(&self) -> String {
let class = unsafe { (*self.kit).class };
type Get = unsafe extern "C" fn(*mut Kit) -> *mut i8;
type Free = unsafe extern "C" fn(*mut i8);
let raw = call!(class, 2, Get, self.kit);
if raw.is_null() {
return "unknown LOK error".into();
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
call!(class, 4, Free, raw);
text
}
/// Registers the kit-wide callback.
pub fn register_callback(&self, callback: Callback) {
let class = unsafe { (*self.kit).class };
type F = unsafe extern "C" fn(*mut Kit, Callback, *mut c_void);
call!(class, 5, F, self.kit, callback, std::ptr::null_mut());
}
/// Answers a password question; None refuses.
pub fn set_password(&self, url: &str, password: Option<&str>) {
let class = unsafe { (*self.kit).class };
let url_c = cstring(url).expect("a url without NUL");
let password_c = password.map(|password| cstring(password).expect("no NUL"));
let password_ptr = password_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
type F = unsafe extern "C" fn(*mut Kit, *const c_char, *const c_char);
call!(class, 8, F, self.kit, url_c.as_ptr(), password_ptr);
}
/// Sets a kit option such as `author`.
pub fn set_option(&self, option: &str, value: &str) -> io::Result<()> {
let class = unsafe { (*self.kit).class };
let (option, value) = (cstring(option)?, cstring(value)?);
type F = unsafe extern "C" fn(*mut Kit, *const c_char, *const c_char);
call!(class, 14, F, self.kit, option.as_ptr(), value.as_ptr());
Ok(())
}
/// Waits for the kit's threads to finish (LOK-10).
pub fn join_threads(&self) -> bool {
let class = unsafe { (*self.kit).class };
type F = unsafe extern "C" fn(*mut Kit) -> i32;
call!(class, 20, F, self.kit) != 0
}
/// Runs a macro by URL, for the debug probe.
pub fn run_macro(&self, url: &str) -> i32 {
let class = unsafe { (*self.kit).class };
let url_c = cstring(url).expect("a url");
type F = unsafe extern "C" fn(*mut Kit, *const i8) -> i32;
call!(class, 10, F, self.kit, url_c.as_ptr())
}
#[cfg(target_os = "macos")]
/// Answers the kernel's "input waiting?" without a run-loop peek.
pub fn register_any_input(&self, waiting: extern "C" fn(*mut c_void, i32) -> bool) {
static DATA: u8 = 0;
let class = unsafe { (*self.kit).class };
type F =
unsafe extern "C" fn(*mut Kit, extern "C" fn(*mut c_void, i32) -> bool, *mut c_void);
let data = std::ptr::addr_of!(DATA).cast_mut().cast();
call!(class, 24, F, self.kit, waiting, data);
}
#[cfg(target_os = "macos")]
/// Runs LOK's loop until kit exit (R-01).
pub fn run_loop(&self) {
type PollCb = Option<extern "C" fn(*mut c_void, i32) -> i32>;
type WakeCb = Option<extern "C" fn(*mut c_void)>;
extern "C" fn poll(_: *mut c_void, _: i32) -> i32 {
0
}
extern "C" fn wake(_: *mut c_void) {}
let class = unsafe { (*self.kit).class };
type F = unsafe extern "C" fn(*mut Kit, PollCb, WakeCb, *mut c_void);
call!(
class,
12,
F,
self.kit,
Some(poll),
Some(wake),
std::ptr::null_mut()
);
}
}
impl Drop for Lok {
fn drop(&mut self) {
if self.kit.is_null() {
return;
}
let class = unsafe { (*self.kit).class };
type F = unsafe extern "C" fn(*mut Kit);
call!(class, 0, F, self.kit);
log::info!("lok: destroyed");
}
}
/// A Rust string as a NUL-terminated C string.
fn cstring(text: &str) -> io::Result<CString> {
CString::new(text)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "the string holds a NUL"))
}
#[cfg(unix)]
struct Library {
handle: *mut c_void,
}
#[cfg(unix)]
impl Library {
/// dlopens the LOK library, merged candidates in order.
fn open(install: &Path) -> io::Result<Self> {
use std::os::unix::ffi::OsStrExt;
let mut last = "no candidate".to_string();
for name in [
"libsofficeapp.dylib",
"libmergedlo.dylib",
"libsofficeapp.so",
"libmergedlo.so",
] {
let path = install.join(name);
if !path.try_exists()? {
continue;
}
let c = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "the path holds a NUL"))?;
let handle = unsafe { libc::dlopen(c.as_ptr(), libc::RTLD_LAZY | libc::RTLD_GLOBAL) };
if handle.is_null() {
last = dl_error();
log::warn!("lok: dlopen {} failed: {last}", path.display());
continue;
}
return Ok(Self { handle });
}
Err(io::Error::new(
io::ErrorKind::NotFound,
format!(
"no loadable LOK library under {}: {last}",
install.display()
),
))
}
/// dlsyms `name` from the library.
unsafe fn symbol<F: Copy>(&self, name: &[u8]) -> Result<F, String> {
let name = name.strip_suffix(b"\0").unwrap_or(name);
let c = CString::new(name).map_err(|_| "bad symbol".to_string())?;
unsafe { libc::dlerror() };
let ptr = unsafe { libc::dlsym(self.handle, c.as_ptr()) };
if ptr.is_null() {
return Err(dl_error());
}
Ok(unsafe { std::mem::transmute_copy(&ptr) })
}
}
#[cfg(unix)]
fn dl_error() -> String {
let raw = unsafe { libc::dlerror() };
if raw.is_null() {
return "dlopen failed".into();
}
unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned()
}
#[cfg(windows)]
struct Library {
handle: isize,
}
#[cfg(windows)]
impl Library {
/// Loads `<install>/sofficeapp.dll`, merged fallback.
fn open(install: &Path) -> io::Result<Self> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::System::LibraryLoader::{
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, LoadLibraryExW,
};
for name in ["sofficeapp.dll", "mergedlo.dll"] {
let path = install.join(name);
if !path.try_exists()? {
continue;
}
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let handle = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
)
};
if handle.is_null() {
return Err(io::Error::last_os_error());
}
return Ok(Self {
handle: handle as isize,
});
}
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("no LOK library under {}", install.display()),
))
}
/// Gets `name` from the library.
unsafe fn symbol<F: Copy>(&self, name: &[u8]) -> Result<F, String> {
use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
let name = name.strip_suffix(b"\0").unwrap_or(name);
let c = CString::new(name).map_err(|_| "bad symbol".to_string())?;
let ptr = unsafe { GetProcAddress(self.handle as _, c.as_ptr() as _) };
let Some(ptr) = ptr else {
return Err(format!("no symbol {}", String::from_utf8_lossy(name)));
};
Ok(unsafe { std::mem::transmute_copy(&ptr) })
}
}
+433
View File
@@ -0,0 +1,433 @@
use std::{ffi::c_char, ffi::c_void, io};
use super::{Callback, Doc, Document, cstring};
unsafe extern "C" {
fn free(ptr: *mut c_void);
}
impl Document {
/// Makes this document's view the kernel's current one.
pub fn activate(&self) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32);
call!(class, 27, F, self.doc, self.view);
}
/// Page count or area in LOK twips; zeros when unset.
pub fn size(&self) -> (i64, i64) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *mut i64, *mut i64);
let (mut width, mut height) = (0i64, 0i64);
call!(class, 11, F, self.doc, &mut width, &mut height);
(width, height)
}
/// Paints the document into `buffer` at (x, y) twips.
pub fn paint_rect(&self, buffer: &mut [u8], pixels: (i32, i32), twips: (i32, i32, i32, i32)) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *mut u8, i32, i32, i32, i32, i32, i32);
let (pw, ph) = pixels;
let (x, y, w, h) = twips;
call!(
class,
9,
F,
self.doc,
buffer.as_mut_ptr(),
pw,
ph,
x,
y,
w,
h
);
}
/// Paints part `part` whole; `mode` 1 paints masters.
pub fn paint_part(&self, buffer: &mut [u8], (part, mode): (i32, i32), pixels: (i32, i32)) {
let (w, h) = self.size();
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *mut u8, i32, i32, i32, i32, i32, i32, i32, i32);
call!(
class,
32,
F,
self.doc,
buffer.as_mut_ptr(),
part,
mode,
pixels.0,
pixels.1,
0,
0,
w as i32,
h as i32
);
}
/// Initializes rendering so callbacks flow (LOK-03).
pub fn initialize_for_rendering(&self) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *const c_char);
call!(class, 12, F, self.doc, std::ptr::null());
}
/// Registers `callback` with `data` (LOK-03).
pub fn set_callback(&self, callback: Option<Callback>, data: *mut c_void) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, Option<Callback>, *mut c_void);
call!(class, 13, F, self.doc, callback, data);
}
/// Paints the document into `buffer` at `width` x `height` (R-01).
pub fn paint_tile(&self, buffer: &mut [u8], width: i32, height: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *mut u8, i32, i32, i32, i32, i32, i32);
call!(
class,
9,
F,
self.doc,
buffer.as_mut_ptr(),
width,
height,
0,
0,
width * 15,
height * 15
);
}
/// Runs a UNO command with JSON `args` (LOK-08).
pub fn post_uno(&self, command: &str, args: Option<&str>) -> io::Result<()> {
self.dispatch(command, args, false)
}
/// Runs a UNO command and asks for its completion result.
pub fn post_uno_notify(&self, command: &str, args: Option<&str>) -> io::Result<()> {
self.dispatch(command, args, true)
}
fn dispatch(&self, command: &str, args: Option<&str>, notify: bool) -> io::Result<()> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *const c_char, *const c_char, bool);
let command = cstring(command)?;
let args = args.map(cstring).transpose()?;
let args = args.as_ref().map_or(std::ptr::null(), |args| args.as_ptr());
call!(class, 16, F, self.doc, command.as_ptr(), args, notify);
Ok(())
}
/// Posts a key event: 0 input, 1 up.
pub fn post_key(&self, event_type: i32, char_code: i32, key_code: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32, i32, i32);
call!(class, 14, F, self.doc, event_type, char_code, key_code);
}
/// Posts a mouse event: 0 down, 1 up, 2 move.
pub fn post_mouse(&self, event: [i32; 6]) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32, i32, i32, i32, i32, i32);
let [kind, x, y, count, buttons, modifier] = event;
call!(class, 15, F, self.doc, kind, x, y, count, buttons, modifier);
}
/// Moves a selected object's handle: 0 start, 1 end.
pub fn set_graphic_selection(&self, kind: i32, x: i32, y: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32, i32, i32);
call!(class, 20, F, self.doc, kind, x, y);
}
/// Posts IME text: 0 composing, 2 commit (LOK-07).
pub fn post_text(&self, event_type: i32, text: &str) -> io::Result<()> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, u32, i32, *const c_char);
let text = cstring(text)?;
call!(class, 40, F, self.doc, 0, event_type, text.as_ptr());
Ok(())
}
/// LOK_DOCTYPE: 0 text, 1 spreadsheet, 2 presentation.
pub fn kind(&self) -> i32 {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> i32;
call!(class, 2, F, self.doc)
}
/// LOK_SELTYPE: 0 none, 1 text, 3 complex.
pub fn selection_type(&self) -> i32 {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> i32;
call!(class, 54, F, self.doc)
}
/// The view clipboard in `mimes`; empty ones skipped (LOK-06).
pub fn clipboard(&self, mimes: &[&str]) -> io::Result<Vec<(String, Vec<u8>)>> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(
*mut Doc,
*const *const c_char,
*mut usize,
*mut *mut *mut c_char,
*mut *mut usize,
*mut *mut *mut c_char,
) -> i32;
let owned = mimes
.iter()
.map(|mime| cstring(mime))
.collect::<io::Result<Vec<_>>>()?;
let mut list: Vec<*const c_char> = owned.iter().map(|mime| mime.as_ptr()).collect();
list.push(std::ptr::null());
let (mut count, mut names, mut sizes, mut streams) = (
0usize,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
);
let ok = call!(
class,
52,
F,
self.doc,
list.as_ptr(),
&mut count,
&mut names,
&mut sizes,
&mut streams
);
if ok == 0 {
return Err(io::Error::other("getClipboard failed"));
}
let mut found = Vec::new();
for i in 0..count {
let (name, size, stream) = unsafe { (*names.add(i), *sizes.add(i), *streams.add(i)) };
if size > 0 && !stream.is_null() {
let mime = unsafe { std::ffi::CStr::from_ptr(name) };
let data = unsafe { std::slice::from_raw_parts(stream.cast::<u8>(), size) };
found.push((mime.to_string_lossy().into_owned(), data.to_vec()));
}
unsafe {
free(name.cast());
free(stream.cast());
}
}
unsafe {
free(names.cast());
free(sizes.cast());
free(streams.cast());
}
Ok(found)
}
/// The JSON LOK keeps for `command` (getCommandValues).
pub fn command_values(&self, command: &str) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *const c_char) -> *mut c_char;
let name = cstring(command)?;
let raw = call!(class, 22, F, self.doc, name.as_ptr());
if raw.is_null() {
return Err(io::Error::other(format!("no values for {command}")));
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
unsafe { free(raw.cast()) };
Ok(text)
}
/// Turns on the a11y callbacks for the current view.
pub fn enable_a11y(&self) {
let class = unsafe { (*self.doc).class };
type View = unsafe extern "C" fn(*mut Doc) -> i32;
type F = unsafe extern "C" fn(*mut Doc, i32, bool);
let view = call!(class, 28, View, self.doc);
call!(class, 69, F, self.doc, view, true);
}
/// Tells the kernel the area the client shows, in twips.
pub fn set_visible_area(&self, x: i32, y: i32, width: i32, height: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32, i32, i32, i32);
call!(class, 24, F, self.doc, x, y, width, height);
}
/// The selection as plain text; Calc joins cells by tabs.
pub fn selection_text(&self) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *const c_char, *mut *mut c_char) -> *mut c_char;
let mime = cstring("text/plain;charset=utf-8")?;
let mut used: *mut c_char = std::ptr::null_mut();
let text = owned(call!(class, 18, F, self.doc, mime.as_ptr(), &mut used));
owned(used);
text.ok_or_else(|| io::Error::other("the kernel gave no selection text"))
}
/// Completes the function name being typed (TABLE-03).
pub fn complete_function(&self, name: &str) -> io::Result<()> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, *const c_char);
let name = cstring(name)?;
call!(class, 59, F, self.doc, name.as_ptr());
Ok(())
}
/// How many parts: sheets or slides.
pub fn parts(&self) -> i32 {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> i32;
call!(class, 3, F, self.doc)
}
/// The part the view shows, from 0.
pub fn part(&self) -> i32 {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> i32;
call!(class, 5, F, self.doc)
}
/// Shows part `part`.
pub fn set_part(&self, part: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32);
call!(class, 6, F, self.doc, part);
}
/// The name of part `part`.
pub fn part_name(&self, part: i32) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32) -> *mut c_char;
owned(call!(class, 7, F, self.doc, part))
.ok_or_else(|| io::Error::other(format!("part {part} has no name")))
}
/// LOK's JSON about part `part`: visible, protected.
pub fn part_info(&self, part: i32) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32) -> *mut c_char;
owned(call!(class, 41, F, self.doc, part))
.ok_or_else(|| io::Error::other(format!("part {part} has no info")))
}
/// Page rectangles as "x, y, w, h; ...".
pub fn page_rects(&self) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> *mut c_char;
let raw = call!(class, 4, F, self.doc);
if raw.is_null() {
return Ok(String::new());
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
unsafe { free(raw.cast()) };
Ok(text)
}
/// The focused paragraph as LOK's a11y JSON.
pub fn a11y_paragraph(&self) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> *mut c_char;
let raw = call!(class, 70, F, self.doc);
if raw.is_null() {
return Err(io::Error::other("no focused paragraph"));
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
unsafe { free(raw.cast()) };
Ok(text)
}
/// Puts one `mime` entry on the view clipboard (LOK-06).
pub fn set_clipboard(&self, mime: &str, data: &[u8]) -> io::Result<()> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(
*mut Doc,
usize,
*const *const c_char,
*const usize,
*const *const c_char,
) -> i32;
let mime = cstring(mime)?;
let ok = call!(
class,
53,
F,
self.doc,
1,
&mime.as_ptr(),
&data.len(),
&data.as_ptr().cast::<c_char>()
);
if ok == 0 {
return Err(io::Error::other("setClipboard failed"));
}
Ok(())
}
/// Saves to `url` as `format`; false means LOK reported failure.
pub fn save_as(&self, url: &str, format: &str, options: &str) -> io::Result<()> {
let class = unsafe { (*self.doc).class };
let url_c = cstring(url)?;
let format_c = cstring(format)?;
let options_c = cstring(options)?;
type F = unsafe extern "C" fn(*mut Doc, *const i8, *const i8, *const i8) -> i32;
let ok = call!(
class,
1,
F,
self.doc,
url_c.as_ptr(),
format_c.as_ptr(),
options_c.as_ptr()
);
if ok == 0 {
return Err(io::Error::other(format!("saveAs failed for {url}")));
}
Ok(())
}
}
impl Drop for Document {
fn drop(&mut self) {
if self.doc.is_null() {
return;
}
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc);
call!(class, 0, F, self.doc);
}
}
/// A document's native handle, for callbacks that cannot borrow it.
#[derive(Clone, Copy)]
pub struct Raw(*mut Doc);
impl Document {
pub fn raw(&self) -> Raw {
Raw(self.doc)
}
}
/// Closes kernel window `window` of document `doc` (LOK-08).
pub fn close_window(doc: Raw, window: u32) {
let doc = doc.0;
let class = unsafe { (*doc).class };
type F = unsafe extern "C" fn(*mut Doc, u32, i32, *const c_char);
call!(class, 36, F, doc, window, 0, std::ptr::null());
}
/// Takes a string LOK allocated; None for null.
fn owned(raw: *mut c_char) -> Option<String> {
if raw.is_null() {
return None;
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
unsafe { free(raw.cast()) };
Some(text)
}
+74
View File
@@ -0,0 +1,74 @@
use std::{ffi::c_char, ffi::c_void, io};
use super::{Doc, Document, cstring};
unsafe extern "C" {
fn free(ptr: *mut c_void);
}
/// One rendered layer: the kernel's JSON and, for bitmaps, pixels.
pub struct Layer {
pub json: String,
pub pixels: Option<Vec<u8>>,
}
fn owned(raw: *mut c_char) -> io::Result<String> {
if raw.is_null() {
return Err(io::Error::other("no text from the kernel"));
}
let text = unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned();
unsafe { free(raw.cast()) };
Ok(text)
}
impl Document {
/// The slideshow's slides, transitions and animations as JSON.
pub fn presentation_info(&self) -> io::Result<String> {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc) -> *mut c_char;
owned(call!(class, 74, F, self.doc))
}
/// Slide `part`'s layers at about `pixels`; gives the size used.
pub fn slide_layers(
&self,
(part, hash): (i32, &str),
pixels: (u32, u32),
max_bytes: usize,
) -> io::Result<((u32, u32), Vec<Layer>)> {
let class = unsafe { (*self.doc).class };
type Create = unsafe extern "C" fn(*mut Doc, *const c_char, i32, *mut u32, *mut u32, bool, bool) -> bool;
type Next = unsafe extern "C" fn(*mut Doc, *mut u8, *mut bool, *mut f64, *mut *mut c_char) -> bool;
type Cleanup = unsafe extern "C" fn(*mut Doc);
let hash = cstring(hash)?;
let (mut width, mut height) = pixels;
let made = call!(class, 75, Create, self.doc, hash.as_ptr(), part, &mut width, &mut height, true, true);
if !made {
return Err(io::Error::other(format!("no slide renderer for slide {part}")));
}
let size = (width as usize) * (height as usize) * 4;
let mut layers = Vec::new();
let mut total = 0;
let result = loop {
let mut pixels = vec![0u8; size];
let (mut bitmap, mut scale, mut json) = (false, 1.0f64, std::ptr::null_mut());
let done = call!(class, 77, Next, self.doc, pixels.as_mut_ptr(), &mut bitmap, &mut scale, &mut json);
if done {
break Ok(());
}
let json = match owned(json) {
Ok(json) => json,
Err(error) => break Err(error),
};
total += json.len() + if bitmap { size } else { 0 };
if total > max_bytes {
break Err(io::Error::other(format!("slide {part}'s layers pass {max_bytes} bytes")));
}
layers.push(Layer { json, pixels: bitmap.then_some(pixels) });
};
call!(class, 76, Cleanup, self.doc);
result.map(|()| ((width, height), layers))
}
}
+200
View File
@@ -0,0 +1,200 @@
//! Worker handshake: pinned-build and tile checks (LOK-01).
use std::{io, path::Path};
use crate::client::{BUILD_ID, Worker};
#[cfg(target_os = "macos")]
use crate::ipc::{self, Pack, Unpack, tag};
/// A tiny flat-XML document for the tile self-check.
#[cfg(target_os = "macos")]
const VERIFY_DOC: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><office:document xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" office:version=\"1.3\" office:mimetype=\"application/vnd.oasis.opendocument.text\"><office:body><office:text><text:p>verify</text:p></office:text></office:body></office:document>";
impl Worker {
/// Rejects builds that are not the pinned one (LOK-01).
pub(crate) fn verify(&mut self, build: &str, profile_dir: &Path) -> io::Result<()> {
if !build.contains(BUILD_ID) {
return self.reject(format!("not the pinned build {BUILD_ID}: {build}"));
}
#[cfg(target_os = "macos")]
if !self.tile_self_check(profile_dir)? {
return self.reject(format!(
"the pinned build {BUILD_ID} does not paint tiles (unpatched)"
));
}
let _ = profile_dir;
Ok(())
}
/// Kills the child and reports the rejection.
pub(crate) fn reject<T>(&mut self, reason: String) -> io::Result<T> {
log::warn!("lok: {reason}");
let _ = self.child.kill();
let _ = self.child.wait();
Err(io::Error::new(io::ErrorKind::InvalidData, reason))
}
/// The version fields of the hooked library, checked strictly (LOK-01).
pub(crate) fn version_checked(&mut self) -> io::Result<String> {
let build = self.build_id()?;
let fields = [
("ProductName", "LibreOffice"),
("ProductVersion", "26.2"),
("BuildId", BUILD_ID),
];
for (key, want) in fields {
let Some(have) = version_field(&build, key) else {
return self.reject(format!("version misses {key}: {build}"));
};
if have != want {
return self.reject(format!("version {key} is {have}, not {want}"));
}
}
Ok(build)
}
/// Paints one tile; the bytes it gained.
#[cfg(target_os = "macos")]
pub(crate) fn tile_self_check(&mut self, profile_dir: &Path) -> io::Result<bool> {
let doc = profile_dir.join("lok-verify.fodt");
std::fs::write(&doc, VERIFY_DOC)?;
let url = ipc::file_url_of(&doc.canonicalize()?);
let payload = self.request(tag::VERIFY, &Pack::new().str(&url).bytes())?;
let gained = Unpack::new(&payload).u64()?;
Ok(gained > 0)
}
}
/// One top-level field of a strict JSON object parse.
fn version_field(text: &str, key: &str) -> Option<String> {
let pairs = JsonFields { text, at: 0 };
pairs.field(key)
}
/// A strict single-object JSON field walker.
struct JsonFields<'a> {
text: &'a str,
at: usize,
}
impl<'a> JsonFields<'a> {
fn field(mut self, want: &str) -> Option<String> {
self.take('{')?;
let mut found = None;
loop {
let key = self.string()?;
self.take(':')?;
let value = self.value()?;
if key == want {
found = value;
}
if self.take(',').is_some() {
continue;
}
self.take('}')?;
self.ws();
return (self.at == self.text.len()).then_some(found).flatten();
}
}
fn ws(&mut self) {
self.at += self.text[self.at..]
.find(|ch: char| !matches!(ch, ' ' | '\t' | '\n' | '\r'))
.unwrap_or(self.text.len() - self.at);
}
fn take(&mut self, ch: char) -> Option<()> {
self.ws();
self.text[self.at..]
.starts_with(ch)
.then(|| self.at += ch.len_utf8())
}
fn string(&mut self) -> Option<String> {
self.take('"')?;
let mut out = String::new();
let mut rest = &self.text[self.at..];
loop {
let at = rest.find(|ch: char| ch == '"' || ch == '\\' || ch < '\u{20}')?;
if rest.as_bytes()[at] < 0x20 {
return None;
}
out.push_str(&rest[..at]);
if rest[at..].starts_with('"') {
self.at += at + 1;
return Some(out);
}
let escaped = rest[at + 1..].chars().next()?;
match escaped {
'"' | '\\' | '/' => out.push(escaped),
'b' => out.push('\u{8}'),
'f' => out.push('\u{c}'),
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'u' => {
let hex = rest[at + 2..].get(..4)?;
if !hex.chars().all(|ch| ch.is_ascii_hexdigit()) {
return None;
}
let code = u32::from_str_radix(hex, 16).ok()?;
out.push(char::from_u32(code).unwrap_or('\u{fffd}'));
rest = &rest[at + 6..];
self.at += at + 6;
continue;
}
_ => return None,
}
rest = &rest[at + 2..];
self.at += at + 2;
}
}
fn value(&mut self) -> Option<Option<String>> {
self.ws();
let rest = &self.text[self.at..];
if rest.starts_with('"') {
return self.string().map(Some);
}
for word in ["true", "false", "null"] {
if rest.starts_with(word) {
self.at += word.len();
return Some(None);
}
}
let end = rest
.find(|ch: char| !(ch.is_ascii_digit() || matches!(ch, '-' | '+' | '.' | 'e' | 'E')))
.unwrap_or(rest.len());
let text = &rest[..end];
if !Self::number_ok(text) {
return None;
}
self.at += end;
Some(None)
}
fn number_ok(text: &str) -> bool {
let text = text.strip_prefix('-').unwrap_or(text);
let (mantissa, exponent) = match text.split_once(['e', 'E']) {
Some((mantissa, exponent)) => (mantissa, Some(exponent)),
None => (text, None),
};
if let Some(exponent) = exponent {
let exp = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
if exp.is_empty() || !exp.chars().all(|ch| ch.is_ascii_digit()) {
return false;
}
}
let (int, dot, frac) = match mantissa.split_once('.') {
Some((int, frac)) => (int, true, frac),
None => (mantissa, false, ""),
};
if int.is_empty() || !int.chars().all(|ch| ch.is_ascii_digit()) {
return false;
}
if int.len() > 1 && int.starts_with('0') {
return false;
}
!dot || (!frac.is_empty() && frac.chars().all(|ch| ch.is_ascii_digit()))
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Undo and redo lists as the kernel reports them.
use std::io;
/// One entry: the kernel's comment and time.
pub type Step = (String, String);
/// Entries of an `.uno:Undo` or `.uno:Redo` reply, newest first.
pub fn steps(json: &str) -> io::Result<Vec<Step>> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("a bad undo list: {error}")))?;
// An empty history is `"actions": ""`.
let Some(actions) = value["actions"].as_array() else {
return Ok(Vec::new());
};
Ok(actions
.iter()
.map(|action| {
let field = |name: &str| action[name].as_str().unwrap_or_default().to_string();
(field("comment"), field("dateTime"))
})
.collect())
}
+106
View File
@@ -0,0 +1,106 @@
pub use ely_ipc::{MAX_FRAME, Pack, UNASKED, Unpack, check_reply, read_frame, write_frame};
/// A local path as a `file:` URL, UTF-8 escaped.
pub fn file_url_of(path: &std::path::Path) -> String {
let text = path.to_string_lossy().into_owned();
#[cfg(windows)]
let text = if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
format!("file://{}", rest.replace('\\', "/"))
} else if let Some(rest) = text.strip_prefix(r"\\?\") {
format!("file:///{}", rest.replace('\\', "/"))
} else {
format!("file:///{}", text.replace('\\', "/"))
};
#[cfg(not(windows))]
let text = format!("file://{text}");
let mut url = String::new();
for byte in text.as_bytes() {
match *byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b':' => {
url.push(*byte as char)
}
other => url.push_str(&format!("%{other:02X}")),
}
}
url
}
/// The path a `file:` URL names; other URLs fail.
pub fn path_of_file_url(url: &str) -> std::io::Result<std::path::PathBuf> {
let bad = || std::io::Error::other(format!("{url} is no file URL"));
let rest = url.strip_prefix("file://").ok_or_else(bad)?;
let mut bytes = Vec::with_capacity(rest.len());
let mut iter = rest.bytes();
while let Some(byte) = iter.next() {
if byte != b'%' {
bytes.push(byte);
continue;
}
let hex = [iter.next().ok_or_else(bad)?, iter.next().ok_or_else(bad)?];
let hex = std::str::from_utf8(&hex).map_err(|_| bad())?;
bytes.push(u8::from_str_radix(hex, 16).map_err(|_| bad())?);
}
let text = String::from_utf8(bytes).map_err(|_| bad())?;
#[cfg(windows)]
let text = text.strip_prefix('/').unwrap_or(&text).replace('/', "\\");
Ok(std::path::PathBuf::from(text))
}
/// The load error a missing or wrong password gives.
pub const LOCKED: &str = "the document needs its password";
/// Request tags from the client.
pub mod tag {
pub const BUILD_ID: u8 = 1;
pub const LOAD: u8 = 2;
pub const DOC_SIZE: u8 = 3;
pub const SAVE_AS: u8 = 4;
pub const CLOSE_DOC: u8 = 5;
pub const SHUTDOWN: u8 = 6;
pub const VERIFY: u8 = 7;
pub const PAINT_TILE: u8 = 12;
/// Unasked: one document's new events.
pub const EVENTS: u8 = 13;
pub const POST_UNO: u8 = 14;
pub const POST_MOUSE: u8 = 8;
pub const RUN_MACRO: u8 = 10;
pub const POST_KEY: u8 = 11;
pub const POST_TEXT: u8 = 15;
pub const COPY: u8 = 16;
pub const PASTE: u8 = 17;
pub const CUT: u8 = 18;
pub const VALUES: u8 = 19;
pub const PAGES: u8 = 20;
pub const GRAPHIC: u8 = 21;
pub const EXPORT_PDF: u8 = 22;
pub const SHEETS: u8 = 23;
pub const SHOW_SHEET: u8 = 24;
pub const VISIBLE_AREA: u8 = 25;
pub const SELECTION_TEXT: u8 = 26;
pub const SET_AUTHOR: u8 = 27;
pub const COMPLETE_FUNCTION: u8 = 28;
pub const IMPORT: u8 = 29;
pub const EXPORT_TEXT: u8 = 30;
pub const PAINT_PART: u8 = 31;
pub const SLIDE_LAYERS: u8 = 32;
/// Refuses unless the document is still at a revision.
pub const EXPECT: u8 = 33;
pub const REVISION: u8 = 34;
pub const OK: u8 = 100;
pub const ERR: u8 = 101;
}
#[cfg(test)]
mod tests {
#[test]
fn a_file_url_turns_back_into_its_path() {
let path = std::env::temp_dir().join("幻灯片 one%.mp4");
let url = super::file_url_of(&path);
assert_eq!(super::path_of_file_url(&url).expect("decodes"), path);
assert!(super::path_of_file_url("vnd.sun.star.Package:Media/a.mp4").is_err());
assert!(super::path_of_file_url("file:///bad%zz").is_err());
}
}
/// How a refusal for a changed document begins.
pub const STALE: &str = "stale: ";
+29
View File
@@ -0,0 +1,29 @@
//! LOK shared access: worker process, IPC and client (PRD §7).
mod client;
pub mod commands;
mod events;
mod ffi;
mod handshake;
pub mod history;
mod ipc;
pub mod review;
pub mod sheet;
pub mod show;
mod worker;
pub use client::{
A11y, Cell, Doc, Events, Function, MIXED, Mark, Mouse, Pdf, Rect, Request, Sheet, Sheets, Tile,
Worker, install_dir, is_stale, templates,
};
#[cfg(feature = "view")]
pub use view::{
CONTEXT, Copy, Cut, Geom, Layout, LokError, LokView, Paste, Reported, TILE_TWIPS, ZOOM_STEPS,
Zoomed, init, layout, paper, read_off, scheme,
};
#[cfg(feature = "view")]
mod view;
pub use ipc::STALE;
pub use ipc::file_url_of as file_url;
pub use ipc::path_of_file_url as file_path;
pub use worker::run as worker_run;
+299
View File
@@ -0,0 +1,299 @@
//! Kernel lists for references, review and checks (DOC-09 to 12).
use std::io;
use crate::Rect;
/// A comment from `.uno:ViewAnnotations`.
#[derive(Clone, Debug, PartialEq)]
pub struct Note {
pub id: String,
/// "0" for a thread's first comment.
pub parent: String,
pub author: String,
pub text: String,
pub resolved: bool,
/// ISO 8601, as the kernel gives it.
pub at: String,
pub anchor: Rect,
}
/// A tracked change from `.uno:AcceptTrackedChanges`.
#[derive(Clone, Debug, PartialEq)]
pub struct Change {
pub index: u64,
pub author: String,
pub kind: String,
pub description: String,
pub at: String,
pub anchor: Option<Rect>,
}
/// Words and characters, in the document and the selection.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Counts {
pub words: u64,
pub characters: u64,
pub selected_words: u64,
pub selected_characters: u64,
}
/// A misspelled word's menu: suggestions as the kernel's rules.
#[derive(Clone, Debug, PartialEq)]
pub struct Spelling {
/// Label and `ApplyRule` value for each suggestion.
pub suggestions: Vec<(String, String)>,
}
/// The counts from `.uno:WordCount`.
pub fn counts(json: &str) -> io::Result<Counts> {
let list = parse(json)?;
let (document, selection) = (&list["document"], &list["selection"]);
Ok(Counts {
words: number(document, "words")?,
characters: number(document, "characters")?,
selected_words: number(selection, "words")?,
selected_characters: number(selection, "characters")?,
})
}
/// A context menu's spelling part, if it has one.
pub fn spelling(json: &str) -> io::Result<Option<Spelling>> {
let list = parse(json)?;
let items = entries(&list, "menu")?;
let commands: Vec<&str> = items
.iter()
.filter_map(|item| item["command"].as_str())
.collect();
if !commands
.iter()
.any(|command| command.starts_with(".uno:SpellCheckIgnoreAll"))
{
return Ok(None);
}
let suggestions = items
.iter()
.filter_map(|item| {
let rule = item["command"]
.as_str()?
.strip_prefix(".uno:SpellCheckApplySuggestion?ApplyRule:string=")?;
Some((item["text"].as_str()?.to_string(), rule.to_string()))
})
.collect();
Ok(Some(Spelling { suggestions }))
}
/// A heading from `.uno:Outline`.
#[derive(Clone, Debug, PartialEq)]
pub struct Heading {
pub text: String,
/// 0 for the top level.
pub level: u64,
pub rect: Rect,
/// The cursor sits under it.
pub current: bool,
}
/// The document's headings, in order.
pub fn outline(json: &str) -> io::Result<Vec<Heading>> {
let list = parse(json)?;
entries(&list, "outline")?
.iter()
.map(|entry| {
Ok(Heading {
text: text(entry, "text")?,
level: number(entry, "level")?,
rect: rect(&text(entry, "rect")?)?,
current: entry["current"]
.as_bool()
.ok_or_else(|| invalid(format!("no current flag: {entry}")))?,
})
})
.collect()
}
/// The document's comments, in kernel order.
pub fn notes(json: &str) -> io::Result<Vec<Note>> {
let list = parse(json)?;
entries(&list, "comments")?
.iter()
.map(|entry| {
Ok(Note {
id: number(entry, "id")?.to_string(),
parent: number(entry, "parentId")?.to_string(),
author: text(entry, "author")?,
text: plain(&text(entry, "html")?),
resolved: text(entry, "resolved")? == "true",
at: text(entry, "dateTime")?,
anchor: rect(&text(entry, "anchorPos")?)?,
})
})
.collect()
}
/// The document's tracked changes, in kernel order.
pub fn changes(json: &str) -> io::Result<Vec<Change>> {
let list = parse(json)?;
entries(&list, "redlines")?
.iter()
.map(|entry| {
let range = text(entry, "textRange")?;
let first = range.split(';').next().unwrap_or_default();
Ok(Change {
index: number(entry, "index")?,
author: text(entry, "author")?,
kind: text(entry, "type")?,
description: text(entry, "description")?,
at: text(entry, "dateTime")?,
anchor: (!first.trim().is_empty())
.then(|| rect(first))
.transpose()?,
})
})
.collect()
}
/// A bookmark from `.uno:Bookmarks`.
#[derive(Clone, Debug, PartialEq)]
pub struct Bookmark {
pub name: String,
/// None when the layout does not show it.
pub rect: Option<Rect>,
}
/// The document's bookmarks.
pub fn bookmarks(json: &str) -> io::Result<Vec<Bookmark>> {
let list = parse(json)?;
entries(&list, "bookmarks")?
.iter()
.map(|entry| {
Ok(Bookmark {
name: text(entry, "name")?,
rect: entry
.get("rect")
.map(|_| rect(&text(entry, "rect")?))
.transpose()?,
})
})
.collect()
}
/// The selected formula from `.uno:Formula`, if one is.
pub fn formula(json: &str) -> io::Result<Option<String>> {
let list = parse(json)?;
match &list["formula"] {
serde_json::Value::Null => Ok(None),
value => value
.as_str()
.map(|formula| Some(formula.to_string()))
.ok_or_else(|| invalid(format!("a bad formula: {value}"))),
}
}
fn parse(json: &str) -> io::Result<serde_json::Value> {
serde_json::from_str(json).map_err(|error| invalid(format!("a bad kernel list: {error}")))
}
fn entries<'a>(list: &'a serde_json::Value, key: &str) -> io::Result<&'a Vec<serde_json::Value>> {
list[key]
.as_array()
.ok_or_else(|| invalid(format!("the list has no {key}")))
}
fn text(entry: &serde_json::Value, key: &str) -> io::Result<String> {
entry[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| invalid(format!("an entry has no {key}: {entry}")))
}
fn number(entry: &serde_json::Value, key: &str) -> io::Result<u64> {
entry[key]
.as_u64()
.ok_or_else(|| invalid(format!("an entry has no {key}: {entry}")))
}
/// "x, y, w, h" in twips.
fn rect(text: &str) -> io::Result<Rect> {
let parts: Vec<i32> = text
.split(',')
.map(|part| part.trim().parse())
.collect::<Result<_, _>>()
.map_err(|_| invalid(format!("a bad rectangle: {text}")))?;
match parts[..] {
[x, y, w, h] => Ok((x, y, w, h)),
_ => Err(invalid(format!("a bad rectangle: {text}"))),
}
}
/// The kernel's simple comment HTML as text.
fn plain(html: &str) -> String {
let mut out = String::new();
let mut rest = html;
// An empty paragraph holds one br.
let mut broke = false;
while let Some(open) = rest.find('<') {
out.push_str(&rest[..open]);
broke &= open == 0;
let Some(close) = rest[open..].find('>') else {
break;
};
let tag = rest[open + 1..open + close].trim().to_ascii_lowercase();
if tag.starts_with("br") || ((tag == "/div" || tag == "/p") && !broke) {
out.push('\n');
}
broke = tag.starts_with("br");
rest = &rest[open + close + 1..];
}
out.push_str(rest);
// The last paragraph's end is no line.
out.strip_suffix('\n')
.unwrap_or(&out)
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&#39;", "'")
.replace("&nbsp;", " ")
.replace("&amp;", "&")
}
fn invalid(message: String) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn comments_and_changes_parse() {
let notes = notes(r#"{"comments":[{"id":1,"parentId":0,"author":"A","html":"<div>One &amp; two</div><div>three</div>","resolved":"false","dateTime":"2026-10-04T10:00:00","anchorPos":"4490, 14759, 1, 231","textRange":""}]}"#)
.expect("notes parse");
assert_eq!(notes[0].text, "One & two\nthree");
assert_eq!(
plain("<div>a</div><div><br/></div><div>Next</div>"),
"a\n\nNext"
);
assert_eq!(plain("<div>a<br/>b</div>"), "a\nb");
assert_eq!(
plain("<div>a</div><div><br/></div><div><br/></div>"),
"a\n\n"
);
assert_eq!(notes[0].anchor, (4490, 14759, 1, 231));
let changes = changes(r#"{"redlines":[{"index":1,"author":"A","type":"Insert","comment":"","description":"Insert x","dateTime":"2026-10-04T10:00:00","textRange":"4490, 14759, 648, 230; 1, 2, 3, 4"}]}"#)
.expect("changes parse");
assert_eq!(changes[0].anchor, Some((4490, 14759, 648, 230)));
assert!(super::notes(r#"{"comments":[{"id":1}]}"#).is_err());
assert_eq!(formula("{}").expect("empty"), None);
let counts = counts(r#"{"document":{"words":11,"characters":41,"charactersNoSpaces":31},"selection":{"words":2,"characters":7,"charactersNoSpaces":6}}"#)
.expect("counts parse");
assert_eq!((counts.words, counts.selected_characters), (11, 7));
let menu = r#"{"menu":[{"text":"The","type":"command","command":".uno:SpellCheckApplySuggestion?ApplyRule:string=Spelling_The"},{"type":"separator"},{"text":"Ignore All","type":"command","command":".uno:SpellCheckIgnoreAll?Type:string=Spelling"}]}"#;
let found = spelling(menu)
.expect("the menu parses")
.expect("a spelling menu");
assert_eq!(found.suggestions, [("The".into(), "Spelling_The".into())]);
let other = r#"{"menu":[{"text":"Cut","type":"command","command":".uno:Cut"}]}"#;
assert_eq!(spelling(other).expect("the menu parses"), None);
}
}
+374
View File
@@ -0,0 +1,374 @@
//! A sheet's row and column geometry from `.uno:SheetGeometryData`.
use std::io;
mod analysis;
pub mod csv;
mod data;
mod page;
pub use analysis::*;
pub use data::*;
pub use page::*;
/// The query for sizes and hidden flags of both axes.
pub const GEOMETRY: &str = ".uno:SheetGeometryData?columns=true&rows=true&sizes=true&hidden=true&filtered=false&groups=false";
/// One axis: runs of equal size, to each last index.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Axis {
/// (last index, size in twips); hidden runs are 0.
runs: Vec<(u32, i32)>,
}
/// Both axes of the shown sheet.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Geometry {
pub rows: Axis,
pub columns: Axis,
}
impl Axis {
/// How many rows or columns.
pub fn count(&self) -> u32 {
self.runs.last().map_or(0, |&(last, _)| last + 1)
}
/// The size of `index` in twips; 0 when hidden.
pub fn size(&self, index: u32) -> i32 {
self.runs
.iter()
.find(|&&(last, _)| index <= last)
.map_or(0, |&(_, size)| size)
}
/// Where `index` starts, in twips.
pub fn start(&self, index: u32) -> i32 {
let (mut at, mut first) = (0i64, 0u32);
for &(last, size) in &self.runs {
if index <= last {
return clamp(at + i64::from(index - first) * i64::from(size));
}
at += i64::from(last - first + 1) * i64::from(size);
first = last + 1;
}
clamp(at)
}
/// The index under `twips`; the last one past the end.
pub fn at(&self, twips: i32) -> u32 {
let (mut at, mut first) = (0i64, 0u32);
let twips = i64::from(twips.max(0));
for &(last, size) in &self.runs {
let span = i64::from(last - first + 1) * i64::from(size);
if size > 0 && twips < at + span {
let into = u32::try_from((twips - at) / i64::from(size)).expect("inside a run");
return first + into;
}
at += span;
first = last + 1;
}
self.count().saturating_sub(1)
}
}
fn clamp(twips: i64) -> i32 {
i32::try_from(twips).unwrap_or(i32::MAX)
}
/// Parses the kernel's geometry JSON.
pub fn geometry(json: &str) -> io::Result<Geometry> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad sheet geometry: {error}")))?;
let axis = |name: &str| -> io::Result<Axis> {
let field = |key: &str| {
value[name][key]
.as_str()
.ok_or_else(|| io::Error::other(format!("no {name} {key} in the geometry")))
};
merge(&runs(field("sizes")?)?, &flags(field("hidden")?)?)
};
Ok(Geometry {
rows: axis("rows")?,
columns: axis("columns")?,
})
}
/// "value:last value:last " as (last, value) runs.
fn runs(text: &str) -> io::Result<Vec<(u32, i32)>> {
text.split_whitespace()
.map(|run| {
let bad = || io::Error::other(format!("a bad geometry run: {run}"));
let (value, last) = run.split_once(':').ok_or_else(bad)?;
Ok((
last.parse().map_err(|_| bad())?,
value.parse().map_err(|_| bad())?,
))
})
.collect()
}
/// "value:last last last ": each later run flips the value.
fn flags(text: &str) -> io::Result<Vec<(u32, i32)>> {
let mut parts = text.split_whitespace();
let bad = |part: &str| io::Error::other(format!("a bad flag run: {part}"));
let head = parts.next().ok_or_else(|| bad(text))?;
let (value, last) = head.split_once(':').ok_or_else(|| bad(head))?;
let mut value: i32 = value.parse().map_err(|_| bad(head))?;
let mut list = vec![(last.parse().map_err(|_| bad(head))?, value)];
for part in parts {
value = 1 - value;
list.push((part.parse().map_err(|_| bad(part))?, value));
}
Ok(list)
}
/// Sizes with hidden runs set to 0.
fn merge(sizes: &[(u32, i32)], hidden: &[(u32, i32)]) -> io::Result<Axis> {
let mut runs: Vec<(u32, i32)> = Vec::new();
let (mut size, mut hide) = (sizes.iter().peekable(), hidden.iter().peekable());
let mut first = 0u32;
while let (Some(&&(size_last, width)), Some(&&(hide_last, hidden))) = (size.peek(), hide.peek())
{
let last = size_last.min(hide_last);
let value = if hidden != 0 { 0 } else { width };
match runs.last_mut() {
Some((end, run)) if *run == value => *end = last,
_ => runs.push((last, value)),
}
first = last + 1;
if size_last == last {
size.next();
}
if hide_last == last {
hide.next();
}
}
if size.peek().is_some() || hide.peek().is_some() {
return Err(io::Error::other(format!(
"geometry runs disagree past index {first}"
)));
}
Ok(Axis { runs })
}
/// What refers to a sheet from elsewhere.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct References {
/// Formula cells on other sheets.
pub formulas: u64,
/// Named ranges.
pub names: u64,
/// The first such cell, as "$U.A1"; empty when none.
pub first: String,
/// Formulas and names whose targets show only at run time.
pub dynamic: u64,
}
/// The query for references to sheet `sheet`, from 0.
pub fn references_query(sheet: usize) -> String {
format!(".uno:SheetReferences?sheet={sheet}")
}
/// Parses `.uno:SheetReferences`.
pub fn references(json: &str) -> io::Result<References> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad sheet references: {error}")))?;
let number = |key: &str| {
value[key]
.as_u64()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
};
Ok(References {
formulas: number("formulas")?,
names: number("names")?,
first: value["first"]
.as_str()
.ok_or_else(|| io::Error::other(format!("no first in {value}")))?
.to_string(),
dynamic: number("dynamic")?,
})
}
/// The workbook's named ranges (TABLE-06).
pub const NAMES: &str = ".uno:DefinedNames";
/// One named range.
#[derive(Clone, Debug, PartialEq)]
pub struct Name {
pub name: String,
/// The sheet it belongs to; empty for the workbook.
pub scope: String,
/// What it refers to, as a formula shows it.
pub formula: String,
/// The absolute range it names; empty for a formula.
pub range: String,
/// It lost a reference or holds an error.
pub broken: bool,
}
/// Parses `.uno:DefinedNames`.
pub fn names(json: &str) -> io::Result<Vec<Name>> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad names: {error}")))?;
let bad = || io::Error::other(format!("unreadable names: {value}"));
value["names"]
.as_array()
.ok_or_else(bad)?
.iter()
.map(|entry| {
let text = |key: &str| entry[key].as_str().map(str::to_string).ok_or_else(bad);
Ok(Name {
name: text("name")?,
scope: text("scope")?,
formula: text("formula")?,
range: text("range")?,
broken: entry["broken"].as_bool().ok_or_else(bad)?,
})
})
.collect()
}
/// The selection as one absolute range (TABLE-06).
pub const SELECTED: &str = ".uno:SelectedRange";
/// The selection as one range, and the data inside it.
#[derive(Clone, Debug, PartialEq)]
pub struct Selection {
/// Absolute, with the sheet.
pub range: String,
/// First column, row, last column, row; None with no data.
pub area: Option<(u32, u32, u32, u32)>,
/// The area as an absolute range; empty with no data.
pub data: String,
/// The area's first row.
pub top: Vec<String>,
/// The kernel takes the first row for headers.
pub header: bool,
}
/// Parses `.uno:SelectedRange`; None when several ranges are selected.
pub fn selected_range(json: &str) -> io::Result<Option<Selection>> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad selection: {error}")))?;
let bad = || io::Error::other(format!("unreadable selection: {value}"));
let range = value["range"].as_str().ok_or_else(bad)?;
if range.is_empty() {
return Ok(None);
}
let Some(area) = value["area"].as_array() else {
return Ok(Some(Selection {
range: range.to_string(),
area: None,
data: String::new(),
top: Vec::new(),
header: false,
}));
};
let corner = |at: usize| -> io::Result<u32> {
area.get(at)
.and_then(|n| n.as_str()?.parse().ok())
.ok_or_else(bad)
};
let top = value["top"]
.as_array()
.ok_or_else(bad)?
.iter()
.map(|text| text.as_str().map(str::to_string).ok_or_else(bad))
.collect::<io::Result<_>>()?;
Ok(Some(Selection {
range: range.to_string(),
area: Some((corner(0)?, corner(1)?, corner(2)?, corner(3)?)),
data: value["data"].as_str().ok_or_else(bad)?.to_string(),
top,
header: value["header"].as_bool().ok_or_else(bad)?,
}))
}
/// The query that checks whether `name` can name a range.
pub fn name_check_query(name: &str) -> String {
format!("{NAMES}?name={}", encode(name))
}
/// `text` percent-encoded for a query value.
fn encode(text: &str) -> String {
text.bytes()
.map(|byte| match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
(byte as char).to_string()
}
other => format!("%{other:02X}"),
})
.collect()
}
/// A name check: "valid", "address" or "characters".
pub fn name_check(json: &str) -> io::Result<&'static str> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad name check: {error}")))?;
match value["name"].as_str() {
Some("valid") => Ok("valid"),
Some("address") => Ok("address"),
Some("characters") => Ok("characters"),
_ => Err(io::Error::other(format!("unreadable name check: {value}"))),
}
}
/// The column's letters: 0 is "A", 26 is "AA".
pub fn column_name(index: u32) -> String {
let mut name = Vec::new();
let mut n = index + 1;
while n > 0 {
let digit = u8::try_from((n - 1) % 26).expect("a letter");
name.push(b'A' + digit);
n = (n - 1) / 26;
}
name.reverse();
String::from_utf8(name).expect("ASCII letters")
}
/// The A1 address of a cell, both from 0.
pub fn address(column: u32, row: u32) -> String {
format!("{}{}", column_name(column), row + 1)
}
#[cfg(test)]
mod tests {
use super::*;
const JSON: &str = r#"{"commandName":".uno:SheetGeometryData","maxtiledcolumn":"1023","maxtiledrow":"500000",
"columns":{"sizes":"1280:1 2000:2 1280:1023 ","hidden":"0:0 1 1023 "},
"rows":{"sizes":"256:1048575 ","hidden":"0:1048575 "}}"#;
#[test]
fn hidden_columns_fold_and_positions_add_up() {
let geometry = geometry(JSON).expect("the geometry parses");
let columns = &geometry.columns;
assert_eq!(columns.count(), 1024);
assert_eq!(columns.size(1), 0, "B hides");
assert_eq!(columns.size(2), 2000);
assert_eq!(columns.start(2), 1280);
assert_eq!(columns.start(3), 3280);
assert_eq!(columns.at(1279), 0);
assert_eq!(columns.at(1280), 2, "a hidden column takes no room");
assert_eq!(columns.at(i32::MAX), 1023);
assert_eq!(geometry.rows.start(10), 2560);
assert_eq!(geometry.rows.at(2559), 9);
}
#[test]
fn names_and_addresses() {
assert_eq!(column_name(0), "A");
assert_eq!(column_name(25), "Z");
assert_eq!(column_name(26), "AA");
assert_eq!(column_name(16383), "XFD");
assert_eq!(address(1, 9), "B10");
}
#[test]
fn broken_runs_fail() {
assert!(runs("12:x").is_err());
assert!(flags("0:3 x").is_err());
assert_eq!(flags("1:2 5").expect("flags"), [(2, 1), (5, 0)]);
assert!(merge(&[(3, 10)], &[(5, 0)]).is_err(), "lengths must agree");
}
}
+199
View File
@@ -0,0 +1,199 @@
//! Charts and pivot tables read from the kernel (TABLE-10, 11).
use std::io;
use serde_json::{Value, json};
/// The one selected chart.
pub const CHART: &str = ".uno:Chart";
/// The pivot table at the cursor.
pub const PIVOT: &str = ".uno:PivotTable";
/// Chart kinds the kernel takes; it reads others as "other".
pub const CHART_KINDS: [&str; 5] = ["column", "bar", "line", "scatter", "pie"];
/// Pivot data functions.
pub const PIVOT_FUNCTIONS: [&str; 5] = ["sum", "count", "average", "max", "min"];
pub(super) fn parse(json: &str, what: &str) -> io::Result<Value> {
serde_json::from_str(json).map_err(|error| io::Error::other(format!("bad {what}: {error}")))
}
pub(super) fn text(value: &Value, key: &str) -> io::Result<String> {
value[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
pub(super) fn flag(value: &Value, key: &str) -> io::Result<bool> {
value[key]
.as_bool()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
pub(super) fn texts(value: &Value, key: &str) -> io::Result<Vec<String>> {
value[key]
.as_array()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))?
.iter()
.map(|item| {
item.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("bad {key} in {value}")))
})
.collect()
}
/// A chart's kind, titles and legend.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Look {
pub kind: String,
pub title: String,
pub legend: bool,
pub x_title: String,
pub y_title: String,
}
impl Look {
/// The JSON the kernel's `Chart` argument takes.
pub fn to_json(&self) -> String {
json!({
"type": self.kind,
"title": self.title,
"legend": self.legend,
"xtitle": self.x_title,
"ytitle": self.y_title,
})
.to_string()
}
}
/// A selected chart: its object name, data and look.
#[derive(Clone, Debug, PartialEq)]
pub struct Chart {
pub name: String,
pub range: String,
pub col_headers: bool,
pub row_headers: bool,
pub look: Look,
}
/// Parses `.uno:Chart`; none when no chart is selected.
pub fn chart(json: &str) -> io::Result<Option<Chart>> {
let value = parse(json, "chart")?;
if value.get("name").is_none() {
return Ok(None);
}
Ok(Some(Chart {
name: text(&value, "name")?,
range: text(&value, "range")?,
col_headers: flag(&value, "colHeaders")?,
row_headers: flag(&value, "rowHeaders")?,
look: look(&value)?,
}))
}
/// The look members of a chart read.
pub(crate) fn look(value: &Value) -> io::Result<Look> {
Ok(Look {
kind: text(value, "type")?,
title: text(value, "title")?,
legend: flag(value, "legend")?,
x_title: text(value, "xtitle")?,
y_title: text(value, "ytitle")?,
})
}
/// A pivot table's layout: fields by area, data with functions.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Layout {
pub rows: Vec<String>,
pub columns: Vec<String>,
pub pages: Vec<String>,
pub data: Vec<(String, String)>,
}
impl Layout {
/// The `Pivot` argument: from `source` to `dest`, or in place.
pub fn to_json(&self, source: &str, dest: &str) -> String {
let data: Vec<Value> = self
.data
.iter()
.map(|(field, function)| json!({ "field": field, "function": function }))
.collect();
json!({
"source": source,
"dest": dest,
"rows": self.rows,
"columns": self.columns,
"pages": self.pages,
"data": data,
})
.to_string()
}
}
/// The pivot table at the cursor.
#[derive(Clone, Debug, PartialEq)]
pub struct Pivot {
pub name: String,
/// Where it shows.
pub range: String,
/// Its data; empty when not from cells.
pub source: String,
pub fields: Vec<String>,
pub layout: Layout,
}
/// Parses `.uno:PivotTable`; none off a pivot table.
pub fn pivot(json: &str) -> io::Result<Option<Pivot>> {
let value = parse(json, "pivot table")?;
if value.get("name").is_none() {
return Ok(None);
}
let data = value["data"]
.as_array()
.ok_or_else(|| io::Error::other(format!("no data in {value}")))?
.iter()
.map(|item| Ok((text(item, "field")?, text(item, "function")?)))
.collect::<io::Result<_>>()?;
Ok(Some(Pivot {
name: text(&value, "name")?,
range: text(&value, "range")?,
source: text(&value, "source")?,
fields: texts(&value, "fields")?,
layout: Layout {
rows: texts(&value, "rows")?,
columns: texts(&value, "columns")?,
pages: texts(&value, "pages")?,
data,
},
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kernel_reads_parse() {
assert_eq!(
chart(r#"{"commandName":".uno:Chart"}"#).expect("none"),
None
);
let one = r#"{"name":"Object 1","range":"$S.$A$1:$B$4","colHeaders":true,"rowHeaders":false,"type":"bar","title":"T","legend":false,"xtitle":"","ytitle":"Y"}"#;
let one = chart(one).expect("a chart").expect("selected");
assert_eq!(
(one.look.kind.as_str(), one.look.y_title.as_str()),
("bar", "Y")
);
assert!(chart(r#"{"name":"Object 1"}"#).is_err(), "parts missing");
let table = r#"{"name":"P","range":"$S.$E$1:$G$5","source":"$S.$A$1:$C$9","fields":["Region","Year","Sales"],"rows":["Region"],"columns":[],"pages":[],"data":[{"field":"Sales","function":"sum"}]}"#;
let table = pivot(table).expect("a pivot").expect("here");
assert_eq!(table.layout.data, [("Sales".into(), "sum".into())]);
assert_eq!(
pivot(r#"{"commandName":".uno:PivotTable"}"#).expect("none"),
None
);
}
}
+182
View File
@@ -0,0 +1,182 @@
//! The kernel's CSV filter options (TABLE-12, 13).
/// How the kernel reads one column.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Column {
Standard,
Text,
DateMdy,
DateDmy,
DateYmd,
Skip,
}
pub const COLUMNS: [Column; 6] = [
Column::Standard,
Column::Text,
Column::DateMdy,
Column::DateDmy,
Column::DateYmd,
Column::Skip,
];
impl Column {
fn code(self) -> u8 {
match self {
Column::Standard => 1,
Column::Text => 2,
Column::DateMdy => 3,
Column::DateDmy => 4,
Column::DateYmd => 5,
Column::Skip => 9,
}
}
}
/// Text encodings the import offers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Encoding {
Utf8,
Utf16,
Gb18030,
Big5,
ShiftJis,
EucKr,
Windows1252,
Windows1251,
Latin1,
}
pub const ENCODINGS: [Encoding; 9] = [
Encoding::Utf8,
Encoding::Utf16,
Encoding::Gb18030,
Encoding::Big5,
Encoding::ShiftJis,
Encoding::EucKr,
Encoding::Windows1252,
Encoding::Windows1251,
Encoding::Latin1,
];
impl Encoding {
/// The label people know it by.
pub fn label(self) -> &'static str {
match self {
Encoding::Utf8 => "UTF-8",
Encoding::Utf16 => "UTF-16",
Encoding::Gb18030 => "GB18030",
Encoding::Big5 => "Big5",
Encoding::ShiftJis => "Shift_JIS",
Encoding::EucKr => "EUC-KR",
Encoding::Windows1252 => "Windows-1252",
Encoding::Windows1251 => "Windows-1251",
Encoding::Latin1 => "ISO-8859-1",
}
}
/// The kernel's `rtl_TextEncoding`.
fn kernel(self) -> u16 {
match self {
Encoding::Utf8 => 76,
Encoding::Utf16 => 0xFFFF,
Encoding::Gb18030 => 85,
Encoding::Big5 => 68,
Encoding::ShiftJis => 64,
Encoding::EucKr => 79,
Encoding::Windows1252 => 1,
Encoding::Windows1251 => 34,
Encoding::Latin1 => 12,
}
}
}
/// US English numbers: `.` decimal, `,` thousands.
const LANGUAGE: u16 = 1033;
/// How a text file becomes a sheet.
#[derive(Clone, Debug, PartialEq)]
pub struct Import {
pub separator: char,
pub quote: Option<char>,
pub encoding: Encoding,
/// Kinds of the first columns; the rest are standard.
pub columns: Vec<Column>,
}
impl Import {
/// The kernel's filter options for this import.
pub fn filter(&self) -> String {
let columns: Vec<String> = self
.columns
.iter()
.enumerate()
.map(|(index, column)| format!("{}/{}", index + 1, column.code()))
.collect();
// Token order: sc/source/ui/dbgui/asciiopt.cxx.
[
u32::from(self.separator).to_string(),
self.quote.map_or(0, u32::from).to_string(),
self.encoding.kernel().to_string(),
"1".into(),
columns.join("/"),
LANGUAGE.to_string(),
// Quoted as text, special numbers, two export flags, trim.
"false,false,false,false,false".into(),
"0".into(),
// Formulas stay text; no BOM; scientific numbers read.
"false,false,true".into(),
]
.join(",")
}
}
/// Options writing the view's sheet as shown, UTF-8.
pub fn export(separator: char) -> String {
[
u32::from(separator).to_string(),
"34".into(),
Encoding::Utf8.kernel().to_string(),
"1".into(),
"1/1".into(),
LANGUAGE.to_string(),
// Quote all text, special numbers, as shown, formulas, trim.
"false,false,true,false,false".into(),
"0".into(),
"false,false,false".into(),
]
.join(",")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imports_name_every_token() {
let import = Import {
separator: '\t',
quote: Some('"'),
encoding: Encoding::Gb18030,
columns: vec![Column::Text, Column::Standard, Column::DateYmd],
};
assert_eq!(
import.filter(),
"9,34,85,1,1/2/2/1/3/5,1033,false,false,false,false,false,0,false,false,true"
);
let bare = Import {
quote: None,
columns: Vec::new(),
..import
};
assert!(bare.filter().starts_with("9,0,85,1,,1033,"));
}
#[test]
fn exports_write_values_as_shown() {
assert_eq!(
export(';'),
"59,34,76,1,1/1,1033,false,false,true,false,false,0,false,false,false"
);
}
}
+277
View File
@@ -0,0 +1,277 @@
//! Formats, filters, rules and links read from the kernel.
use std::io;
/// The current cell's format code and kind.
pub const NUMBER: &str = ".uno:NumberFormatCode";
/// A filter column's entries.
pub const FILTER: &str = ".uno:AutoFilterValues";
/// A cell's choices: its validation list.
pub const LIST: &str = ".uno:DataSelectValues";
/// The current cell's validation.
pub const VALIDATION: &str = ".uno:Validation";
/// The shown sheet's conditional formats.
pub const FORMATS: &str = ".uno:ConditionalFormats";
/// Sources whose data shows as last saved (§9.3).
pub const LINKS: &str = ".uno:ExternalLinks";
fn parse(json: &str, what: &str) -> io::Result<serde_json::Value> {
serde_json::from_str(json).map_err(|error| io::Error::other(format!("bad {what}: {error}")))
}
fn text(value: &serde_json::Value, key: &str) -> io::Result<String> {
value[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
fn flag(value: &serde_json::Value, key: &str) -> io::Result<bool> {
value[key]
.as_bool()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
/// The query that checks a format code.
pub fn number_check_query(code: &str) -> String {
format!("{NUMBER}?code={}", super::encode(code))
}
/// Parses a code check.
pub fn number_valid(json: &str) -> io::Result<bool> {
flag(&parse(json, "format check")?, "valid")
}
/// Parses `.uno:NumberFormatCode`: the code and its kind.
pub fn number_format(json: &str) -> io::Result<(String, String)> {
let value = parse(json, "number format")?;
Ok((text(&value, "code")?, text(&value, "type")?))
}
/// The query for a cell's filter entries or choices.
pub fn cell_query(base: &str, column: u32, row: u32) -> String {
format!("{base}?col={column}&row={row}")
}
/// One filter entry, as the kernel's own menu shows it.
#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
pub text: String,
/// Other columns' filters hide its rows.
pub hidden: bool,
/// The column's own filter keeps it.
pub selected: bool,
}
/// A filter column: whether it filters, and its entries.
#[derive(Clone, Debug, PartialEq)]
pub struct Filter {
pub filtered: bool,
pub entries: Vec<Entry>,
}
/// Parses `.uno:AutoFilterValues`.
pub fn filter_values(json: &str) -> io::Result<Filter> {
let value = parse(json, "filter values")?;
let entries = value["values"]
.as_array()
.ok_or_else(|| io::Error::other(format!("no values in {value}")))?
.iter()
.map(|entry| {
Ok(Entry {
text: text(entry, "text")?,
hidden: flag(entry, "hidden")?,
selected: flag(entry, "selected")?,
})
})
.collect::<io::Result<_>>()?;
Ok(Filter {
filtered: flag(&value, "filtered")?,
entries,
})
}
/// Parses `.uno:ExternalLinks`.
pub fn links(json: &str) -> io::Result<Vec<String>> {
let value = parse(json, "links")?;
value["links"]
.as_array()
.ok_or_else(|| io::Error::other(format!("no links in {value}")))?
.iter()
.map(|link| {
link.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("a bad link: {link}")))
})
.collect()
}
/// Parses `.uno:DataSelectValues`.
pub fn list_values(json: &str) -> io::Result<Vec<String>> {
let value = parse(json, "choices")?;
value["values"]
.as_array()
.ok_or_else(|| io::Error::other(format!("no values in {value}")))?
.iter()
.map(|entry| {
entry
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("a bad choice: {entry}")))
})
.collect()
}
/// A validation as the kernel reports and takes it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Validation {
/// any, whole, decimal, date, time, textlength, list, custom.
pub kind: String,
pub operator: String,
pub value1: String,
pub value2: String,
/// List entries to set; the kernel quotes them.
pub list: Vec<String>,
pub dropdown: bool,
pub ignore_blank: bool,
pub show_input: bool,
pub input_title: String,
pub input_message: String,
pub show_error: bool,
pub error_title: String,
pub error_message: String,
/// stop, warning or info.
pub error_style: String,
}
impl Validation {
/// The rule `rules.validation` takes.
pub fn to_json(&self) -> String {
serde_json::json!({
"type": self.kind,
"operator": self.operator,
"value1": self.value1,
"value2": self.value2,
"list": self.list,
"dropdown": self.dropdown,
"ignoreBlank": self.ignore_blank,
"showInput": self.show_input,
"inputTitle": self.input_title,
"inputMessage": self.input_message,
"showError": self.show_error,
"errorTitle": self.error_title,
"errorMessage": self.error_message,
"errorStyle": self.error_style,
})
.to_string()
}
}
/// Parses `.uno:Validation`.
pub fn validation(json: &str) -> io::Result<Validation> {
let value = parse(json, "validation")?;
let kind = text(&value, "type")?;
// A cell without a rule reports its type alone.
if value.get("operator").is_none() {
return Ok(Validation {
kind,
..Validation::default()
});
}
Ok(Validation {
kind,
operator: text(&value, "operator")?,
value1: text(&value, "value1")?,
value2: text(&value, "value2")?,
list: Vec::new(),
dropdown: flag(&value, "dropdown")?,
ignore_blank: flag(&value, "ignoreBlank")?,
show_input: flag(&value, "showInput")?,
input_title: text(&value, "inputTitle")?,
input_message: text(&value, "inputMessage")?,
show_error: flag(&value, "showError")?,
error_title: text(&value, "errorTitle")?,
error_message: text(&value, "errorMessage")?,
error_style: text(&value, "errorStyle")?,
})
}
/// One conditional format on the shown sheet.
#[derive(Clone, Debug, PartialEq)]
pub struct Format {
pub key: u64,
pub range: String,
/// cell, scale, databar, iconset or other.
pub kind: String,
/// The cell style a cell rule applies.
pub style: String,
pub value: String,
}
/// Parses `.uno:ConditionalFormats`.
pub fn formats(json: &str) -> io::Result<Vec<Format>> {
let value = parse(json, "conditional formats")?;
value["formats"]
.as_array()
.ok_or_else(|| io::Error::other(format!("no formats in {value}")))?
.iter()
.map(|entry| {
let cell = text(entry, "kind")? == "cell";
let optional = |key| {
if cell {
text(entry, key)
} else {
Ok(String::new())
}
};
Ok(Format {
key: entry["key"]
.as_u64()
.ok_or_else(|| io::Error::other(format!("no key in {entry}")))?,
range: text(entry, "range")?,
kind: text(entry, "kind")?,
style: optional("style")?,
value: optional("value1")?,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kernel_reads_parse() {
let filter = r#"{"filtered":true,"values":[{"text":"a","hidden":false,"selected":true},{"text":"","hidden":true,"selected":false}]}"#;
let filter = filter_values(filter).expect("entries");
assert!(filter.filtered && filter.entries[1].hidden && !filter.entries[1].selected);
assert_eq!(
list_values(r#"{"values":["Red","Green"]}"#).expect("list"),
["Red", "Green"]
);
assert_eq!(validation(r#"{"type":"any"}"#).expect("none").kind, "any");
let help = r#"{"type":"any","operator":"equal","value1":"","value2":"","dropdown":true,"ignoreBlank":true,"showInput":true,"inputTitle":"","inputMessage":"An id","showError":false,"errorTitle":"","errorMessage":"","errorStyle":"stop"}"#;
assert_eq!(validation(help).expect("help").input_message, "An id");
assert!(
validation(r#"{"type":"list","operator":"equal","dropdown":true}"#).is_err(),
"a part is missing"
);
let formats = formats(
r#"{"formats":[{"key":1,"range":"A1:A3","kind":"cell","style":"Good","value1":"5"},{"key":2,"range":"B1","kind":"scale"}]}"#,
)
.expect("formats");
assert_eq!(
(formats[0].style.as_str(), formats[1].kind.as_str()),
("Good", "scale")
);
assert!(
number_format(r#"{"code":"0.00"}"#).is_err(),
"a missing kind fails"
);
assert_eq!(
number_check_query("0.0 %"),
".uno:NumberFormatCode?code=0.0%20%25"
);
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Print layout and sheet protection (TABLE-14, 15).
use std::io;
use serde_json::{Value, json};
use super::analysis::{flag, parse, texts};
/// The shown sheet's print layout.
pub const LAYOUT: &str = ".uno:PrintLayout";
/// The shown sheet's protection.
pub const PROTECTION: &str = ".uno:SheetProtection";
/// Actions a protected sheet may allow, in kernel names.
pub const PROTECT_OPTIONS: [&str; 8] = [
"selectLocked",
"selectUnlocked",
"insertColumns",
"insertRows",
"deleteColumns",
"deleteRows",
"autofilter",
"pivot",
];
/// How printing scales the sheet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scale {
Percent(u16),
/// Pages wide and tall; 0 leaves one free.
Fit(u16, u16),
/// Pages in all.
Pages(u16),
}
/// Rows or columns, first to last, from 1.
pub type Span = (u32, u32);
/// What the kernel prints of the shown sheet.
#[derive(Clone, Debug, PartialEq)]
pub struct PrintLayout {
/// Print ranges; none prints the used area.
pub areas: Vec<String>,
pub rows: Option<Span>,
pub columns: Option<Span>,
pub landscape: bool,
pub scale: Scale,
/// Sheets sharing the page style.
pub sheets: Vec<String>,
/// Manual breaks at the cursor.
pub row_break: bool,
pub column_break: bool,
}
/// The JSON `page.setup` takes.
pub fn page_json(landscape: bool, scale: Scale) -> String {
match scale {
Scale::Percent(percent) => json!({ "landscape": landscape, "scale": percent }),
Scale::Fit(wide, tall) => json!({ "landscape": landscape, "fit": [wide, tall] }),
Scale::Pages(pages) => json!({ "landscape": landscape, "pages": pages }),
}
.to_string()
}
/// Repeated rows as `print.area` takes them.
pub fn rows_ref(span: Option<Span>) -> String {
span.map_or_else(String::new, |(first, last)| format!("${first}:${last}"))
}
/// Repeated columns as `print.area` takes them.
pub fn columns_ref(span: Option<Span>) -> String {
span.map_or_else(String::new, |(first, last)| {
let name = |index: u32| super::column_name(index - 1);
format!("${}:${}", name(first), name(last))
})
}
fn number(value: &Value, key: &str) -> io::Result<u64> {
value[key]
.as_u64()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
fn span(value: &Value, key: &str) -> io::Result<Option<Span>> {
let Some(node) = value.get(key) else {
return Ok(None);
};
let bound = |end| -> io::Result<u32> {
u32::try_from(number(node, end)?).map_err(|_| io::Error::other(format!("bad {key}")))
};
Ok(Some((bound("first")?, bound("last")?)))
}
/// Parses `.uno:PrintLayout`.
pub fn print_layout(json: &str) -> io::Result<PrintLayout> {
let value = parse(json, "print layout")?;
let small = |key| -> io::Result<u16> {
u16::try_from(number(&value, key)?).map_err(|_| io::Error::other(format!("bad {key}")))
};
let (percent, wide, tall, pages) = (
small("scale")?,
small("fitWidth")?,
small("fitHeight")?,
small("pages")?,
);
// The kernel's order: pages, then fit, then percent.
let scale = match () {
_ if pages > 0 => Scale::Pages(pages),
_ if wide > 0 || tall > 0 => Scale::Fit(wide, tall),
_ if percent > 0 => Scale::Percent(percent),
_ => return Err(io::Error::other(format!("no scale in {value}"))),
};
Ok(PrintLayout {
areas: texts(&value, "areas")?,
rows: span(&value, "rows")?,
columns: span(&value, "columns")?,
landscape: flag(&value, "landscape")?,
scale,
sheets: texts(&value, "sheets")?,
row_break: flag(&value, "rowBreak")?,
column_break: flag(&value, "columnBreak")?,
})
}
/// A sheet's protection as the kernel reports it.
#[derive(Clone, Debug, PartialEq)]
pub struct Protection {
pub protected: bool,
/// Unprotecting needs a password.
pub password: bool,
pub allow: Vec<String>,
}
/// Parses `.uno:SheetProtection`.
pub fn protection(json: &str) -> io::Result<Protection> {
let value = parse(json, "protection")?;
Ok(Protection {
protected: flag(&value, "protected")?,
password: flag(&value, "password")?,
allow: texts(&value, "allow")?,
})
}
/// The JSON `sheet.protect` takes to protect.
pub fn protect_json(password: &str, allow: &[String]) -> String {
json!({ "protect": true, "password": password, "allow": allow }).to_string()
}
/// The JSON `sheet.protect` takes to unprotect.
pub fn unprotect_json(password: &str) -> String {
json!({ "protect": false, "password": password }).to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layouts_read_each_scale() {
let json = r#"{"areas":["$A$1:$C$4"],"rows":{"first":1,"last":2},"rowBreak":false,
"columnBreak":true,"landscape":true,"scale":0,"pages":0,"fitWidth":1,"fitHeight":0,
"sheets":["Sheet1","Sheet2"]}"#;
let read = print_layout(json).unwrap();
assert_eq!(read.areas, ["$A$1:$C$4"]);
assert_eq!((read.rows, read.columns), (Some((1, 2)), None));
assert_eq!(read.scale, Scale::Fit(1, 0));
assert!(read.landscape && read.column_break && !read.row_break);
let both = json.replace(r#""scale":0"#, r#""scale":100"#);
assert_eq!(
print_layout(&both).unwrap().scale,
Scale::Fit(1, 0),
"fit wins"
);
let none = json.replace(r#""fitWidth":1"#, r#""fitWidth":0"#);
assert!(print_layout(&none).is_err(), "no scale is an error");
}
#[test]
fn spans_become_references() {
assert_eq!(rows_ref(Some((1, 3))), "$1:$3");
assert_eq!(columns_ref(Some((1, 28))), "$A:$AB");
assert_eq!(rows_ref(None), "");
}
}
+90
View File
@@ -0,0 +1,90 @@
//! A presentation's design read from the kernel (SHOW-01, 02).
use std::io;
use serde_json::Value;
mod check;
mod layers;
mod media;
mod motion;
mod objects;
mod parts;
mod playlist;
pub use check::*;
pub use layers::*;
pub use media::*;
pub use motion::*;
pub use objects::*;
pub use parts::*;
pub use playlist::*;
/// Masters, layouts and color sets of the shown slide.
pub const DESIGN: &str = ".uno:SlideDesign";
/// Layouts the slide panel offers, as kernel AutoLayout numbers.
pub const LAYOUTS: [u32; 12] = [20, 0, 1, 3, 19, 32, 12, 15, 14, 16, 18, 34];
/// The shown slide's design and the choices.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Design {
pub masters: Vec<String>,
pub master: String,
/// The view edits masters, not slides.
pub master_view: bool,
pub layout: u32,
/// The master's color set; empty without one.
pub theme: String,
pub themes: Vec<String>,
}
fn texts(value: &Value, key: &str) -> io::Result<Vec<String>> {
value[key]
.as_array()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))?
.iter()
.map(|item| {
item.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("bad {key} in {value}")))
})
.collect()
}
fn text(value: &Value, key: &str) -> io::Result<String> {
value[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
/// Parses `.uno:SlideDesign`.
pub fn design(json: &str) -> io::Result<Design> {
let value: Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad design: {error}")))?;
let layout = value["layout"]
.as_u64()
.and_then(|layout| u32::try_from(layout).ok())
.ok_or_else(|| io::Error::other(format!("no layout in {value}")))?;
Ok(Design {
masters: texts(&value, "masters")?,
master: text(&value, "master")?,
master_view: value["masterView"]
.as_bool()
.ok_or_else(|| io::Error::other(format!("no masterView in {value}")))?,
layout,
theme: text(&value, "theme")?,
themes: texts(&value, "themes")?,
})
}
#[cfg(test)]
mod tests {
#[test]
fn designs_parse_and_fail_on_gaps() {
let json = r#"{"masters":["A","B"],"master":"B","masterView":false,"layout":1,"theme":"","themes":["LibreOffice"]}"#;
let design = super::design(json).unwrap();
assert_eq!((design.master.as_str(), design.layout), ("B", 1));
assert!(super::design(&json.replace(r#""layout":1,"#, "")).is_err());
}
}
+63
View File
@@ -0,0 +1,63 @@
//! What may go wrong in a show (SHOW-14).
use std::io;
use serde_json::Value;
/// Fonts, links and unreadable objects of every slide and master.
pub const SLIDE_CHECK: &str = ".uno:SlideCheck";
/// One slide's or master's findings.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PageCheck {
/// Font families its text asks for.
pub fonts: Vec<String>,
/// Linked files, and whether each is missing.
pub links: Vec<(String, bool)>,
/// Names of objects the kernel cannot show.
pub broken: Vec<String>,
}
/// Slides in order, then masters by name.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Check {
pub slides: Vec<PageCheck>,
pub masters: Vec<(String, PageCheck)>,
}
fn page(value: &Value) -> io::Result<PageCheck> {
let bad = |what: &str| io::Error::other(format!("bad {what} in {value}"));
let texts = |key: &str| -> io::Result<Vec<String>> {
(value[key].as_array().ok_or_else(|| bad(key))?.iter())
.map(|item| item.as_str().map(str::to_string).ok_or_else(|| bad(key)))
.collect()
};
let links = (value["links"].as_array().ok_or_else(|| bad("links"))?.iter())
.map(|link| {
let url = link["url"].as_str().ok_or_else(|| bad("url"))?;
let missing = link["missing"].as_bool().ok_or_else(|| bad("missing"))?;
Ok((url.to_string(), missing))
})
.collect::<io::Result<_>>()?;
Ok(PageCheck {
fonts: texts("fonts")?,
links,
broken: texts("broken")?,
})
}
/// Parses `.uno:SlideCheck`.
pub fn check(json: &str) -> io::Result<Check> {
let value: Value = serde_json::from_str(json).map_err(io::Error::other)?;
let bad = |what: &str| io::Error::other(format!("bad {what} in {value}"));
let slides = (value["slides"].as_array().ok_or_else(|| bad("slides"))?.iter())
.map(page)
.collect::<io::Result<_>>()?;
let masters = (value["masters"].as_array().ok_or_else(|| bad("masters"))?.iter())
.map(|master| {
let name = master["name"].as_str().ok_or_else(|| bad("name"))?;
Ok((name.to_string(), page(master)?))
})
.collect::<io::Result<_>>()?;
Ok(Check { slides, masters })
}
+108
View File
@@ -0,0 +1,108 @@
//! A slide drawn as slideshow layers (SHOW-09).
use std::{collections::HashMap, io};
use serde_json::Value;
use crate::ipc::Unpack;
/// What a layer is.
#[derive(Clone, Debug, PartialEq)]
pub enum Part {
/// Still content: background, master, slide, field text.
Still,
/// One animated object; `hash` matches its effects.
Moving {
hash: String,
visible: bool,
/// x, y, width, height on the slide, 1/100 mm.
bounds: (i64, i64, i64, i64),
},
}
/// One layer with tile-format pixels.
pub struct Layer {
pub part: Part,
pub pixels: Vec<u8>,
}
/// A slide's layers, bottom first, at one pixel size.
pub struct Layers {
pub size: (u32, u32),
pub list: Vec<Layer>,
}
/// What the kernel sent for one layer.
enum Sent {
Layer(Part),
/// Where a master field goes, by object hash.
Placeholder(String),
/// A field's text for this slide, by object hash.
FieldText(String),
}
fn sent(json: &Value) -> io::Result<Sent> {
let bad = || io::Error::other(format!("bad layer {json}"));
let content = &json["content"];
let hash = || (content["hash"].as_str().map(str::to_string)).ok_or_else(bad);
if json["group"].as_str() == Some("TextFields") {
return Ok(Sent::FieldText(hash()?));
}
match json["type"].as_str() {
Some("bitmap") => Ok(Sent::Layer(Part::Still)),
Some("animated") => {
let at = |key: &str| content["bounds"][key].as_i64().ok_or_else(bad);
Ok(Sent::Layer(Part::Moving {
hash: hash()?,
visible: content["initVisible"].as_bool().ok_or_else(bad)?,
bounds: (at("x")?, at("y")?, at("width")?, at("height")?),
}))
}
Some("placeholder") => Ok(Sent::Placeholder(hash()?)),
_ => Err(bad()),
}
}
/// Parses the worker's slide layers reply; fields go in place.
pub fn layers(payload: &[u8]) -> io::Result<Layers> {
let mut unpack = Unpack::new(payload);
let size = (u32::try_from(unpack.u64()?), u32::try_from(unpack.u64()?));
let (Ok(width), Ok(height)) = size else {
return Err(io::Error::other("bad layer size"));
};
let count = unpack.u64()?;
let mut sent_list = Vec::new();
for _ in 0..count {
let json: Value = serde_json::from_str(&unpack.str()?).map_err(io::Error::other)?;
let pixels = (unpack.u64()? != 0).then(|| unpack.blob()).transpose()?;
let kind = sent(&json)?;
if pixels.is_some() == matches!(kind, Sent::Placeholder(_)) {
return Err(io::Error::other(format!("pixels do not fit layer {json}")));
}
sent_list.push((kind, pixels));
}
let mut texts: HashMap<String, Vec<u8>> = HashMap::new();
for (kind, pixels) in &mut sent_list {
if let Sent::FieldText(hash) = kind {
texts.insert(hash.clone(), pixels.take().expect("checked above"));
}
}
// A field hidden on this slide has no text.
let list = (sent_list.into_iter())
.filter_map(|(kind, pixels)| match kind {
Sent::Layer(part) => Some(Layer {
part,
pixels: pixels.expect("checked above"),
}),
Sent::Placeholder(hash) => texts.remove(&hash).map(|pixels| Layer {
part: Part::Still,
pixels,
}),
Sent::FieldText(_) => None,
})
.collect();
Ok(Layers {
size: (width, height),
list,
})
}
+59
View File
@@ -0,0 +1,59 @@
//! Audio and video on the shown slide (SHOW-10).
use std::io;
use serde_json::Value;
/// The shown slide's media objects.
pub const MEDIA: &str = ".uno:SlideMedia";
/// One media object as the kernel keeps it.
#[derive(Clone, Debug, PartialEq)]
pub struct Media {
/// Its place in the object list.
pub index: usize,
pub url: String,
/// Linked to a file outside the document.
pub link: bool,
/// The file that plays: the link, or the kernel's copy.
pub file: String,
/// The file to play is not there.
pub missing: bool,
pub repeat: bool,
/// x, y, width, height on the slide, 1/100 mm.
pub bounds: (i64, i64, i64, i64),
}
/// Parses `.uno:SlideMedia`.
pub fn media(json: &str) -> io::Result<Vec<Media>> {
media_of(&serde_json::from_str(json).map_err(io::Error::other)?)
}
pub(super) fn media_of(value: &Value) -> io::Result<Vec<Media>> {
let bad = |what: &str, item: &Value| io::Error::other(format!("bad {what} in {item}"));
let list = value["media"]
.as_array()
.ok_or_else(|| bad("media", value))?;
list.iter()
.map(|item| {
let text = |key: &str| {
item[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| bad(key, item))
};
let flag = |key: &str| item[key].as_bool().ok_or_else(|| bad(key, item));
let index = item["index"].as_u64().ok_or_else(|| bad("index", item))?;
let at = |key: &str| item[key].as_i64().ok_or_else(|| bad(key, item));
Ok(Media {
index: usize::try_from(index).map_err(io::Error::other)?,
url: text("url")?,
link: flag("link")?,
file: text("file")?,
missing: flag("missing")?,
repeat: flag("loop")?,
bounds: (at("x")?, at("y")?, at("width")?, at("height")?),
})
})
.collect()
}
+142
View File
@@ -0,0 +1,142 @@
//! Transitions and animations of a slide (SHOW-09).
use std::io;
use serde_json::{Value, json};
/// The shown slide's transition.
pub const TRANSITION: &str = ".uno:SlideTransition";
/// The shown slide's animation effects.
pub const ANIMATIONS: &str = ".uno:SlideAnimations";
/// Transitions Ely offers, by kernel preset; empty is none.
pub const TRANSITIONS: [&str; 10] = [
"",
"fade-smoothly",
"fade-through-black",
"push-left",
"push-up",
"cover-left",
"uncover-left",
"wipe-right",
"split-vertical-out",
"dissolve",
];
/// Effects Ely offers, by kernel preset.
pub const EFFECTS: [&str; 14] = [
"ooo-entrance-appear",
"ooo-entrance-fade-in",
"ooo-entrance-fly-in",
"ooo-entrance-wipe",
"ooo-entrance-zoom",
"ooo-entrance-float",
"ooo-emphasis-grow-and-shrink",
"ooo-emphasis-blink",
"ooo-exit-disappear",
"ooo-exit-fade-out",
"ooo-exit-fly-out",
"ooo-exit-wipe",
"ooo-exit-zoom",
"ooo-exit-float",
];
/// A slide's transition; preset "other" is not Ely's.
#[derive(Clone, Debug, PartialEq)]
pub struct Transition {
pub preset: String,
/// Seconds.
pub duration: f64,
/// Advances after `time` seconds; else on a click.
pub auto: bool,
pub time: f64,
}
/// One effect of the slide's main sequence, in order.
#[derive(Clone, Debug, PartialEq)]
pub struct Effect {
pub preset: String,
/// The kernel's name for the preset, English.
pub label: String,
/// entrance, emphasis, exit or other.
pub class: String,
/// The target's place in the object list, if listed.
pub target: Option<usize>,
/// The target's slideshow layer hash.
pub hash: String,
/// click, with or after.
pub start: String,
pub duration: f64,
pub delay: f64,
}
fn error(what: &str, value: &Value) -> io::Error {
io::Error::other(format!("bad {what} in {value}"))
}
fn text(value: &Value, key: &str) -> io::Result<String> {
(value[key].as_str().map(str::to_string)).ok_or_else(|| error(key, value))
}
fn number(value: &Value, key: &str) -> io::Result<f64> {
value[key].as_f64().ok_or_else(|| error(key, value))
}
/// Parses `.uno:SlideTransition`.
pub fn transition(json: &str) -> io::Result<Transition> {
transition_of(&serde_json::from_str(json).map_err(io::Error::other)?)
}
pub(super) fn transition_of(value: &Value) -> io::Result<Transition> {
let advance = text(value, "advance")?;
Ok(Transition {
preset: text(value, "preset")?,
duration: number(value, "duration")?,
auto: match advance.as_str() {
"auto" => true,
"click" => false,
_ => return Err(error("advance", value)),
},
time: number(value, "time")?,
})
}
/// The `Transition` argument; `all` sets every slide.
pub fn transition_json(transition: &Transition, all: bool) -> String {
json!({
"preset": transition.preset,
"duration": transition.duration,
"advance": if transition.auto { "auto" } else { "click" },
"time": transition.time,
"all": all,
})
.to_string()
}
/// Parses `.uno:SlideAnimations`.
pub fn effects(json: &str) -> io::Result<Vec<Effect>> {
effects_of(&serde_json::from_str(json).map_err(io::Error::other)?)
}
pub(super) fn effects_of(value: &Value) -> io::Result<Vec<Effect>> {
let list = value["effects"]
.as_array()
.ok_or_else(|| error("effects", value))?;
list.iter()
.map(|item| {
let target = item["target"]
.as_i64()
.ok_or_else(|| error("target", item))?;
Ok(Effect {
preset: text(item, "preset")?,
label: text(item, "label")?,
class: text(item, "class")?,
target: usize::try_from(target).ok(),
hash: text(item, "hash")?,
start: text(item, "start")?,
duration: number(item, "duration")?,
delay: number(item, "delay")?,
})
})
.collect()
}
+194
View File
@@ -0,0 +1,194 @@
//! A slide's objects, selection and guides (SHOW-03 to 06).
use std::io;
use serde_json::Value;
/// The shown slide's objects, selection, guides and snapping.
pub const OBJECTS: &str = ".uno:SlideObjects";
/// One object on the slide, in z order.
#[derive(Clone, Debug, PartialEq)]
pub struct Object {
/// The name the file gives it; often empty.
pub name: String,
/// text, shape, line, image, group, table, chart, media…
pub kind: String,
/// title, body or other; empty when it is none.
pub placeholder: String,
/// Left, top, width, height in 1/100 mm.
pub rect: (i64, i64, i64, i64),
pub locked: bool,
pub selected: bool,
}
/// A fill or outline color.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Paint {
None,
Mixed,
Color(u32),
}
/// The marked objects; `None` means mixed.
#[derive(Clone, Debug, PartialEq)]
pub struct Selection {
pub count: usize,
/// As [`Object::kind`], or mixed.
pub kind: String,
pub can_group: bool,
pub can_ungroup: bool,
pub fill: Paint,
pub line: Paint,
/// 1/100 mm.
pub line_width: Option<i64>,
/// Percent.
pub transparency: Option<i64>,
pub shadow: Option<bool>,
/// off, shrink, grow, or mixed.
pub autofit: String,
/// Left, top, width, height in 1/100 mm.
pub rect: (i64, i64, i64, i64),
/// 1/100 degree.
pub rotation: i64,
pub rotation_center: (i64, i64),
pub lock_position: Option<bool>,
pub lock_size: Option<bool>,
}
/// A guide; lines use one coordinate.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Guide {
pub kind: GuideKind,
/// 1/100 mm on the slide.
pub at: (i64, i64),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GuideKind {
Horizontal,
Vertical,
Point,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Objects {
pub objects: Vec<Object>,
pub selection: Option<Selection>,
pub snap_grid: bool,
pub snap_guides: bool,
pub guides: Vec<Guide>,
}
fn int(value: &Value, key: &str) -> io::Result<i64> {
value[key]
.as_i64()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
fn flag(value: &Value, key: &str) -> io::Result<bool> {
value[key]
.as_bool()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
fn text(value: &Value, key: &str) -> io::Result<String> {
value[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
}
/// A number where `-2` means mixed.
fn maybe(value: &Value, key: &str) -> io::Result<Option<i64>> {
int(value, key).map(|n| (n != -2).then_some(n))
}
fn rect(value: &Value) -> io::Result<(i64, i64, i64, i64)> {
Ok((
int(value, "x")?,
int(value, "y")?,
int(value, "width")?,
int(value, "height")?,
))
}
fn paint(value: &Value, key: &str) -> io::Result<Paint> {
Ok(match int(value, key)? {
-1 => Paint::None,
-2 => Paint::Mixed,
color => Paint::Color(
u32::try_from(color).map_err(|_| io::Error::other(format!("bad {key} in {value}")))?,
),
})
}
fn selection(value: &Value) -> io::Result<Option<Selection>> {
if int(value, "count")? == 0 {
return Ok(None);
}
let flag = |key| maybe(value, key).map(|n| n.map(|n| n == 1));
Ok(Some(Selection {
count: usize::try_from(int(value, "count")?).map_err(io::Error::other)?,
kind: text(value, "kind")?,
can_group: self::flag(value, "canGroup")?,
can_ungroup: self::flag(value, "canUngroup")?,
fill: paint(value, "fill")?,
line: paint(value, "line")?,
line_width: maybe(value, "lineWidth")?,
transparency: maybe(value, "transparency")?,
shadow: flag("shadow")?,
autofit: text(value, "autofit")?,
rect: rect(value)?,
rotation: int(value, "rotation")?,
rotation_center: (int(value, "rotationX")?, int(value, "rotationY")?),
lock_position: flag("lockPosition")?,
lock_size: flag("lockSize")?,
}))
}
/// Parses `.uno:SlideObjects`.
pub fn objects(json: &str) -> io::Result<Objects> {
let value: Value = serde_json::from_str(json)
.map_err(|error| io::Error::other(format!("bad objects: {error}")))?;
let list = |key: &str| {
value[key]
.as_array()
.ok_or_else(|| io::Error::other(format!("no {key} in {value}")))
};
let objects = list("objects")?
.iter()
.map(|item| {
Ok(Object {
name: text(item, "name")?,
kind: text(item, "kind")?,
placeholder: text(item, "placeholder")?,
rect: rect(item)?,
locked: flag(item, "locked")?,
selected: flag(item, "selected")?,
})
})
.collect::<io::Result<_>>()?;
let guides = list("guides")?
.iter()
.map(|item| {
let kind = match text(item, "kind")?.as_str() {
"horizontal" => GuideKind::Horizontal,
"vertical" => GuideKind::Vertical,
"point" => GuideKind::Point,
other => return Err(io::Error::other(format!("bad guide kind {other}"))),
};
Ok(Guide {
kind,
at: (int(item, "x")?, int(item, "y")?),
})
})
.collect::<io::Result<_>>()?;
Ok(Objects {
objects,
selection: selection(&value["selection"])?,
snap_grid: flag(&value, "snapGrid")?,
snap_guides: flag(&value, "snapGuides")?,
guides,
})
}
+178
View File
@@ -0,0 +1,178 @@
//! A slide's chart, notes and comments (SHOW-07, 08).
use std::io;
use serde_json::{Value, json};
use crate::Rect;
use crate::sheet::Look;
/// The shown slide's notes.
pub const NOTES: &str = ".uno:SlideNotes";
/// A chart's own table: one value per category and series.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChartData {
pub categories: Vec<String>,
/// Name and values; `None` where a cell is empty.
pub series: Vec<(String, Vec<Option<f64>>)>,
}
/// The selected chart on a slide.
#[derive(Clone, Debug, PartialEq)]
pub struct SlideChart {
pub name: String,
pub look: Look,
/// None when the data is not one table.
pub data: Option<ChartData>,
}
/// The `Chart` argument: the look, and the data if given.
pub fn chart_json(look: &Look, data: Option<&ChartData>) -> String {
let mut value: Value = serde_json::from_str(&look.to_json()).expect("a look is JSON");
if let Some(data) = data {
let series: Vec<Value> = (data.series.iter())
.map(|(name, values)| json!({ "name": name, "values": values }))
.collect();
value["data"] = json!({ "categories": data.categories, "series": series });
}
value.to_string()
}
fn error(what: &str, value: &Value) -> io::Error {
io::Error::other(format!("bad {what} in {value}"))
}
/// Parses `.uno:Chart` on a slide; none without a chart.
pub fn slide_chart(json: &str) -> io::Result<Option<SlideChart>> {
let value: Value = serde_json::from_str(json).map_err(io::Error::other)?;
let Some(name) = value.get("name") else {
return Ok(None);
};
let data = value.get("data").map(chart_data).transpose()?;
Ok(Some(SlideChart {
name: name
.as_str()
.ok_or_else(|| error("name", &value))?
.to_string(),
look: crate::sheet::look(&value)?,
data,
}))
}
fn chart_data(data: &Value) -> io::Result<ChartData> {
let categories = data["categories"]
.as_array()
.ok_or_else(|| error("categories", data))?
.iter()
.map(|item| {
item.as_str()
.map(str::to_string)
.ok_or_else(|| error("category", item))
})
.collect::<io::Result<_>>()?;
let series = data["series"]
.as_array()
.ok_or_else(|| error("series", data))?
.iter()
.map(|item| {
let name = item["name"].as_str().ok_or_else(|| error("name", item))?;
let values = item["values"]
.as_array()
.ok_or_else(|| error("values", item))?
.iter()
.map(|value| match value {
Value::Null => Ok(None),
value => value
.as_f64()
.map(Some)
.ok_or_else(|| error("value", value)),
})
.collect::<io::Result<_>>()?;
Ok((name.to_string(), values))
})
.collect::<io::Result<_>>()?;
Ok(ChartData { categories, series })
}
/// The shown slide's notes.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Notes {
/// The slide they belong to; none on a master.
pub part: Option<usize>,
/// The slide has a notes text box.
pub editable: bool,
pub text: String,
/// Their look varies, which plain text would lose.
pub rich: bool,
}
/// Parses `.uno:SlideNotes`.
pub fn notes(json: &str) -> io::Result<Notes> {
let value: Value = serde_json::from_str(json).map_err(io::Error::other)?;
let flag = |key| value[key].as_bool().ok_or_else(|| error(key, &value));
let part = value["part"]
.as_i64()
.ok_or_else(|| error("part", &value))?;
Ok(Notes {
part: usize::try_from(part).ok(),
editable: flag("editable")?,
text: value["text"]
.as_str()
.ok_or_else(|| error("text", &value))?
.to_string(),
rich: flag("rich")?,
})
}
/// A comment on a slide.
#[derive(Clone, Debug, PartialEq)]
pub struct Remark {
pub id: String,
pub author: String,
pub text: String,
/// ISO 8601, as the kernel gives it.
pub at: String,
pub part: usize,
/// Where it is pinned, in twips.
pub anchor: Rect,
}
/// Parses `.uno:ViewAnnotations` from a presentation.
pub fn remarks(json: &str) -> io::Result<Vec<Remark>> {
let value: Value = serde_json::from_str(json).map_err(io::Error::other)?;
let Some(list) = value["comments"].as_object() else {
return Ok(Vec::new());
};
list.values()
.map(|item| {
let text = |key: &str| {
item[key]
.as_str()
.map(str::to_string)
.ok_or_else(|| error(key, item))
};
let id = item["id"].as_u64().ok_or_else(|| error("id", item))?;
let part = item["part"].as_u64().ok_or_else(|| error("part", item))?;
let anchor: Vec<i32> = text("rectangle")?
.split(',')
.map(|n| {
n.trim()
.parse::<i32>()
.map_err(|_| error("rectangle", item))
})
.collect::<io::Result<_>>()?;
let [x, y, w, h] = anchor[..] else {
return Err(error("rectangle", item));
};
Ok(Remark {
id: id.to_string(),
author: text("author")?,
text: text("text")?,
at: text("dateTime")?,
part: usize::try_from(part).map_err(io::Error::other)?,
anchor: (x, y, w, h),
})
})
.collect()
}
+41
View File
@@ -0,0 +1,41 @@
//! Every slide as a show plays it (SHOW-11, 12).
use std::io;
use serde_json::Value;
use super::{Effect, Media, Transition, effects_of, media_of, transition_of};
/// All slides: hidden, notes, motion, media.
pub const SLIDE_SHOW: &str = ".uno:SlideShow";
/// One slide for the show.
#[derive(Clone, Debug, PartialEq)]
pub struct ShowSlide {
pub hidden: bool,
pub notes: String,
pub transition: Transition,
pub effects: Vec<Effect>,
pub media: Vec<Media>,
}
/// Parses `.uno:SlideShow`.
pub fn slide_show(json: &str) -> io::Result<Vec<ShowSlide>> {
let value: Value = serde_json::from_str(json).map_err(io::Error::other)?;
let bad = |what: &str, item: &Value| io::Error::other(format!("bad {what} in {item}"));
let list = value["slides"]
.as_array()
.ok_or_else(|| bad("slides", &value))?;
list.iter()
.map(|item| {
Ok(ShowSlide {
hidden: item["hidden"].as_bool().ok_or_else(|| bad("hidden", item))?,
notes: (item["notes"].as_str().map(str::to_string))
.ok_or_else(|| bad("notes", item))?,
transition: transition_of(&item["transition"])?,
effects: effects_of(item)?,
media: media_of(item)?,
})
})
.collect()
}
+494
View File
@@ -0,0 +1,494 @@
//! The GPUI tile canvas for one document (LOK-03, LOK-04, LOK-06).
use std::{
collections::{HashMap, HashSet},
io,
sync::{Arc, Mutex},
};
use gpui::{
App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, Pixels, Point, RenderImage,
Task, px,
};
use image::{Frame, ImageBuffer, Rgba};
use crate::{Doc, Events, Rect, Worker};
mod clip;
mod clock;
mod formula;
mod handles;
mod ime;
mod input;
mod lane;
mod off;
mod panes;
mod reads;
mod render;
mod zoom;
pub use zoom::{ZOOM_STEPS, Zoomed};
mod scroll;
pub use input::{CONTEXT, Copy, Cut, Paste, init};
pub use off::read_off;
pub use render::scheme;
/// One tile edge in twips.
pub const TILE_TWIPS: i32 = 3840;
/// Twips per pixel at zoom 1.0 and DPI 1.0.
pub(crate) const TWIPS_PER_PIXEL: f32 = 15.0;
/// Document/view conversion under one zoom and DPI (LOK-04).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Geom {
pub zoom: f32,
pub dpi: f32,
}
impl Geom {
/// Twips to logical pixels; GPUI scales to devices.
pub fn px_of(&self, twips: i32) -> f32 {
twips as f32 * self.zoom / TWIPS_PER_PIXEL
}
/// Logical pixels to twips.
pub fn twips_of(&self, pixels: f32) -> i32 {
(pixels * TWIPS_PER_PIXEL / self.zoom).round() as i32
}
/// Texture pixels for one tile edge at this DPI.
fn tile_pixels(&self) -> u32 {
(self.px_of(TILE_TWIPS) * self.dpi).round().max(1.0) as u32
}
}
/// An input request the engine refused; apps show it.
#[derive(Clone, Debug)]
pub struct LokError(pub String);
/// The kernel reported, or queued input landed.
#[derive(Clone, Debug)]
pub struct Reported;
struct TileEntry {
image: Arc<RenderImage>,
/// Shown until its repaint lands, so edits never flash.
stale: bool,
}
/// Paints one LOK document as a cached tile grid (LOK-03).
pub struct LokView {
worker: Arc<Mutex<Worker>>,
doc: Doc,
geom: Geom,
scroll: (i32, i32),
doc_size: (i32, i32),
generation: u64,
tiles: HashMap<(i32, i32), TileEntry>,
/// Tiles no longer drawn, freed at the next paint.
retired: ely_gpui_component::primitives::Retired,
fetching: HashSet<(i32, i32)>,
failed: HashSet<((i32, i32), u64)>,
/// The area last told to the kernel.
shown: Option<Rect>,
viewport: (f32, f32),
origin: Point<Pixels>,
/// Pixels a small document sits in: left, top.
spare: (f32, f32),
/// Frozen columns and rows, in twips from the top left.
frozen: (i32, i32),
/// The farthest point a jump needed; Calc grows to it.
reach: (i32, i32),
pages: Vec<Rect>,
focus: FocusHandle,
lane: lane::Lane,
sent: u64,
applied: u64,
edited: u64,
moves: u64,
last_edit: u64,
clock: clock::EditClock,
/// Tiles the last frame showed.
on_screen: Vec<(i32, i32)>,
/// The mark of this view's last copy.
copied: Option<String>,
/// The event watch; it ends with the view.
watching: Option<Task<()>>,
cursor: Option<Rect>,
cursor_visible: bool,
selection: Vec<Rect>,
cell: crate::Cell,
/// Whether the kernel was last told to paint dark.
dark: Option<bool>,
/// The zoom follows the viewport so a page fits.
fit: bool,
/// The sheet shown, and the offered function chosen.
part: usize,
picked: usize,
marked: Option<ime::Marked>,
dragging: bool,
grip: Option<handles::Grip>,
handle_size: Pixels,
states: HashMap<String, String>,
graphic: Option<Rect>,
review: u64,
/// The last search outcome: its count and matches.
search: (u64, Vec<Rect>),
menu: Option<String>,
fonts: Vec<String>,
a11y: crate::A11y,
tabs: Vec<i32>,
}
/// A document's size and page frames, in twips.
pub type Layout = ((i64, i64), Vec<Rect>);
type Measured = io::Result<Layout>;
/// A page's colour; the kernel's Ely schemes share it.
pub fn paper(cx: &gpui::App) -> gpui::Hsla {
use ely_gpui_component::theme::ActiveTheme as _;
let theme = cx.theme();
if theme.is_dark() {
theme.colors.surface
} else {
theme.colors.paper
}
}
/// Reads `doc`'s size and page frames.
pub fn layout(worker: &mut Worker, doc: &Doc) -> io::Result<Layout> {
Ok((doc.size(worker)?, doc.pages(worker)?))
}
/// Reads the layout under the worker lock.
fn measure(worker: &Mutex<Worker>, doc: &Doc) -> Measured {
layout(&mut worker.lock().expect("the worker lock"), doc)
}
impl EventEmitter<LokError> for LokView {}
impl EventEmitter<Reported> for LokView {}
impl LokView {
/// A view of `doc` at `layout`; starts the event watch.
pub fn open(
worker: Arc<Mutex<Worker>>,
doc: Doc,
(size, pages): Layout,
cx: &mut App,
) -> Entity<Self> {
cx.new(|cx| Self::sized(worker, doc, size, pages, cx))
}
fn sized(
worker: Arc<Mutex<Worker>>,
doc: Doc,
(width, height): (i64, i64),
pages: Vec<Rect>,
cx: &mut Context<Self>,
) -> Self {
log::info!("lok: {} pages", pages.len());
let lane = Self::lane(Arc::clone(&worker), doc.clone(), cx);
let mut view = Self {
worker,
doc,
geom: Geom {
zoom: 1.0,
dpi: 1.0,
},
scroll: (0, 0),
doc_size: (width as i32, height as i32),
generation: 0,
tiles: HashMap::new(),
retired: Default::default(),
fetching: HashSet::new(),
failed: HashSet::new(),
shown: None,
viewport: (0.0, 0.0),
origin: Point::default(),
spare: (0.0, 0.0),
frozen: (0, 0),
reach: (0, 0),
pages,
focus: cx.focus_handle().tab_stop(true),
lane,
sent: 0,
applied: 0,
edited: 0,
moves: 0,
last_edit: 0,
clock: clock::EditClock::default(),
on_screen: Vec::new(),
copied: None,
cursor: None,
cursor_visible: true,
selection: Vec::new(),
cell: crate::Cell::default(),
dark: None,
fit: false,
part: 0,
picked: 0,
marked: None,
dragging: false,
grip: None,
handle_size: px(6.0),
states: HashMap::new(),
graphic: None,
review: 0,
search: (0, Vec::new()),
menu: None,
fonts: Vec::new(),
a11y: crate::A11y::default(),
tabs: Vec::new(),
watching: None,
};
view.watching = Some(view.watch(cx));
view
}
/// Repaints every tile; the kernel sent no notice.
pub fn invalidate(&mut self, cx: &mut Context<Self>) {
for tile in self.tiles.values_mut() {
tile.stale = true;
}
self.failed.clear();
cx.notify();
}
/// Zooms so one page fits the viewport, from now on.
pub fn fit_page(&mut self, cx: &mut Context<Self>) {
if !self.fit {
self.fit = true;
cx.emit(Zoomed);
cx.notify();
}
}
/// The tiles painted for the current state (test evidence).
#[cfg(test)]
pub fn tile_count(&self) -> usize {
self.tiles.values().filter(|tile| !tile.stale).count()
}
/// Runs a table command; arguments are checked now (LOK-02).
pub fn run(&mut self, id: &str, values: &[&str]) -> io::Result<()> {
let command = crate::commands::find(id)?;
if command.addressed(values) {
return Err(io::Error::other(format!("{id} names something by number; run it at the state it was read")));
}
self.send(input::Input::Run { commands: vec![command.owned(values)?], at: None });
Ok(())
}
/// The document as the view last saw it.
pub fn read_at(&self) -> Doc {
self.doc.clone()
}
/// Batches and landings arrive out of order; keep the latest.
fn seen_revision(&mut self, revision: u64) {
self.doc.rev = self.doc.rev.max(revision);
}
/// Runs `id` against `at`, the document as it was read.
pub fn run_at(&mut self, at: &crate::Doc, id: &str, values: &[&str]) -> io::Result<()> {
self.run_all_at(at, &[(id, values)])
}
/// Runs `commands` in order, all made from the read `at`.
pub fn run_all_at(&mut self, at: &crate::Doc, commands: &[(&str, &[&str])]) -> io::Result<()> {
let commands = commands.iter().map(|(id, values)| crate::commands::find(id)?.owned(values)).collect::<io::Result<_>>()?;
self.send(input::Input::Run { commands, at: Some(at.clone()) });
Ok(())
}
/// Takes pushed events; the worker lock stays free (LOK-03).
fn watch(&self, cx: &mut Context<Self>) -> Task<()> {
let feed = self.worker.lock().expect("the worker lock").feed();
let (worker, doc) = (Arc::clone(&self.worker), self.doc.clone());
cx.spawn(async move |this, cx| {
// The resize count measured; none yet.
let (mut known, mut resized) = (0u64, None);
loop {
if this.upgrade().is_none() {
break;
}
// Awaited, not blocked: no thread waits for events.
let batch = match feed.next(&doc, known).await {
Ok(batch) => {
let measured = if resized != Some(batch.resized) {
let (worker, doc) = (Arc::clone(&worker), doc.clone());
let read = async move { measure(&worker, &doc) };
Some(cx.background_executor().spawn(read).await)
} else {
None
};
Ok((batch, measured))
}
Err(error) => Err(error),
};
let batch = match batch {
Ok(batch) => batch,
Err(error) => {
log::error!("lok: event watch ends: {error}");
let message = format!("the document engine stopped: {error}");
if this.update(cx, |_, cx| cx.emit(LokError(message))).is_err() {
log::info!("lok: the view went first");
}
break;
}
};
let (batch, measured) = batch;
(known, resized) = (batch.seq, Some(batch.resized));
if this
.update(cx, |view, cx| view.apply_batch(batch, measured, cx))
.is_err()
{
break;
}
}
})
}
/// Takes the cursor; drops the tiles a batch dirties (LOK-03).
fn apply_batch(&mut self, batch: Events, measured: Option<Measured>, cx: &mut Context<Self>) {
// What the view shows is the document at this revision.
self.seen_revision(batch.revision);
match measured {
Some(Ok(((width, height), pages))) => {
self.doc_size = (width as i32, height as i32);
if pages.len() != self.pages.len() {
log::info!("lok: {} pages", pages.len());
}
self.pages = pages;
self.clamp_scroll();
}
Some(Err(error)) => log::warn!("lok: document size lost: {error}"),
None => {}
}
if batch.cursor != self.cursor {
self.moves += 1;
// A moved cursor stays in view.
if self.viewport.1 > 0.0
&& let Some(cursor) = batch.cursor
{
self.show(cursor, cx);
}
}
// A moved cell cursor stays in view too.
if batch.cell.cursor != self.cell.cursor
&& self.viewport.1 > 0.0
&& let Some(cell) = batch.cell.cursor
{
self.show(cell, cx);
}
self.cursor = batch.cursor;
self.cursor_visible = batch.cursor_visible;
self.selection = batch.selection;
if batch.cell.functions != self.cell.functions {
self.picked = 0;
}
self.cell = batch.cell;
self.graphic = batch.graphic;
self.review = batch.review;
self.search = (batch.searched, batch.found);
self.fonts = batch.fonts;
if batch.menu.is_some() {
self.menu = batch.menu;
}
for fault in batch.faults {
cx.emit(LokError(fault));
}
self.a11y = batch.a11y;
self.tabs = batch.tabs;
self.states.extend(batch.states);
for title in batch.blocked {
cx.emit(LokError(format!(
"the kernel opened a dialog Ely closed: {title}"
)));
}
cx.emit(Reported);
if batch.generation == self.generation && !batch.all && batch.rects.is_empty() {
cx.notify();
return;
}
self.generation = batch.generation;
self.clock.bumped(batch.revision, batch.generation);
let rects = &batch.rects;
for (&(kx, ky), tile) in &mut self.tiles {
let (tx, ty) = (kx * TILE_TWIPS, ky * TILE_TWIPS);
tile.stale |= batch.all
|| rects.iter().any(|&(x, y, w, h)| {
tx < x + w && x < tx + TILE_TWIPS && ty < y + h && y < ty + TILE_TWIPS
});
}
// Shown tiles repaint now, not a frame later.
let dirty: Vec<_> = self
.on_screen
.iter()
.copied()
.filter(|key| self.tiles.get(key).is_some_and(|tile| tile.stale))
.collect();
for key in dirty {
self.request_tile(key);
}
cx.notify();
}
/// Requests one missing tile on the background executor.
fn request_tile(&mut self, key: (i32, i32)) {
if self.failed.contains(&(key, self.generation)) || !self.fetching.insert(key) {
return;
}
let job = lane::Job {
key,
geom: self.geom,
};
self.lane
.tiles
.unbounded_send(job)
.expect("the lane lives with the view");
}
/// Takes a painted tile; stale generations never land (LOK-03).
fn finish_tile(
&mut self,
key: (i32, i32),
geom: Geom,
tile: io::Result<crate::Tile>,
cx: &mut Context<Self>,
) {
self.fetching.remove(&key);
match tile {
Ok(tile) if tile.generation >= self.generation && geom == self.geom => {
let side = geom.tile_pixels();
// LOK and RenderImage both take BGRA bytes.
let Some(image) = ImageBuffer::<Rgba<u8>, _>::from_raw(side, side, tile.pixels)
else {
log::warn!("lok: a tile came back the wrong size");
return;
};
let entry = TileEntry {
image: Arc::new(RenderImage::new([Frame::new(image)])),
stale: false,
};
log::debug!("lok: tile {key:?} shown");
if let Some(old) = self.tiles.insert(key, entry) {
self.retired.push(old.image);
}
self.clock.painted(tile.generation);
cx.notify();
}
Ok(_) => cx.notify(),
Err(error) => {
// Retried at the next change or move.
log::warn!("lok: tile {key:?} failed: {error}");
self.failed.insert((key, self.generation));
cx.emit(LokError(format!("a page failed to paint: {error}")));
}
}
}
}
#[cfg(test)]
mod tests;
+90
View File
@@ -0,0 +1,90 @@
//! The clipboard for LokView (LOK-06, TABLE-08).
use std::{
io,
sync::atomic::{AtomicU64, Ordering},
};
use ely_platform::clipboard::{self, Clip};
use crate::{Doc, Worker};
/// The clipboard payload for copied LOK flavors.
pub(super) fn clip_of(flavors: Vec<(String, Vec<u8>)>) -> Option<Clip> {
let take = |mime: &str| {
flavors
.iter()
.find(|(name, _)| name == mime)
.map(|(_, data)| data.clone())
};
let text =
take("text/plain;charset=utf-8").map(|data| String::from_utf8_lossy(&data).into_owned());
if let (Some(png), None) = (take("image/png"), &text) {
return Some(Clip::Png(png));
}
match (take("text/html"), text) {
(Some(html), text) => Some(Clip::Html {
html: String::from_utf8_lossy(&html).into_owned(),
text: text.unwrap_or_default(),
}),
(None, Some(text)) => Some(Clip::Text(text)),
(None, None) => None,
}
}
/// The LOK flavor for a clipboard payload.
pub(super) fn flavor_of(clip: Clip) -> (&'static str, Vec<u8>) {
match clip {
Clip::Text(text) => ("text/plain;charset=utf-8", text.into_bytes()),
Clip::Html { html, .. } => ("text/html", html.into_bytes()),
Clip::Png(png) => ("image/png", png),
}
}
/// Copies out, marked; a cut deletes after the write.
pub(super) fn copy_out(
worker: &mut Worker,
doc: &Doc,
cut: bool,
write: impl FnOnce(&Clip) -> io::Result<()>,
) -> io::Result<Option<String>> {
let Some(mut clip) = clip_of(worker.copy(doc)?) else {
return Ok(None);
};
let mark = if let Clip::Html { html, .. } = &mut clip {
static COPIES: AtomicU64 = AtomicU64::new(0);
let mark = format!(
"{}-{}",
std::process::id(),
COPIES.fetch_add(1, Ordering::SeqCst)
);
html.push_str(&format!("<!--{MARK}{mark}-->"));
Some(mark)
} else {
None
};
write(&clip)?;
if cut {
worker.cut(doc)?;
}
Ok(mark)
}
/// Ely's copies end their HTML with this and a mark.
const MARK: &str = "ely-copy:";
/// The mark of Ely's copy in `html`, if any.
pub(super) fn mark_of(html: &str) -> Option<&str> {
let start = html.rfind(&format!("<!--{MARK}"))? + 4 + MARK.len();
let end = html[start..].find("-->")?;
Some(&html[start..start + end])
}
/// Pastes the system clipboard.
pub(super) fn paste(worker: &mut Worker, doc: &Doc) -> io::Result<()> {
let Some(clip) = clipboard::read().map_err(io::Error::other)? else {
return Ok(());
};
let (mime, data) = flavor_of(clip);
worker.paste(doc, mime, &data)
}
+97
View File
@@ -0,0 +1,97 @@
//! Times an edit to the tile showing it (PERF-02).
use std::time::Instant;
/// One edit's clock: sent when, its revision, its generation.
type Edit = (Instant, Option<u64>, Option<u64>);
#[derive(Default)]
pub(super) struct EditClock {
edit: Option<Edit>,
/// The last generation bump: its revision and generation.
bumped: (u64, u64),
}
impl EditClock {
/// An edit queued; an unseen earlier start stays.
pub(super) fn sent(&mut self) {
self.edit.get_or_insert((Instant::now(), None, None));
}
/// The edit landed at `revision`; its batch may precede it.
pub(super) fn landed(&mut self, revision: Option<u64>) {
let Some((_, rev @ None, generation)) = &mut self.edit else {
return;
};
let Some(revision) = revision else {
self.edit = None;
return;
};
*rev = Some(revision);
if self.bumped.0 >= revision {
*generation = Some(self.bumped.1);
}
}
/// A batch at `revision` dirtied tiles into `generation`.
pub(super) fn bumped(&mut self, revision: u64, generation: u64) {
self.bumped = (revision, generation);
if let Some((_, Some(rev), shown @ None)) = &mut self.edit
&& revision >= *rev
{
*shown = Some(generation);
}
}
/// A tile of `generation` came; logs the edit it shows.
pub(super) fn painted(&mut self, generation: u64) {
if let Some((at, _, Some(shown))) = self.edit
&& generation >= shown
{
log::debug!("lok: edit to tile {} ms", at.elapsed().as_millis());
self.edit = None;
}
}
#[cfg(test)]
fn running(&self) -> bool {
self.edit.is_some()
}
}
#[cfg(test)]
mod tests {
use super::EditClock;
#[test]
fn a_batch_before_the_landing_still_ends_the_edit() {
let mut clock = EditClock::default();
clock.sent();
clock.bumped(7, 3);
clock.landed(Some(7));
clock.painted(2);
assert!(clock.running(), "an older picture leaves it running");
clock.painted(3);
assert!(!clock.running(), "the edit's own picture ends it");
}
#[test]
fn only_a_batch_at_the_edit_revision_counts() {
let mut clock = EditClock::default();
clock.sent();
clock.bumped(6, 3);
clock.landed(Some(7));
clock.painted(3);
assert!(clock.running(), "a batch before the edit shows the old text");
clock.bumped(7, 4);
clock.painted(4);
assert!(!clock.running());
}
#[test]
fn an_unread_revision_drops_the_edit() {
let mut clock = EditClock::default();
clock.sent();
clock.landed(None);
assert!(!clock.running());
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Formula entry: reference marks and function hints (TABLE-03).
use ely_gpui_component::{
editor::{CompletionItem, CompletionMenu, Signature, SignatureHelp, SymbolKind, completions},
primitives::raise,
};
use gpui::{
AnyElement, Bounds, Context, Hsla, IntoElement, Keystroke, Modifiers, ParentElement, Pixels,
anchored, rgb,
};
use super::{LokView, input::Input};
impl LokView {
/// The sheet shown, which reference marks follow.
pub fn set_part(&mut self, part: usize) {
self.part = part;
}
/// The shown sheet's reference marks, in window pixels.
pub(super) fn marks(&self) -> Vec<(Bounds<Pixels>, Hsla)> {
self.cell
.marks
.iter()
.filter(|mark| mark.part == self.part)
.map(|mark| (self.screen_rect(mark.rect), rgb(mark.color).into()))
.collect()
}
/// The offered functions, in the order the menu shows.
fn offered(&self) -> Vec<CompletionItem> {
let items: Vec<CompletionItem> = self
.cell
.functions
.iter()
.map(|function| {
CompletionItem::new(function.name.clone(), SymbolKind::Function)
.detail(function.signature.clone())
.docs(function.description.clone())
})
.collect();
completions(&items, "")
.into_iter()
.map(|(item, _)| item)
.collect()
}
/// Up and Down walk the offered functions.
pub(super) fn walk(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) -> bool {
let count = self.cell.functions.len();
if count == 0 || keystroke.modifiers != Modifiers::none() {
return false;
}
self.picked = match keystroke.key.as_str() {
"down" => (self.picked + 1) % count,
"up" => (self.picked + count - 1) % count,
_ => return false,
};
cx.notify();
true
}
/// Takes the chosen function, in order with typing.
pub(super) fn complete(&mut self) -> bool {
let Some(item) = self.offered().into_iter().nth(self.picked) else {
return false;
};
log::info!("lok: completes {}", item.label);
self.send(Input::Complete(item.label.to_string()));
true
}
/// The offered functions, else the call's usage, under the cell.
pub(super) fn hints(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let cell = self.screen_rect(self.cell.cursor?);
let hint = if self.cell.functions.is_empty() {
SignatureHelp::new("lok-view-usage", [usage(&self.cell.usage)?]).into_any_element()
} else {
let this = cx.entity();
let offered = self.offered();
let labels: Vec<_> = offered.iter().map(|item| item.label.clone()).collect();
CompletionMenu::new("lok-view-functions", offered)
.selected(self.picked)
.on_pick(move |item, _, cx| {
let at = labels.iter().position(|label| *label == item.label);
this.update(cx, |view, cx| {
view.picked = at.expect("a picked item is offered");
view.complete();
cx.notify();
})
})
.into_any_element()
};
let place = anchored()
.position(cell.bottom_left())
.snap_to_window()
.child(hint);
Some(raise("lok-view-hints", place).into_any_element())
}
}
/// The kernel's usage text as a signature.
fn usage(text: &str) -> Option<Signature> {
let (call, docs) = text.split_once(" : ").unwrap_or((text, ""));
let at = call.find('►')?;
let label = call.replacen('►', "", 1);
let rest = &label[at..];
let end = at + rest.find([',', ';', ')']).unwrap_or(rest.len());
Some(Signature {
label: label.clone().into(),
params: std::iter::once(at..end).collect(),
docs: (!docs.is_empty()).then(|| docs.to_string().into()),
})
}
#[cfg(test)]
mod tests {
use super::usage;
#[test]
fn the_kernel_usage_reads_as_a_signature() {
let signature = usage("SUM(► Number 1, Number 2) : The numbers.").expect("a usage");
assert_eq!(signature.label.as_ref(), "SUM( Number 1, Number 2)");
assert_eq!(&signature.label[signature.params[0].clone()], " Number 1");
assert_eq!(signature.docs.as_deref(), Some("The numbers."));
assert!(usage("").is_none());
}
}
+108
View File
@@ -0,0 +1,108 @@
//! The selected object's frame and its eight handles (DOC-08).
use gpui::{Pixels, Point};
use super::LokView;
use crate::Rect;
/// A held handle: which, from where, to where.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Grip {
pub(super) at: usize,
pub(super) from: (i32, i32),
pub(super) to: (i32, i32),
}
/// Corners and edge middles, left to right, top to bottom.
pub(super) fn points((x, y, w, h): Rect) -> [(i32, i32); 8] {
let (cx, cy, r, b) = (x + w / 2, y + h / 2, x + w, y + h);
[
(x, y),
(cx, y),
(r, y),
(x, cy),
(r, cy),
(x, b),
(cx, b),
(r, b),
]
}
/// The frame with handle `at` moved to `to`.
pub(super) fn dragged((x, y, w, h): Rect, at: usize, (tx, ty): (i32, i32)) -> Rect {
let (mut left, mut top, mut right, mut bottom) = (x, y, x + w, y + h);
if matches!(at, 0 | 3 | 5) {
left = tx;
}
if matches!(at, 2 | 4 | 7) {
right = tx;
}
if matches!(at, 0..=2) {
top = ty;
}
if matches!(at, 5..=7) {
bottom = ty;
}
(
left.min(right),
top.min(bottom),
(right - left).abs(),
(bottom - top).abs(),
)
}
impl LokView {
/// Grabs the handle under `position`, if a frame is selected.
pub(super) fn grab(&mut self, position: Point<Pixels>) -> bool {
let Some(frame) = self.graphic else {
return false;
};
let reach = self.handle_size;
let hit = points(frame).iter().position(|&point| {
let at = self.window_point(point);
(at.x - position.x).abs() <= reach && (at.y - position.y).abs() <= reach
});
let Some(at) = hit else {
return false;
};
let from = points(frame)[at];
log::info!("lok: handle {at} grabbed");
self.grip = Some(Grip { at, from, to: from });
true
}
/// The frame to paint, previewing a held handle.
pub(super) fn frame(&self) -> Option<Rect> {
let frame = self.graphic?;
Some(match self.grip {
Some(grip) => dragged(frame, grip.at, grip.to),
None => frame,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn handles_move_their_own_sides() {
let frame = (100, 200, 300, 400);
assert_eq!(points(frame)[7], (400, 600));
assert_eq!(
dragged(frame, 7, (300, 500)),
(100, 200, 200, 300),
"a corner moves two sides"
);
assert_eq!(
dragged(frame, 4, (500, 0)),
(100, 200, 400, 400),
"an edge moves one"
);
assert_eq!(
dragged(frame, 0, (500, 700)),
(400, 600, 100, 100),
"past the far side flips"
);
}
}
+191
View File
@@ -0,0 +1,191 @@
//! The IME composition bridge for LokView (LOK-07).
use std::ops::Range;
use gpui::{Bounds, Context, EntityInputHandler, Pixels, UTF16Selection, Window};
use super::{LokView, input::Input};
/// The live composition and its UTF-16 selection.
pub(super) struct Marked {
pub text: String,
pub selected: Range<usize>,
}
fn len16(text: &str) -> usize {
text.encode_utf16().count()
}
/// The byte offset of a UTF-16 index, clamped.
fn byte_at(text: &str, at16: usize) -> usize {
let mut seen = 0;
for (byte, c) in text.char_indices() {
if seen >= at16 {
return byte;
}
seen += c.len_utf16();
}
text.len()
}
/// `base` with its UTF-16 `range` replaced by `text`.
fn splice(base: &str, range: &Range<usize>, text: &str) -> String {
let (start, end) = (
byte_at(base, range.start),
byte_at(base, range.end.max(range.start)),
);
format!("{}{text}{}", &base[..start], &base[end..])
}
impl LokView {
/// Replaces part of the composition; empty text cancels it.
pub(super) fn compose(
&mut self,
range: Option<Range<usize>>,
text: &str,
selected: Option<Range<usize>>,
) {
let (composed, start) = match (&self.marked, range) {
(Some(marked), Some(range)) => (splice(&marked.text, &range, text), range.start),
_ => (text.to_string(), 0),
};
self.send(Input::Text {
commit: false,
text: composed.clone(),
});
if composed.is_empty() {
self.send(Input::Text {
commit: true,
text: String::new(),
});
self.marked = None;
return;
}
let end = len16(&composed);
let tail = start + len16(text);
let selected = selected.map_or(tail..tail, |s| s.start + start..s.end + start);
self.marked = Some(Marked {
selected: selected.start.min(end)..selected.end.min(end),
text: composed,
});
}
/// Types `text` at the cursor.
pub fn insert(&mut self, text: &str) {
self.commit(None, text);
}
/// Commits `text` into the composition's `range`, or at the cursor.
pub(super) fn commit(&mut self, range: Option<Range<usize>>, text: &str) {
let committed = match (&self.marked, range) {
(Some(marked), Some(range)) => splice(&marked.text, &range, text),
_ => text.to_string(),
};
self.send(Input::Text {
commit: false,
text: committed,
});
self.send(Input::Text {
commit: true,
text: String::new(),
});
self.marked = None;
}
}
impl EntityInputHandler for LokView {
fn text_for_range(
&mut self,
range: Range<usize>,
adjusted: &mut Option<Range<usize>>,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<String> {
let marked = self.marked.as_ref()?;
let end = len16(&marked.text);
let range = range.start.min(end)..range.end.min(end);
let text =
&marked.text[byte_at(&marked.text, range.start)..byte_at(&marked.text, range.end)];
*adjusted = Some(range);
Some(text.to_string())
}
fn selected_text_range(
&mut self,
_: bool,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<UTF16Selection> {
let range = self
.marked
.as_ref()
.map_or(0..0, |marked| marked.selected.clone());
Some(UTF16Selection {
range,
reversed: false,
})
}
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
self.marked.as_ref().map(|marked| 0..len16(&marked.text))
}
fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {
if let Some(marked) = self.marked.take() {
self.commit(None, &marked.text);
}
}
fn replace_text_in_range(
&mut self,
range: Option<Range<usize>>,
text: &str,
_: &mut Window,
_: &mut Context<Self>,
) {
self.commit(range, text);
}
fn replace_and_mark_text_in_range(
&mut self,
range: Option<Range<usize>>,
text: &str,
selected: Option<Range<usize>>,
_: &mut Window,
_: &mut Context<Self>,
) {
self.compose(range, text, selected);
}
fn bounds_for_range(
&mut self,
_: Range<usize>,
_: Bounds<Pixels>,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
self.cursor_bounds()
}
fn character_index_for_point(
&mut self,
_: gpui::Point<Pixels>,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<usize> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splices_count_utf16() {
assert_eq!(splice("nihao", &(0..2), "你"), "你hao");
assert_eq!(splice("你好", &(1..2), "们"), "你们");
assert_eq!(splice("ab", &(5..9), "c"), "abc", "ranges clamp");
assert_eq!(byte_at("😀a", 2), 4, "a surrogate pair is two units");
}
}
+423
View File
@@ -0,0 +1,423 @@
//! Keys, mouse, IME and clipboard for LokView (LOK-06, LOK-07).
use std::{io, sync::Mutex, time::Instant};
use ely_platform::clipboard;
use gpui::{
App, Context, KeyBinding, KeyDownEvent, Keystroke, Modifiers, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, Pixels, Window, actions,
};
use super::{LokView, clip, handles};
use crate::{Doc, Mouse, Rect, Worker};
actions!(lok_view, [Copy, Cut, Paste, NextField, PreviousField]);
/// The key context of every LokView.
pub const CONTEXT: &str = "LokView";
/// Binds the clipboard keys; call once at startup.
pub fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("secondary-c", Copy, Some(CONTEXT)),
KeyBinding::new("secondary-x", Cut, Some(CONTEXT)),
KeyBinding::new("secondary-v", Paste, Some(CONTEXT)),
// The document owns Tab, as office apps do.
KeyBinding::new("tab", NextField, Some(CONTEXT)),
KeyBinding::new("shift-tab", PreviousField, Some(CONTEXT)),
]);
}
/// One queued request; the queue keeps input order.
pub(super) enum Input {
Key {
char_code: u32,
key_code: i32,
},
Mouse(Mouse),
Text {
commit: bool,
text: String,
},
Copy {
cut: bool,
},
Paste,
/// Values or formulas alone: `paste.values` or `paste.formulas`.
PasteOnly(&'static str),
/// A function the kernel offered, taken.
Complete(String),
/// The kernel's color scheme; not an edit.
Theme(&'static str),
/// Commands in order, from one read.
Run {
commands: Vec<(&'static str, Vec<String>)>,
/// The document as read, for commands by number.
at: Option<crate::Doc>,
},
/// A handle of the selected object, moved.
Drag {
from: (i32, i32),
to: (i32, i32),
},
/// The area the view shows, in twips.
Visible(Rect),
/// Shows sheet or slide `part`, from 0.
Part(usize),
}
impl Input {
/// Whether the input may change the document.
pub(super) fn edits(&self) -> bool {
match self {
// Arrows, Home, End, Page keys, Escape.
Input::Key { key_code, .. } => !matches!(key_code & 0x0FFF, 1024..=1031 | 1281),
Input::Mouse(_)
| Input::Copy { cut: false }
| Input::Visible(_)
| Input::Part(_)
| Input::Theme(_) => false,
Input::Run { commands, .. } => commands.iter().any(|(id, _)| *id != "edit.select_all"),
Input::Text { .. }
| Input::Copy { cut: true }
| Input::Paste
| Input::PasteOnly(_)
| Input::Drag { .. }
| Input::Complete(_) => true,
}
}
}
/// vcl modifier bits.
const SHIFT: i32 = 0x1000;
const MOD1: i32 = 0x2000;
const MOD2: i32 = 0x4000;
const MOD3: i32 = 0x8000;
/// vcl bits for GPUI modifiers; macOS Cmd is MOD1.
fn vcl_modifiers(modifiers: &Modifiers) -> i32 {
let mut bits = 0;
if modifiers.shift {
bits |= SHIFT;
}
if modifiers.alt {
bits |= MOD2;
}
if cfg!(target_os = "macos") {
if modifiers.platform {
bits |= MOD1;
}
if modifiers.control {
bits |= MOD3;
}
} else if modifiers.control {
bits |= MOD1;
}
bits
}
/// A non-text keystroke as (char, vcl code).
pub(super) fn vcl_key(keystroke: &Keystroke) -> Option<(u32, i32)> {
let modifiers = &keystroke.modifiers;
let command =
modifiers.control || modifiers.platform || (modifiers.alt && !cfg!(target_os = "macos"));
let named = match keystroke.key.as_str() {
"down" => Some(1024),
"up" => Some(1025),
"left" => Some(1026),
"right" => Some(1027),
"home" => Some(1028),
"end" => Some(1029),
"pageup" => Some(1030),
"pagedown" => Some(1031),
"enter" => Some(1280),
"escape" => Some(1281),
"tab" => Some(1282),
"backspace" => Some(1283),
"space" if command => Some(1284),
"insert" => Some(1285),
"delete" => Some(1286),
key => key
.strip_prefix('f')
.and_then(|n| n.parse::<i32>().ok())
.filter(|n| (1..=26).contains(n))
.map(|n| 767 + n),
};
let code = match named {
Some(code) => code,
None if !command => return None,
None => {
let mut chars = keystroke.key.chars();
match (chars.next(), chars.next()) {
(Some(c @ 'a'..='z'), None) => 512 + (c as i32 - 'a' as i32),
(Some(c @ '0'..='9'), None) => 256 + (c as i32 - '0' as i32),
_ => return None,
}
}
};
Some((0, code | vcl_modifiers(modifiers)))
}
/// LOK mouse buttons: 1 left, 2 middle, 4 right.
fn lok_button(button: MouseButton) -> Option<i32> {
match button {
MouseButton::Left => Some(1),
MouseButton::Middle => Some(2),
MouseButton::Right => Some(4),
_ => None,
}
}
/// Runs one input; gives a copy's mark and the revision.
pub(super) fn run(worker: &Mutex<Worker>, doc: &Doc, input: Input) -> (io::Result<Option<String>>, Option<u64>) {
let mut worker = worker.lock().expect("the worker lock");
let counts = !matches!(input, Input::Visible(_));
let copied = apply(&mut worker, doc, input);
// A failed input may have moved the revision too.
let now = match counts {
true => worker.now(doc).inspect_err(|error| log::warn!("lok: revision unread: {error}")).ok().map(|now| now.rev),
false => None,
};
(copied, now)
}
fn apply(worker: &mut Worker, doc: &Doc, input: Input) -> io::Result<Option<String>> {
let done = match input {
Input::Key {
char_code,
key_code,
} => worker.post_key(doc, char_code, key_code),
Input::Mouse(event) => worker.post_mouse(doc, event),
Input::Drag { from, to } => worker.drag_graphic(doc, from, to),
Input::Visible(area) => doc.visible_area(worker, area),
Input::Part(part) => doc.show_sheet(worker, part),
Input::Complete(name) => doc.complete_function(worker, &name),
Input::Theme(scheme) => worker.run(doc, "view.theme", &[scheme]),
Input::Text { commit, text } => worker.post_text(doc, commit, &text),
Input::Copy { cut } => {
return clip::copy_out(worker, doc, cut, |clip| {
clipboard::write(clip).map_err(io::Error::other)
});
}
Input::Run { commands, at } => {
let values: Vec<Vec<&str>> =
commands.iter().map(|(_, values)| values.iter().map(String::as_str).collect()).collect();
let commands: Vec<(&str, &[&str])> =
commands.iter().zip(&values).map(|((id, _), values)| (*id, values.as_slice())).collect();
worker.run_all(at.as_ref().unwrap_or(doc), &commands)
}
Input::Paste => clip::paste(worker, doc),
// The kernel's own cells: the app checked the clipboard.
Input::PasteOnly(id) => worker.run(doc, id, &[]),
};
done.map(|()| None)
}
impl LokView {
/// Queues `input` in order; edits mark the view pending.
pub(super) fn send(&mut self, input: Input) {
self.sent += 1;
if input.edits() {
self.last_edit = self.sent;
self.clock.sent();
}
self.lane
.inputs
.unbounded_send((self.sent, input, Instant::now()))
.expect("the input queue lives with the view");
}
/// Shows part `part` after the input queued before it.
pub fn show_part(&mut self, part: usize) {
log::info!("lok: shows part {part}");
self.part = part;
self.send(Input::Part(part));
}
/// Whether a possible edit is still queued.
pub fn edit_pending(&self) -> bool {
self.applied < self.last_edit
}
/// How many edits reached the kernel.
pub fn edited(&self) -> u64 {
self.edited
}
/// The sequence number of the last queued input.
pub fn sent(&self) -> u64 {
self.sent
}
/// Whether input `seq` reached the kernel.
pub fn reached(&self, seq: u64) -> bool {
self.applied >= seq
}
/// Whether every queued input reached the kernel.
pub fn settled(&self) -> bool {
self.applied >= self.sent
}
/// Posts a non-text key; text waits for the IME.
pub(super) fn key_down(&mut self, keystroke: &Keystroke) -> bool {
let Some((char_code, key_code)) = vcl_key(keystroke) else {
return false;
};
self.send(Input::Key {
char_code,
key_code,
});
true
}
/// Posts a mouse event at a view position (LOK-04).
pub(super) fn mouse(
&mut self,
kind: i32,
position: gpui::Point<Pixels>,
button: i32,
count: usize,
modifiers: &Modifiers,
) {
let (x, y) = self.doc_point(position);
self.send(Input::Mouse(Mouse {
kind,
x,
y,
count: count.max(1) as i32,
buttons: button,
modifiers: vcl_modifiers(modifiers),
}));
}
pub(super) fn on_key_down(
&mut self,
event: &KeyDownEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if self.walk(&event.keystroke, cx) || self.key_down(&event.keystroke) {
cx.stop_propagation();
}
}
pub(super) fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(button) = lok_button(event.button) else {
return;
};
window.focus(&self.focus, cx);
if event.button == MouseButton::Left && self.grab(event.position) {
cx.notify();
return;
}
self.dragging = event.button == MouseButton::Left;
self.mouse(
0,
event.position,
button,
event.click_count,
&event.modifiers,
);
}
pub(super) fn on_mouse_up(
&mut self,
event: &MouseUpEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if let Some(grip) = self.grip.take() {
let to = self.doc_point(event.position);
log::info!("lok: handle released");
self.send(Input::Drag {
from: grip.from,
to,
});
cx.notify();
return;
}
let Some(button) = lok_button(event.button) else {
return;
};
if event.button == MouseButton::Left {
self.dragging = false;
}
self.mouse(
1,
event.position,
button,
event.click_count,
&event.modifiers,
);
}
/// Ends a drag released outside the view.
pub(super) fn on_mouse_up_out(
&mut self,
event: &MouseUpEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.dragging || self.grip.is_some() {
self.on_mouse_up(event, window, cx);
}
}
pub(super) fn on_mouse_move(
&mut self,
event: &MouseMoveEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if self.grip.is_some() {
let to = self.doc_point(event.position);
self.grip = self.grip.map(|grip| handles::Grip { to, ..grip });
cx.notify();
return;
}
if self.dragging && event.pressed_button == Some(MouseButton::Left) {
self.mouse(2, event.position, 1, 1, &event.modifiers);
}
}
pub(super) fn on_copy(&mut self, _: &Copy, _: &mut Window, _: &mut Context<Self>) {
self.send(Input::Copy { cut: false });
}
pub(super) fn on_next_field(&mut self, _: &NextField, _: &mut Window, _: &mut Context<Self>) {
if !self.complete() {
self.key_down(&Keystroke::parse("tab").expect("a keystroke"));
}
}
pub(super) fn on_previous_field(
&mut self,
_: &PreviousField,
_: &mut Window,
_: &mut Context<Self>,
) {
self.key_down(&Keystroke::parse("shift-tab").expect("a keystroke"));
}
pub(super) fn on_cut(&mut self, _: &Cut, _: &mut Window, _: &mut Context<Self>) {
self.send(Input::Copy { cut: true });
}
pub(super) fn on_paste(&mut self, _: &Paste, _: &mut Window, _: &mut Context<Self>) {
self.send(Input::Paste);
}
/// Pastes values or formulas alone (TABLE-08).
pub fn paste_only(&mut self, id: &'static str) {
self.send(Input::PasteOnly(id));
}
}
#[cfg(test)]
mod tests;
+93
View File
@@ -0,0 +1,93 @@
use super::*;
use crate::view::clip::{clip_of, flavor_of};
use ely_platform::clipboard::Clip;
fn stroke(text: &str) -> Keystroke {
Keystroke::parse(text).expect("a keystroke")
}
#[test]
fn named_keys_map_to_vcl_codes() {
assert_eq!(vcl_key(&stroke("enter")), Some((0, 1280)));
assert_eq!(vcl_key(&stroke("shift-left")), Some((0, 1026 | SHIFT)));
assert_eq!(vcl_key(&stroke("backspace")), Some((0, 1283)));
assert_eq!(vcl_key(&stroke("f5")), Some((0, 772)));
let primary = if cfg!(target_os = "macos") {
"cmd"
} else {
"ctrl"
};
assert_eq!(
vcl_key(&stroke(&format!("{primary}-b"))),
Some((0, 513 | MOD1))
);
assert_eq!(
vcl_key(&stroke(&format!("{primary}-shift-z"))),
Some((0, 537 | MOD1 | SHIFT))
);
}
#[test]
fn printable_text_waits_for_the_ime() {
let mut typed = stroke("a");
typed.key_char = Some("a".into());
assert_eq!(vcl_key(&typed), None);
let mut space = stroke("space");
space.key_char = Some(" ".into());
assert_eq!(vcl_key(&space), None);
}
#[test]
fn copied_flavors_pick_the_richest_clip() {
let flavor = |mime: &str, data: &str| (mime.to_string(), data.as_bytes().to_vec());
let html = clip_of(vec![
flavor("text/html", "<b>x</b>"),
flavor("text/plain;charset=utf-8", "x"),
]);
assert_eq!(
html,
Some(Clip::Html {
html: "<b>x</b>".into(),
text: "x".into()
})
);
assert_eq!(
clip_of(vec![flavor("image/png", "png")]),
Some(Clip::Png(b"png".to_vec()))
);
assert_eq!(clip_of(Vec::new()), None);
assert_eq!(
flavor_of(Clip::Text("t".into())).0,
"text/plain;charset=utf-8"
);
}
#[test]
fn copy_marks_read_back() {
use crate::view::clip::mark_of;
assert_eq!(mark_of("<b>x</b><!--ely-copy:7-3-->"), Some("7-3"));
assert_eq!(mark_of("<b>x</b>"), None);
let wrapped = "<html><body><b>x</b><!--ely-copy:7-4--></body></html>";
assert_eq!(mark_of(wrapped), Some("7-4"), "the clipboard may wrap it");
}
#[test]
fn a_failed_input_still_reports_the_revision_it_reached() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker = Worker::spawn(&install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join("book.fods");
std::fs::write(&source, crate::client::tests::input::FODS).expect("the fixture writes");
let doc = worker.load(&format!("file://{}", source.display())).expect("the book loads");
let worker = Mutex::new(worker);
// Nothing merged to split: the kernel refuses.
let input = Input::Run { commands: vec![("cells.split", Vec::new())], at: None };
let (outcome, now) = run(&worker, &doc, input);
assert!(outcome.is_err(), "the split fails");
let reached = worker.lock().expect("the worker lock").now(&doc).expect("the state");
assert_eq!(now, Some(reached.rev), "the view learns the revision anyway");
assert!(reached.rev > doc.rev, "the request counted");
}
+125
View File
@@ -0,0 +1,125 @@
//! One background lane per view: inputs first, then tiles (LOK-03).
use std::{
io,
sync::{Arc, Mutex},
time::Instant,
};
use futures::{StreamExt, channel::mpsc, select_biased};
use gpui::Context;
use super::{Geom, LokError, LokView, Reported, TILE_TWIPS, input::Input};
use crate::{Doc, Tile, Worker};
/// An input slower than this is logged as a warning.
const SLOW_MS: u128 = 100;
/// A tile to paint at `key` for `geom`.
pub(super) struct Job {
pub key: (i32, i32),
pub geom: Geom,
}
/// What came back from the lane.
enum Landed {
Input(u64, bool, (io::Result<Option<String>>, Option<u64>)),
Tile(Job, io::Result<Tile>),
}
/// The lane's two queues.
pub(super) struct Lane {
pub inputs: mpsc::UnboundedSender<(u64, Input, Instant)>,
pub tiles: mpsc::UnboundedSender<Job>,
}
impl LokView {
/// Starts the lane; it ends with the view.
pub(super) fn lane(worker: Arc<Mutex<Worker>>, doc: Doc, cx: &mut Context<Self>) -> Lane {
let (inputs, mut input_queue) = mpsc::unbounded::<(u64, Input, Instant)>();
let (tiles, mut tile_queue) = mpsc::unbounded::<Job>();
let (landing, mut landed) = mpsc::unbounded::<Landed>();
cx.background_executor()
.spawn(async move {
loop {
let done = select_biased! {
input = input_queue.next() => {
let Some((seq, input, sent)) = input else { break };
let (waited, edits) = (sent.elapsed().as_millis(), input.edits());
let outcome = super::input::run(&worker, &doc, input);
let took = sent.elapsed().as_millis();
if took > SLOW_MS {
log::warn!("lok: input {seq} waited {waited}, took {took} ms");
} else {
log::debug!("lok: input {seq} waited {waited}, took {took} ms");
}
Landed::Input(seq, edits, outcome)
}
job = tile_queue.next() => {
let Some(job) = job else { break };
let started = Instant::now();
let side = job.geom.tile_pixels();
let (x, y) = (job.key.0 * TILE_TWIPS, job.key.1 * TILE_TWIPS);
let tile = doc.paint_tile(
&mut worker.lock().expect("the worker lock"),
(x, y, TILE_TWIPS, TILE_TWIPS),
(side, side),
);
let key = job.key;
log::debug!("lok: tile {key:?} in {} ms", started.elapsed().as_millis());
Landed::Tile(job, tile)
}
};
if landing.unbounded_send(done).is_err() {
break;
}
}
})
.detach();
cx.spawn(async move |this, cx| {
while let Some(first) = landed.next().await {
let mut batch = vec![first];
while let Ok(more) = landed.try_recv() {
batch.push(more);
}
let taken = this.update(cx, |view, cx| view.take_landed(batch, cx));
if taken.is_err() {
break;
}
}
})
.detach();
Lane { inputs, tiles }
}
fn take_landed(&mut self, batch: Vec<Landed>, cx: &mut Context<Self>) {
let mut reported = false;
for landed in batch {
match landed {
Landed::Input(seq, edits, outcome) => {
self.applied = seq;
self.edited += u64::from(edits);
let (outcome, now) = outcome;
if edits {
self.clock.landed(now);
}
self.seen_revision(now.unwrap_or(0));
match outcome {
Ok(Some(copied)) => self.copied = Some(copied),
Ok(None) => {}
Err(error) => {
log::error!("lok: input failed ({:?})", error.kind());
cx.emit(LokError(error.to_string()));
}
}
reported = true;
}
Landed::Tile(job, tile) => self.finish_tile(job.key, job.geom, tile, cx),
}
}
if reported {
cx.emit(Reported);
}
cx.notify();
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Kernel reads off the UI thread.
use std::{
io,
sync::{Arc, Mutex},
};
use gpui::Context;
use crate::{Doc, Worker};
/// Runs `read` on a background thread; `then` takes its result.
pub fn read_off<E: 'static, T: Send + 'static>(
worker: &Arc<Mutex<Worker>>,
doc: &Doc,
read: impl FnOnce(&mut Worker, &Doc) -> io::Result<T> + Send + 'static,
then: impl FnOnce(&mut E, io::Result<T>, &mut Context<E>) + 'static,
cx: &mut Context<E>,
) {
let (worker, doc) = (Arc::clone(worker), doc.clone());
cx.spawn(async move |this, cx| {
let read = cx
.background_executor()
.spawn(async move { read(&mut worker.lock().expect("the worker lock"), &doc) })
.await;
if this
.update(cx, |entity, cx| then(entity, read, cx))
.is_err()
{
log::info!("lok: a read outlived its reader");
}
})
.detach();
}
+69
View File
@@ -0,0 +1,69 @@
//! Frozen rows and columns stay; the rest scrolls (TABLE-02).
/// One axis: frozen extent and scroll past it, in twips.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Axis {
pub frozen: i32,
pub scroll: i32,
}
impl Axis {
/// Where document `doc` shows, in twips from the view's start.
pub fn show(self, doc: i32) -> i32 {
if doc < self.frozen {
doc
} else {
(doc - self.scroll).max(self.frozen)
}
}
/// The document point under view twips `at`.
pub fn doc(self, at: i32) -> i32 {
if at < self.frozen {
at
} else {
at + self.scroll
}
}
/// Each pane: document start and end, and its view start.
pub fn panes(self, length: i32) -> Vec<(i32, i32, i32)> {
let mut panes = Vec::with_capacity(2);
if self.frozen > 0 {
panes.push((0, self.frozen, 0));
}
let start = self.frozen + self.scroll;
panes.push((start, start + (length - self.frozen).max(0), self.frozen));
panes
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_frozen_part_stays_and_the_rest_scrolls() {
let axis = Axis {
frozen: 300,
scroll: 1000,
};
assert_eq!(axis.show(100), 100, "frozen rows stay");
assert_eq!(axis.show(1500), 500, "the rest moves by the scroll");
assert_eq!(axis.show(800), 300, "the hidden band folds to the line");
assert_eq!(axis.doc(100), 100);
assert_eq!(axis.doc(500), 1500);
assert_eq!(axis.panes(2000), [(0, 300, 0), (1300, 3000, 300)]);
}
#[test]
fn without_a_freeze_one_pane_scrolls() {
let axis = Axis {
frozen: 0,
scroll: 400,
};
assert_eq!(axis.show(1000), 600);
assert_eq!(axis.doc(600), 1000);
assert_eq!(axis.panes(2000), [(400, 2400, 0)]);
}
}
+113
View File
@@ -0,0 +1,113 @@
//! What the view knows, for apps to read.
use gpui::FocusHandle;
use super::LokView;
use crate::Rect;
impl LokView {
/// Whether the kernel paints dark; None before the first frame.
pub fn dark(&self) -> Option<bool> {
self.dark
}
/// The kernel's state for `uno`, as LOK reports it (LOK-05).
pub fn state(&self, uno: &str) -> Option<&str> {
self.states.get(uno).map(String::as_str)
}
/// The selected object's frame in twips, if any.
pub fn graphic(&self) -> Option<Rect> {
self.graphic
}
/// Bumps when comments or tracked changes change.
pub fn review(&self) -> u64 {
self.review
}
/// The cursor in twips, if the kernel shows one.
pub fn cursor(&self) -> Option<Rect> {
self.cursor
}
/// Whether the kernel shows a caret.
pub fn caret(&self) -> bool {
self.cursor_visible && self.cursor.is_some()
}
/// Counts cursor moves the kernel reported.
pub fn moves(&self) -> u64 {
self.moves
}
/// What a spreadsheet reports about its current cell.
pub fn cell(&self) -> &crate::Cell {
&self.cell
}
/// Document twips as a point inside the view.
pub fn place(&self, at: (i32, i32)) -> gpui::Point<gpui::Pixels> {
self.window_point(at) - self.origin
}
/// The view's size in pixels at the last paint.
pub fn viewport(&self) -> (f32, f32) {
self.viewport
}
/// Frozen columns and rows, in twips.
pub fn frozen(&self) -> (i32, i32) {
self.frozen
}
/// The view's top left in window coordinates.
pub fn origin(&self) -> gpui::Point<gpui::Pixels> {
self.origin
}
/// A view-local point as document twips.
pub fn twips_at(&self, at: gpui::Point<gpui::Pixels>) -> (i32, i32) {
self.doc_point(at + self.origin)
}
/// Each page's frame in twips.
pub fn pages(&self) -> &[Rect] {
&self.pages
}
/// The selection's rectangles in twips.
pub fn selection(&self) -> &[Rect] {
&self.selection
}
/// The last search's count and matches.
pub fn search(&self) -> (u64, &[Rect]) {
(self.search.0, &self.search.1)
}
/// Fonts the document names and the system lacks.
pub fn missing_fonts(&self) -> &[String] {
&self.fonts
}
/// Takes the context menu the kernel last offered.
pub fn take_menu(&mut self) -> Option<String> {
self.menu.take()
}
/// The paragraph's own tab stops, in 1/100 mm.
pub fn tabs(&self) -> &[i32] {
&self.tabs
}
/// The handle apps focus to type into the document.
pub fn focus_handle(&self) -> &FocusHandle {
&self.focus
}
/// Whether the clipboard `html` is this view's last copy.
pub fn holds_copy(&self, html: &str) -> bool {
super::clip::mark_of(html).is_some_and(|mark| self.copied.as_deref() == Some(mark))
}
}
+346
View File
@@ -0,0 +1,346 @@
//! LokView's element tree and paint (LOK-03, §7 tail).
use ely_gpui_component::theme::ActiveTheme;
use gpui::{
BorderStyle, Bounds, ContentMask, Context, Corners, CursorStyle, Edges, ElementInputHandler,
InteractiveElement, IntoElement, MouseButton, ParentElement, Render, Role,
StatefulInteractiveElement, Styled, Window, canvas, div, fill, outline, px, quad, size,
transparent_black,
};
use std::sync::Arc;
use gpui::{Pixels, RenderImage, point};
use super::{CONTEXT, LokView, TILE_TWIPS, TWIPS_PER_PIXEL, handles, input};
use crate::Rect;
/// Ely's kernel color schemes, from `ely.xcd`.
const DARK: &str = "COLOR_SCHEME_ELY_DARK";
const LIGHT: &str = "COLOR_SCHEME_ELY_LIGHT";
/// The kernel scheme for a light or dark app.
pub fn scheme(dark: bool) -> &'static str {
if dark { DARK } else { LIGHT }
}
impl LokView {
/// Paints with the app's light or dark scheme.
pub(super) fn follow_theme(&mut self, dark: bool) {
if self.dark != Some(dark) {
self.dark = Some(dark);
let scheme = scheme(dark);
log::info!("lok: paints with {scheme}");
self.send(input::Input::Theme(scheme));
}
}
}
impl Render for LokView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let dpi = window.scale_factor();
if dpi != self.geom.dpi {
self.geom.dpi = dpi;
self.retire_tiles();
}
self.follow_theme(cx.theme().is_dark());
let this = cx.entity().clone();
let focus = self.focus.clone();
let colors = &cx.theme().colors;
let paper = super::paper(cx);
let (selection_color, caret_color) = (colors.selection, colors.focus);
let canvas_color = colors.sunken;
let caret_width = cx.theme().caret_width().to_pixels(window.rem_size());
self.handle_size = cx.theme().handle_hit().to_pixels(window.rem_size());
let (frame_color, handle_fill) = (colors.focus, colors.bg);
div()
.id("lok-view")
.role(Role::MultilineTextInput)
.aria_value(self.a11y.text.clone())
.key_context(CONTEXT)
.track_focus(&self.focus)
.cursor(CursorStyle::IBeam)
.size_full()
.overflow_hidden()
.bg(canvas_color)
.on_action(cx.listener(Self::on_copy))
.on_action(cx.listener(Self::on_cut))
.on_action(cx.listener(Self::on_next_field))
.on_action(cx.listener(Self::on_previous_field))
.on_action(cx.listener(Self::on_paste))
.on_key_down(cx.listener(Self::on_key_down))
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
.on_mouse_down(MouseButton::Right, cx.listener(Self::on_mouse_down))
.on_mouse_down(MouseButton::Middle, cx.listener(Self::on_mouse_down))
.on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
.on_mouse_up(MouseButton::Right, cx.listener(Self::on_mouse_up))
.on_mouse_up(MouseButton::Middle, cx.listener(Self::on_mouse_up))
.on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up_out))
.on_mouse_move(cx.listener(Self::on_mouse_move))
.on_scroll_wheel(cx.listener(Self::on_wheel))
.on_pinch(cx.listener(Self::on_pinch))
.child(
canvas(
{
let this = this.clone();
move |bounds, window, app| {
this.update(app, |view, _| {
view.retired.release(window);
view.prepare(bounds)
})
}
},
move |bounds, painted, window, app| {
for page in &painted.pages {
window.paint_quad(fill(*page, paper));
window.with_content_mask(
Some(ContentMask { bounds: *page }),
|window| {
for (rect, image, clip) in &painted.tiles {
let mask = Some(ContentMask { bounds: *clip });
let painted = window.with_content_mask(mask, |window| {
window.paint_image(
*rect,
*rect,
Corners::default(),
image.clone(),
0,
false,
)
});
if let Err(error) = painted {
log::error!("lok: tile paint failed: {error}");
}
}
},
);
}
window.with_content_mask(Some(ContentMask { bounds }), |window| {
for rect in painted.selection {
window.paint_quad(fill(rect, selection_color));
}
for (mark, color) in painted.marks {
window.paint_quad(quad(
mark,
Corners::default(),
transparent_black(),
Edges::all(px(2.0)),
color,
BorderStyle::Solid,
));
}
if let Some(cell) = painted.cell {
window.paint_quad(quad(
cell,
Corners::default(),
transparent_black(),
Edges::all(px(2.0)),
frame_color,
BorderStyle::Solid,
));
}
if let Some((frame, handles)) = painted.frame {
window.paint_quad(outline(frame, frame_color, BorderStyle::Solid));
for handle in handles {
window.paint_quad(quad(
handle,
Corners::default(),
handle_fill,
Edges::all(px(1.0)),
frame_color,
BorderStyle::Solid,
));
}
}
if let Some(caret) = painted.caret.filter(|_| focus.is_focused(window))
{
let caret = Bounds {
size: size(caret_width, caret.size.height),
..caret
};
window.paint_quad(fill(caret, caret_color));
}
});
window.handle_input(&focus, ElementInputHandler::new(bounds, this), app);
},
)
.size_full(),
)
.children(self.hints(cx))
}
}
/// The page mask, tiles, selection and caret to paint.
pub(super) struct Painted {
/// Page frames on screen; tiles show only inside them.
pub(super) pages: Vec<Bounds<Pixels>>,
/// Each tile, its place and the pane that clips it.
pub(super) tiles: Vec<(Bounds<Pixels>, Arc<RenderImage>, Bounds<Pixels>)>,
pub(super) selection: Vec<Bounds<Pixels>>,
pub(super) caret: Option<Bounds<Pixels>>,
/// A spreadsheet's cell cursor.
pub(super) cell: Option<Bounds<Pixels>>,
/// The selected object's frame and handle squares.
pub(super) frame: Option<(Bounds<Pixels>, Vec<Bounds<Pixels>>)>,
/// The references of a formula being typed.
pub(super) marks: Vec<(Bounds<Pixels>, gpui::Hsla)>,
}
impl LokView {
/// The zoom that fits the page, with a margin.
fn fit_zoom(&mut self) {
const MARGIN: f32 = 0.94;
let (w, h) = self.doc_size;
if w <= 0 || h <= 0 || self.viewport.0 <= 0.0 || self.viewport.1 <= 0.0 {
return;
}
let across = self.viewport.0 * TWIPS_PER_PIXEL / w as f32;
let down = self.viewport.1 * TWIPS_PER_PIXEL / h as f32;
let zoom = (across.min(down) * MARGIN).min(4.0);
if (zoom - self.geom.zoom).abs() > 0.001 {
self.geom.zoom = zoom;
self.retire_tiles();
self.failed.clear();
}
}
/// All its images, for a closing tab to free.
pub fn retire_all(&mut self) -> ely_gpui_component::primitives::Retired {
self.retire_tiles();
std::mem::take(&mut self.retired)
}
/// Every tile goes; their images are freed next paint.
pub(super) fn retire_tiles(&mut self) {
for (_, tile) in self.tiles.drain() {
self.retired.push(tile.image);
}
}
/// Drops tiles over a screen away from any shown one.
fn keep_near(&mut self, (vw, vh): (i32, i32)) {
let reach = (vw / TILE_TWIPS + 1, vh / TILE_TWIPS + 1);
let shown = &self.on_screen;
let before = self.tiles.len();
let retired = &mut self.retired;
self.tiles.retain(|key, tile| {
let near = shown
.iter()
.any(|at| (key.0 - at.0).abs() <= reach.0 && (key.1 - at.1).abs() <= reach.1);
if !near {
retired.push(tile.image.clone());
}
near
});
if self.tiles.len() < before {
log::debug!("lok: dropped {} far tiles", before - self.tiles.len());
}
}
/// The page mask and visible tiles; requests the missing ones.
pub(super) fn prepare(&mut self, bounds: Bounds<Pixels>) -> Painted {
self.viewport = (bounds.size.width.into(), bounds.size.height.into());
self.origin = bounds.origin;
if self.fit {
self.fit_zoom();
}
self.clamp_scroll();
let geom = self.geom;
let (sx, sy) = self.scroll;
// A narrow document sits centered.
let extent = self.extent();
let slack = |view: f32, doc: i32| (view - geom.px_of(doc)).max(0.0) / 2.0;
// A fitted page sits centred both ways.
self.spare = (
slack(self.viewport.0, extent.0),
if self.fit {
slack(self.viewport.1, extent.1)
} else {
0.0
},
);
let pages = if self.pages.is_empty() {
vec![self.screen_rect((0, 0, extent.0, extent.1))]
} else {
self.pages
.iter()
.map(|&page| self.screen_rect(page))
.collect()
};
let (vw, vh) = (
geom.twips_of(bounds.size.width.into()),
geom.twips_of(bounds.size.height.into()),
);
if self.shown != Some((sx, sy, vw, vh)) {
self.shown = Some((sx, sy, vw, vh));
self.failed.clear();
self.send(input::Input::Visible((sx, sy, vw, vh)));
}
let (ax, ay) = self.axes();
let side = px(geom.px_of(TILE_TWIPS));
let at = |vx: i32, vy: i32| {
bounds.origin
+ point(
px(self.spare.0 + geom.px_of(vx)),
px(self.spare.1 + geom.px_of(vy)),
)
};
let mut ready = Vec::new();
let mut missing = Vec::new();
self.on_screen.clear();
for (dx0, dx1, vx) in ax.panes(vw) {
for (dy0, dy1, vy) in ay.panes(vh) {
let clip = Bounds::from_corners(at(vx, vy), at(vx + dx1 - dx0, vy + dy1 - dy0));
let (kx0, ky0) = (dx0.div_euclid(TILE_TWIPS), dy0.div_euclid(TILE_TWIPS));
let (kx1, ky1) = (dx1.div_euclid(TILE_TWIPS), dy1.div_euclid(TILE_TWIPS));
for key in (kx0..=kx1).flat_map(|kx| (ky0..=ky1).map(move |ky| (kx, ky))) {
if key.0 * TILE_TWIPS >= extent.0 || key.1 * TILE_TWIPS >= extent.1 {
continue;
}
self.on_screen.push(key);
match self.tiles.get(&key) {
Some(tile) => {
let origin =
at(vx + key.0 * TILE_TWIPS - dx0, vy + key.1 * TILE_TWIPS - dy0);
let place = Bounds {
origin,
size: size(side, side),
};
ready.push((place, Arc::clone(&tile.image), clip));
if tile.stale {
missing.push(key);
}
}
None => missing.push(key),
}
}
}
}
self.keep_near((vw, vh));
for key in missing {
self.request_tile(key);
}
let rect = |rect: Rect| self.screen_rect(rect);
let caret = self.cursor.filter(|_| self.cursor_visible).map(rect);
let half = self.handle_size / 2.0;
let frame = self.frame().map(|frame| {
let squares = handles::points(frame)
.iter()
.map(|&(x, y)| Bounds {
origin: self.window_point((x, y)) - point(half, half),
size: size(self.handle_size, self.handle_size),
})
.collect();
(rect(frame), squares)
});
Painted {
pages,
tiles: ready,
selection: self.selection.iter().copied().map(rect).collect(),
caret,
cell: self.cell.cursor.map(rect),
frame,
marks: self.marks(),
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Scrolling the page view (LOK-04).
use gpui::{
Bounds, Context, Pixels, Point, ScrollDelta, ScrollWheelEvent, Window, point, px, size,
};
use super::{LokView, input::Input};
use crate::{Mouse, Rect};
impl LokView {
/// Scrolls by view pixels, clamped to the document (LOK-04).
pub(super) fn scroll_by(&mut self, dx: f32, dy: f32, cx: &mut Context<Self>) {
self.scroll.0 -= self.geom.twips_of(dx);
self.scroll.1 -= self.geom.twips_of(dy);
self.clamp_scroll();
cx.notify();
}
/// Keeps the viewport inside the document (LOK-04).
pub(super) fn clamp_scroll(&mut self) {
let (vw, vh) = (
self.geom.twips_of(self.viewport.0),
self.geom.twips_of(self.viewport.1),
);
let extent = self.extent();
self.scroll.0 = self.scroll.0.clamp(0, (extent.0 - vw).max(0));
self.scroll.1 = self.scroll.1.clamp(0, (extent.1 - vh).max(0));
}
/// Scrolls the wheel in twips, clamped to the document (LOK-04).
pub(super) fn on_scroll(
&mut self,
event: &ScrollWheelEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
let (dx, dy) = match event.delta {
ScrollDelta::Pixels(point) => (f32::from(point.x), f32::from(point.y)),
ScrollDelta::Lines(point) => (point.x * 40.0, point.y * 40.0),
};
self.scroll_by(dx, dy, cx);
}
/// Scrolls `rect` into view; frozen parts always show.
pub fn show(&mut self, (x, y, w, h): Rect, cx: &mut Context<Self>) {
let (fx, fy) = self.frozen;
let (vw, vh) = (
self.geom.twips_of(self.viewport.0) - fx,
self.geom.twips_of(self.viewport.1) - fy,
);
// Room past the target, so the clamp lets it show.
self.reach = (
self.reach.0.max(x + w + vw + fx),
self.reach.1.max(y + h + vh + fy),
);
if x >= fx && (x < fx + self.scroll.0 || x + w > fx + self.scroll.0 + vw) {
self.scroll.0 = x - fx - vw / 2;
}
if y >= fy && (y < fy + self.scroll.1 || y + h > fy + self.scroll.1 + vh) {
self.scroll.1 = y - fy - vh / 3;
}
self.clamp_scroll();
cx.notify();
}
/// Freezes what lies before `frozen`, in twips.
pub fn set_frozen(&mut self, frozen: (i32, i32), cx: &mut Context<Self>) {
if self.frozen != frozen {
log::info!("lok: frozen at {frozen:?}");
self.frozen = frozen;
cx.notify();
}
}
/// Scrolls `rect` into view and puts the cursor there.
pub fn reveal(&mut self, rect: Rect, cx: &mut Context<Self>) {
self.show(rect, cx);
let (x, y, _, h) = rect;
log::info!("lok: reveal at {x},{y}");
for kind in [0, 1] {
let (count, buttons, modifiers) = (1, 1, 0);
let y = y + h / 2;
self.send(Input::Mouse(Mouse {
kind,
x,
y,
count,
buttons,
modifiers,
}));
}
}
/// The scroll offset in twips.
pub fn scroll(&self) -> (i32, i32) {
self.scroll
}
/// The document extent the view may scroll over.
pub(super) fn extent(&self) -> (i32, i32) {
// A fitted page is the page, whatever the cursor reached.
if self.fit {
return self.doc_size;
}
(
self.doc_size.0.max(self.reach.0),
self.doc_size.1.max(self.reach.1),
)
}
/// The document point under a view position (LOK-04).
pub fn doc_point(&self, position: Point<Pixels>) -> (i32, i32) {
let local = position - self.origin;
let (ax, ay) = self.axes();
(
ax.doc(self.geom.twips_of(f32::from(local.x) - self.spare.0)),
ay.doc(self.geom.twips_of(f32::from(local.y) - self.spare.1)),
)
}
/// The panes of each axis.
pub(super) fn axes(&self) -> (super::panes::Axis, super::panes::Axis) {
let axis = |frozen, scroll| super::panes::Axis { frozen, scroll };
(
axis(self.frozen.0, self.scroll.0),
axis(self.frozen.1, self.scroll.1),
)
}
/// The window point of a document point in twips (LOK-04).
pub fn window_point(&self, (x, y): (i32, i32)) -> gpui::Point<Pixels> {
let (ax, ay) = self.axes();
let (x, y) = (self.geom.px_of(ax.show(x)), self.geom.px_of(ay.show(y)));
self.origin + point(px(self.spare.0 + x), px(self.spare.1 + y))
}
/// A document rect in window pixels, panes applied.
pub(super) fn screen_rect(&self, (x, y, w, h): crate::Rect) -> Bounds<Pixels> {
Bounds::from_corners(self.window_point((x, y)), self.window_point((x + w, y + h)))
}
/// The cursor rect in window pixels.
pub fn cursor_bounds(&self) -> Option<Bounds<Pixels>> {
let (x, y, w, h) = self.cursor?;
Some(Bounds {
origin: self.window_point((x, y)),
size: size(px(self.geom.px_of(w.max(1))), px(self.geom.px_of(h))),
})
}
}
+466
View File
@@ -0,0 +1,466 @@
use super::*;
mod clip;
mod commands;
mod fit;
mod input;
mod large;
mod theme;
use gpui::{App, Bounds, Entity, point, size};
#[test]
fn geom_converts_both_ways() {
let geom = Geom {
zoom: 2.0,
dpi: 2.0,
};
assert_eq!(geom.px_of(15), 2.0, "15 twips at 200% zoom is 2 logical px");
assert_eq!(geom.twips_of(2.0), 15, "2 logical px back to 15 twips");
assert_eq!(geom.tile_pixels(), 1024, "the texture is 1024 device px");
let base = Geom {
zoom: 1.0,
dpi: 2.0,
};
assert_eq!(base.px_of(TILE_TWIPS), 256.0, "one tile is 256 logical px");
assert_eq!(
base.twips_of(256.0),
TILE_TWIPS,
"256 logical px is one tile"
);
assert_eq!(base.tile_pixels(), 512, "the texture is 512 device px");
}
pub(super) fn live_view(
app: &mut App,
install: &std::path::Path,
) -> (Entity<LokView>, Arc<Mutex<crate::Worker>>) {
live_view_of(app, install, "note.fodt", crate::client::tests::FODT)
}
/// A view on `body` saved as `name`.
pub(super) fn live_view_of(
app: &mut App,
install: &std::path::Path,
name: &str,
body: &str,
) -> (Entity<LokView>, Arc<Mutex<crate::Worker>>) {
let dir = tempfile::tempdir().expect("a temp dir");
let mut worker =
crate::Worker::spawn(install, &dir.path().join("profile")).expect("the worker");
let source = dir.path().join(name);
std::fs::write(&source, body).expect("the fixture writes");
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the document loads");
std::mem::forget(dir);
let shared = Arc::new(Mutex::new(worker));
let laid = super::layout(&mut shared.lock().expect("the worker lock"), &doc)
.expect("the layout reads");
let view = LokView::open(Arc::clone(&shared), doc, laid, app);
(view, shared)
}
#[test]
fn edits_grow_the_view_size() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let before = view.doc_size;
{
let mut worker = view.worker.lock().expect("the worker lock");
for _ in 0..80 {
worker.post_key(&view.doc, 0, 1280).expect("Return posts");
}
}
let measured = super::measure(&view.worker, &view.doc);
view.apply_batch(
crate::Events {
generation: 1,
all: true,
rects: Vec::new(),
..crate::Events::default()
},
Some(measured),
cx,
);
assert!(
view.doc_size.1 > before.1,
"the view size follows the document: {before:?} to {:?}",
view.doc_size
);
});
});
}
#[test]
fn releasing_the_view_stops_the_watch() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
let (view, shared) = cx.update(|app| live_view(app, &install));
for _ in 0..5 {
cx.executor().tick();
}
let weak = Arc::downgrade(&shared);
drop(shared);
cx.update(|_| drop(view));
let mut released = false;
for _ in 0..20 {
cx.executor().tick();
released = weak.upgrade().is_none();
if released {
break;
}
}
assert!(released, "the idle watch releases the worker");
}
#[test]
fn tiles_paint_in_logical_pixels_at_2x() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
view.geom.dpi = 2.0;
let side = view.geom.tile_pixels() as usize;
assert_eq!(side, 512, "a 2x tile texture is 512 px");
for key in [(0, 0), (1, 0)] {
let tile = crate::Tile {
generation: 0,
pixels: vec![255u8; side * side * 4],
};
view.finish_tile(key, view.geom, Ok(tile), cx);
}
let bounds = Bounds {
origin: point(px(10.0), px(20.0)),
size: size(px(800.0), px(600.0)),
};
let ready = view.prepare(bounds).tiles;
let rects: Vec<_> = ready.iter().map(|(rect, ..)| *rect).collect();
assert!(rects.len() >= 2, "both cached tiles paint: {rects:?}");
assert_eq!(rects[0].size.width, px(256.0), "one tile is 256 logical px");
assert_eq!(rects[0].origin, point(px(10.0), px(20.0)));
assert_eq!(rects[1].origin.x, px(266.0), "the next tile sits 256 px on");
assert_eq!(view.doc_point(point(px(266.0), px(20.0))), (TILE_TWIPS, 0));
});
});
}
#[test]
fn a_red_tile_stays_red_in_the_render_image() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let side = view.geom.tile_pixels() as usize;
let red_bgra = [0u8, 0, 255, 255];
let tile = crate::Tile {
generation: 0,
pixels: red_bgra.repeat(side * side),
};
view.finish_tile((0, 0), view.geom, Ok(tile), cx);
let image = &view.tiles[&(0, 0)].image;
let bytes = image.as_bytes(0).expect("one frame");
assert_eq!(&bytes[..4], &red_bgra, "GPUI gets the BGRA bytes as is");
});
});
}
#[test]
fn the_view_clamps_scroll_and_guards_generations() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
view.viewport = (800.0, 600.0);
view.scroll_by(0.0, -100_000.0, cx);
let max_y = (view.doc_size.1 - view.geom.twips_of(600.0)).max(0);
assert_eq!(view.scroll.1, max_y, "scroll clamps at the bottom");
view.scroll_by(0.0, 1_000_000.0, cx);
assert_eq!(view.scroll.1, 0, "scroll clamps at the top");
assert!(view.doc_size.0 > 0 && view.doc_size.1 > 0, "the size loads");
let geom = view.geom;
let side = geom.tile_pixels() as usize;
let painted = |generation: u64| {
Ok(crate::Tile {
generation,
pixels: vec![0u8; side * side * 4],
})
};
view.finish_tile((0, 0), geom, painted(0), cx);
assert_eq!(view.tile_count(), 1, "a current tile lands");
view.apply_batch(
crate::Events {
generation: 5,
all: true,
rects: Vec::new(),
..crate::Events::default()
},
None,
cx,
);
assert_eq!(view.tile_count(), 0, "an all batch outdates the grid");
assert_eq!(view.tiles.len(), 1, "the old image shows until its repaint");
view.finish_tile((0, 0), geom, painted(4), cx);
assert_eq!(view.tile_count(), 0, "a stale tile never lands");
view.finish_tile((0, 0), geom, painted(5), cx);
assert_eq!(view.tile_count(), 1, "a fresh tile lands again");
view.apply_batch(
crate::Events {
generation: 6,
all: false,
rects: vec![(100, 100, 50, 50)],
..crate::Events::default()
},
None,
cx,
);
assert_eq!(
view.tile_count(),
0,
"a rect batch outdates intersecting tiles"
);
view.finish_tile((0, 0), geom, painted(6), cx);
view.finish_tile((3, 3), geom, painted(6), cx);
view.apply_batch(
crate::Events {
generation: 7,
all: false,
rects: vec![(284, 1418, 3715, 551)],
..crate::Events::default()
},
None,
cx,
);
assert!(!view.tiles[&(3, 3)].stale, "a distant tile stays current");
assert!(
view.tiles[&(0, 0)].stale,
"the dirty tile waits for its repaint"
);
let bounds = Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(800.0), px(600.0)),
};
let painted = view.prepare(bounds);
assert!(!painted.tiles.is_empty(), "stale tiles still paint");
assert!(
view.fetching.contains(&(0, 0)),
"and their repaint is asked"
);
});
});
}
#[test]
fn scroll_stays_inside_after_shrink_zoom_and_resize() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let bottom =
|view: &LokView| (view.doc_size.1 - view.geom.twips_of(view.viewport.1)).max(0);
view.viewport = (800.0, 600.0);
{
let mut worker = view.worker.lock().expect("the worker lock");
for _ in 0..80 {
worker.post_key(&view.doc, 0, 1280).expect("Return posts");
}
}
let batch = |generation| crate::Events {
generation,
all: true,
..crate::Events::default()
};
view.apply_batch(batch(1), None, cx);
view.scroll_by(0.0, -1_000_000.0, cx);
assert_eq!(view.scroll.1, bottom(view), "scrolled to the grown bottom");
{
let mut worker = view.worker.lock().expect("the worker lock");
worker
.run(&view.doc, "edit.select_all", &[])
.expect("select all");
worker.cut(&view.doc).expect("the cut runs");
}
view.apply_batch(batch(2), None, cx);
assert_eq!(
view.scroll.1,
bottom(view),
"a shrink pulls the scroll back"
);
view.set_zoom(2.0, cx);
view.scroll_by(0.0, -1_000_000.0, cx);
view.set_zoom(0.25, cx);
assert_eq!(
view.scroll.1,
bottom(view),
"a smaller zoom pulls the scroll back"
);
view.set_zoom(2.0, cx);
view.viewport = (800.0, 300.0);
view.scroll_by(0.0, -1_000_000.0, cx);
let bounds = Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(800.0), px(1200.0)),
};
view.prepare(bounds);
assert_eq!(
view.scroll.1,
bottom(view),
"a taller viewport pulls the scroll back"
);
});
});
}
#[test]
fn a_moved_cursor_scrolls_into_view_and_a_still_one_does_not() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
view.viewport = (800.0, 200.0);
let far = Some((1418, view.doc_size.1 - 600, 1, 276));
let batch = || crate::Events {
cursor: far,
..crate::Events::default()
};
view.apply_batch(batch(), None, cx);
assert!(view.scroll.1 > 0, "the view follows the cursor");
view.scroll_by(0.0, 1_000_000.0, cx);
view.apply_batch(batch(), None, cx);
assert_eq!(view.scroll.1, 0, "a still cursor leaves the scroll alone");
let far = view.doc_size.1 + 20_000;
let cell = crate::Cell {
cursor: Some((1418, far, 1280, 277)),
..crate::Cell::default()
};
view.apply_batch(
crate::Events {
cell,
..crate::Events::default()
},
None,
cx,
);
let height = view.geom.twips_of(view.viewport.1);
assert!(
view.scroll.1 <= far && far + 277 <= view.scroll.1 + height,
"a cell past the kernel's size still comes into view"
);
view.scroll = (0, 0);
let width = view.geom.twips_of(view.viewport.0);
view.show((width - 200, 0, 1280, 256), cx);
assert!(
view.scroll.0 > 0 && width - 200 + 1280 <= view.scroll.0 + width,
"a cell cut at the right edge comes into view"
);
view.scroll = (0, 0);
view.frozen = (0, 600);
view.show((1418, 300, 1280, 277), cx);
assert_eq!(view.scroll.1, 0, "a frozen row needs no scroll");
view.show((1418, 9000, 1280, 277), cx);
let scrolled = view.scroll.1;
assert!(scrolled > 0, "a far row scrolls the rest");
let row = view.place((0, 300)).y;
assert_eq!(f32::from(row), view.geom.px_of(300), "the frozen row stays");
let far = view.twips_at(view.place((0, 9000)));
assert!(
(far.1 - 9000).abs() <= 15,
"a scrolled row maps back: {far:?}"
);
});
});
}
#[test]
fn a_closing_view_hands_over_every_image() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let side = view.geom.tile_pixels() as usize;
let tile = |generation| Ok(crate::Tile { generation, pixels: vec![0; side * side * 4] });
let (geom, generation) = (view.geom, view.generation);
view.finish_tile((0, 0), geom, tile(generation), cx);
view.finish_tile((0, 0), geom, tile(generation), cx);
assert_eq!(view.tiles.len(), 1);
let images = view.retire_all();
assert!(!images.is_empty(), "the shown and the replaced tile go");
assert!(view.tiles.is_empty() && view.retired.is_empty(), "the view keeps none");
});
});
}
#[test]
fn zooming_keeps_the_pointed_spot_and_walks_the_steps() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
view.viewport = (800.0, 600.0);
view.origin = gpui::point(gpui::px(0.0), gpui::px(0.0));
view.doc_size = (60_000, 80_000);
view.scroll = (3_000, 9_000);
view.fit = true;
let at = gpui::point(gpui::px(300.0), gpui::px(200.0));
let spot = |view: &LokView| {
(view.scroll.0 + view.geom.twips_of(300.0), view.scroll.1 + view.geom.twips_of(200.0))
};
let before = spot(view);
view.zoom_at(2.0, Some(at), cx);
let after = spot(view);
assert!((before.0 - after.0).abs() <= 1 && (before.1 - after.1).abs() <= 1, "{before:?} {after:?}");
assert!(!view.fitting(), "a chosen zoom ends fitting");
view.set_zoom(1.0, cx);
view.zoom_step(true, cx);
assert_eq!(view.zoom(), 1.25);
view.zoom_step(false, cx);
view.zoom_step(false, cx);
assert_eq!(view.zoom(), 0.8);
view.set_zoom(9.0, cx);
assert_eq!(view.zoom(), 4.0, "the most is 400 %");
view.zoom_step(true, cx);
assert_eq!(view.zoom(), 4.0);
view.fit_page(cx);
assert!(view.fitting());
});
});
}
+91
View File
@@ -0,0 +1,91 @@
use super::*;
use ely_platform::clipboard::{self, Clip};
use gpui::TestAppContext;
const BOOK: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S"><table:table-row>
<table:table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:table-cell>
<table:table-cell table:formula="of:=[.A1]*3" office:value-type="float" office:value="6"><text:p>6</text:p></table:table-cell>
</table:table-row></table:table></office:spreadsheet></office:body>
</office:document>"#;
fn flush(cx: &TestAppContext) {
for _ in 0..80 {
cx.executor().tick();
}
}
fn goto(view: &Entity<LokView>, cx: &mut TestAppContext, cell: &str) {
cx.update(|app| {
let view = view.read(app);
let mut worker = view.worker.lock().expect("the worker lock");
worker
.run(&view.doc, "cell.goto", &[cell])
.expect("the cell");
});
}
/// The workbook as flat XML.
fn saved(view: &Entity<LokView>, cx: &mut TestAppContext) -> String {
let out = tempfile::tempdir()
.expect("a temp dir")
.keep()
.join("out.fods");
cx.update(|app| {
let view = view.read(app);
let mut worker = view.worker.lock().expect("the worker lock");
view.doc
.save_as(&mut worker, &format!("file://{}", out.display()), "fods")
.expect("the save works");
});
std::fs::read_to_string(&out).expect("the save reads")
}
#[test]
fn values_and_formulas_paste_alone_from_the_views_copy() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
if std::env::var_os("ELY_CLIPBOARD_TEST").is_none() {
eprintln!("SKIP: set ELY_CLIPBOARD_TEST=1; this replaces the clipboard");
return;
}
let mut cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view_of(app, &install, "book.fods", BOOK));
goto(&view, &mut cx, "B1");
cx.update(|app| {
view.update(app, |view, _| {
view.send(crate::view::input::Input::Copy { cut: false })
})
});
flush(&cx);
for (cell, id) in [("C1", "paste.values"), ("D1", "paste.formulas")] {
goto(&view, &mut cx, cell);
cx.update(|app| view.update(app, |view, _| view.paste_only(id)));
flush(&cx);
}
let xml = saved(&view, &mut cx);
assert_eq!(xml.matches("table:formula=").count(), 2, "C1 holds 6 alone");
assert!(xml.contains("of:=[.C1]*3"), "D1 keeps the formula");
let copy = cx.update(|app| {
let read = clipboard::read().expect("the clipboard reads");
let Some(Clip::Html { html, .. }) = read else {
panic!("the copy lands as html");
};
view.read(app).holds_copy(&html)
});
assert!(copy, "the view knows its own copy");
// Copies made elsewhere carry no mark of this view.
let other = "<table><tr><td>6</td></tr></table>";
assert!(cx.update(|app| !view.read(app).holds_copy(other)));
let foreign = "<td>6</td><!--ely-copy:1-999-->";
assert!(
cx.update(|app| !view.read(app).holds_copy(foreign)),
"another copy's mark"
);
}
+167
View File
@@ -0,0 +1,167 @@
use super::*;
use gpui::TestAppContext;
/// Steps the scheduler until `done` or the budget ends.
fn settle(cx: &TestAppContext, done: impl Fn(&App) -> bool) -> bool {
for _ in 0..60 {
for _ in 0..20 {
cx.executor().tick();
}
if cx.update(|app| done(app)) {
return true;
}
}
false
}
#[test]
fn run_reaches_the_kernel_and_state_comes_back() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
cx.update(|app| {
view.update(app, |view, _| {
assert!(
view.run("format.dialog", &[]).is_err(),
"unknown ids fail fast"
);
assert!(
view.run("format.size", &[]).is_err(),
"missing values fail fast"
);
view.commit(None, "a");
view.run("edit.select_all", &[]).expect("select all queues");
view.run("format.bold", &[]).expect("bold queues");
view.run("format.size", &["20"]).expect("size queues");
})
});
let landed = settle(&cx, |app| {
let view = view.read(app);
view.state(".uno:Bold") == Some("true")
&& view.state(".uno:FontHeight") == Some("20")
&& view.a11y.text == "aHello 世界"
});
assert!(landed, "the kernel state reaches the view");
cx.update(|app| {
let view = view.read(app);
assert_eq!(
view.a11y.text, "aHello 世界",
"the a11y text follows the paragraph"
);
});
}
#[test]
fn a_kernel_dialog_reaches_apps_as_an_error() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let body = crate::client::tests::input::FODS;
let (view, _) = cx.update(|app| live_view_of(app, &install, "in.fods", body));
let errors = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
cx.update(|app| {
let errors = errors.clone();
app.subscribe(&view, move |_, error: &LokError, _| {
errors.borrow_mut().push(error.0.clone())
})
.detach();
view.update(app, |view, _| {
view.key_down(&gpui::Keystroke::parse("backspace").expect("backspace"));
});
});
let reported = settle(&cx, |_| !errors.borrow().is_empty());
assert!(reported, "the blocked dialog reaches subscribers");
assert!(
errors.borrow()[0].contains("Delete Contents"),
"{:?}",
errors.borrow()
);
}
#[test]
fn a_dead_worker_reaches_apps_while_idle() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, shared) = cx.update(|app| live_view(app, &install));
let errors = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
cx.update(|app| {
let errors = errors.clone();
app.subscribe(&view, move |_, error: &LokError, _| {
errors.borrow_mut().push(error.0.clone())
})
.detach();
});
let pid = shared.lock().expect("the worker lock").child.id();
std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.status()
.expect("kill runs");
let reported = settle(&cx, |_| !errors.borrow().is_empty());
assert!(reported, "the idle watch reports the dead engine");
assert!(
errors.borrow()[0].contains("engine stopped"),
"{:?}",
errors.borrow()
);
}
#[test]
fn a_handle_drag_resizes_the_selected_image() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
let dir = tempfile::tempdir().expect("a temp dir");
let mut png = Vec::new();
image::RgbaImage::from_pixel(300, 200, image::Rgba([0, 0, 255, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("the png encodes");
let path = dir.path().join("blue.png");
std::fs::write(&path, png).expect("the png writes");
let url = crate::file_url(&path);
cx.update(|app| view.update(app, |view, _| view.run("image.insert", &[&url])))
.expect("the insert queues");
assert!(
settle(&cx, |app| view.read(app).graphic.is_some()),
"the image is selected"
);
let frame = cx.update(|app| view.read(app).graphic).expect("selected");
let corner = super::super::handles::points(frame)[7];
let to = (corner.0 - frame.2 / 3, corner.1 - frame.3 / 3);
cx.update(|app| {
view.update(app, |view, _| {
assert!(
view.grab(view.window_point(corner)),
"the corner handle grabs"
);
view.grip = view
.grip
.map(|grip| super::super::handles::Grip { to, ..grip });
assert_eq!(
view.frame(),
Some(super::super::handles::dragged(frame, 7, to))
);
let grip = view.grip.take().expect("held");
view.send(super::super::input::Input::Drag {
from: grip.from,
to: grip.to,
});
})
});
let resized = settle(&cx, |app| {
view.read(app)
.graphic
.is_some_and(|now| now.2 < frame.2 && now.3 < frame.3)
});
assert!(resized, "the kernel resized the image");
}
+90
View File
@@ -0,0 +1,90 @@
use super::*;
#[test]
fn a_fitted_slide_fills_the_viewport_centred() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let deck = crate::client::tests::show::DECK;
let (view, _) = live_view_of(app, &install, "deck.fodp", deck);
view.update(app, |view, cx| {
view.fit_page(cx);
let bounds = Bounds {
origin: point(px(10.0), px(20.0)),
size: size(px(800.0), px(600.0)),
};
view.prepare(bounds);
let (w, h) = view.doc_size;
let want = (800.0 * 15.0 / w as f32).min(600.0 * 15.0 / h as f32) * 0.94;
assert!(
(view.geom.zoom - want).abs() < 0.001,
"{} vs {want}",
view.geom.zoom
);
assert!(
view.spare.0 > 0.0 && view.spare.1 > 0.0,
"centred: {:?}",
view.spare
);
let corner = view.window_point((0, 0));
assert_eq!(view.doc_point(corner), (0, 0), "points map both ways");
// A cursor far out must not move a fitted page.
view.reach = (w * 3, h * 3);
view.prepare(bounds);
assert_eq!(view.window_point((0, 0)), corner, "the page stays put");
let far = view.window_point((w, h));
assert!(
f32::from(far.y) < 620.0 && f32::from(far.x) < 810.0,
"the page fits"
);
});
});
}
#[test]
fn a_resized_slide_reaches_the_view_and_still_fits() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
let view = cx.update(|app| {
let deck = crate::client::tests::show::DECK;
live_view_of(app, &install, "deck.fodp", deck).0
});
cx.update(|app| {
view.update(app, |view, cx| {
view.fit_page(cx);
view.run("slide.size", &["300000", "300000", "true"])
.expect("sent");
})
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while cx.update(|app| view.read(app).doc_size.0 < 100_000) {
assert!(
std::time::Instant::now() < deadline,
"the view never read the new size"
);
if !cx.executor().tick() {
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
cx.update(|app| {
view.update(app, |view, _| {
let bounds = Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(800.0), px(600.0)),
};
view.prepare(bounds);
let (w, h) = view.doc_size;
let far = view.window_point((w, h));
assert!(
f32::from(far.x) <= 800.0 && f32::from(far.y) <= 600.0,
"a 3 m page fits: {far:?}"
);
})
});
}
+271
View File
@@ -0,0 +1,271 @@
use super::*;
use crate::client::tests::input::paragraphs;
use ely_platform::clipboard::{self, Clip};
use gpui::{InputHandler, Keystroke, TestAppContext, Window};
/// Steps the scheduler so queued input reaches LOK.
fn flush(cx: &TestAppContext) {
for _ in 0..80 {
cx.executor().tick();
}
}
/// The document's paragraphs, saved through the shared worker.
fn saved(view: &Entity<LokView>, cx: &mut TestAppContext) -> Vec<String> {
let out = tempfile::tempdir()
.expect("a temp dir")
.keep()
.join("out.fodt");
cx.update(|app| {
let view = view.read(app);
let mut worker = view.worker.lock().expect("the worker lock");
view.doc
.save_as(&mut worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
});
paragraphs(&std::fs::read_to_string(&out).expect("the save reads"))
}
fn typed(key: &str) -> Keystroke {
let mut stroke = Keystroke::parse(key).expect("a keystroke");
stroke.key_char = Some(key.to_string());
stroke
}
#[test]
fn typing_and_composing_reach_the_document() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
cx.update(|app| {
view.update(app, |view, _| {
assert!(!view.key_down(&typed("a")), "text waits for the IME");
view.commit(None, "ab");
view.compose(None, "n", None);
view.compose(None, "ni", None);
view.compose(None, "你", None);
assert_eq!(view.marked.as_ref().map(|m| m.text.as_str()), Some("你"));
view.commit(None, "你");
assert!(view.marked.is_none());
view.compose(None, "x", None);
view.compose(None, "", None);
assert!(view.marked.is_none(), "an empty composition cancels");
assert!(view.key_down(&Keystroke::parse("enter").expect("enter")));
})
});
flush(&cx);
assert_eq!(saved(&view, &mut cx), ["ab你", "Hello 世界"]);
}
struct Blank;
impl gpui::Render for Blank {
fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl gpui::IntoElement {
gpui::Empty
}
}
#[test]
fn the_platform_ime_callbacks_compose_in_utf16() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
let window = cx.add_window(|_, _| Blank);
cx.update_window(window.into(), |_, window, app| {
let bounds = Bounds::default();
let mut ime = gpui::ElementInputHandler::new(bounds, view.clone());
ime.replace_and_mark_text_in_range(None, "nihao", Some(2..2), window, app);
let selected = ime
.selected_text_range(false, window, app)
.expect("a selection");
assert_eq!(selected.range, 2..2, "the IME caret sits inside");
let mut adjusted = None;
let head = ime.text_for_range(0..2, &mut adjusted, window, app);
assert_eq!(head.as_deref(), Some("ni"));
assert_eq!(adjusted, Some(0..2));
assert_eq!(ime.marked_text_range(window, app), Some(0..5));
ime.replace_and_mark_text_in_range(Some(0..2), "你", Some(1..1), window, app);
let marked = view.read(app).marked.as_ref().map(|m| m.text.clone());
assert_eq!(marked.as_deref(), Some("你hao"));
let selected = ime.selected_text_range(false, window, app).map(|s| s.range);
assert_eq!(selected, Some(1..1));
ime.replace_text_in_range(Some(1..4), "好", window, app);
assert_eq!(
ime.marked_text_range(window, app),
None,
"the commit ends it"
);
ime.replace_and_mark_text_in_range(None, "x", None, window, app);
ime.unmark_text(window, app);
})
.expect("the window lives");
flush(&cx);
assert_eq!(saved(&view, &mut cx), ["你好xHello 世界"]);
}
#[test]
fn a_cut_keeps_the_text_when_the_clipboard_fails() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = TestAppContext::single();
let (view, shared) = cx.update(|app| live_view(app, &install));
let doc = cx.update(|app| view.read(app).doc.clone());
{
let mut worker = shared.lock().expect("the worker lock");
worker
.run(&doc, "edit.select_all", &[])
.expect("select all");
let failed = crate::view::clip::copy_out(&mut worker, &doc, true, |_| {
Err(std::io::Error::other("the clipboard refused"))
});
assert!(failed.is_err(), "the write failure surfaces");
assert!(
!worker.copy(&doc).expect("copy runs").is_empty(),
"the selection stays"
);
}
assert_eq!(saved(&view, &mut cx), ["Hello 世界"], "the text stays");
}
#[test]
fn a_drag_selects_and_events_carry_the_cursor() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
cx.update(|app| {
view.update(app, |view, _| {
let none = gpui::Modifiers::default();
let y = px(view.geom.px_of(1500));
view.mouse(0, point(px(view.geom.px_of(1500)), y), 1, 1, &none);
view.mouse(2, point(px(view.geom.px_of(4000)), y), 1, 1, &none);
view.mouse(1, point(px(view.geom.px_of(4000)), y), 1, 1, &none);
})
});
let mut selected = false;
for _ in 0..40 {
flush(&cx);
selected = cx.update(|app| !view.read(app).selection.is_empty());
if selected {
break;
}
}
assert!(selected, "the drag selection reaches the view");
cx.update(|app| {
let view = view.read(app);
let bounds = view.cursor_bounds().expect("the cursor arrived");
assert!(bounds.size.height > px(0.0), "the caret has height");
});
}
#[test]
fn a_dead_document_surfaces_an_error() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, shared) = cx.update(|app| live_view(app, &install));
let errors = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
cx.update(|app| {
let errors = errors.clone();
app.subscribe(&view, move |_, error: &LokError, _| {
errors.borrow_mut().push(error.0.clone())
})
.detach();
let doc = view.read(app).doc.clone();
shared
.lock()
.expect("the worker lock")
.close_doc(doc)
.expect("the doc closes");
view.update(app, |view, _| {
view.key_down(&Keystroke::parse("enter").expect("enter"));
});
});
flush(&cx);
let errors = errors.borrow();
assert!(
errors
.iter()
.any(|error| error.contains("no such document")),
"the failure reaches subscribers: {errors:?}"
);
}
#[test]
fn the_clipboard_moves_html_tables_and_images() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
if std::env::var_os("ELY_CLIPBOARD_TEST").is_none() {
eprintln!("SKIP: set ELY_CLIPBOARD_TEST=1; this replaces the clipboard");
return;
}
let mut cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
let primary = if cfg!(target_os = "macos") {
"cmd-a"
} else {
"ctrl-a"
};
cx.update(|app| {
view.update(app, |view, _| {
view.key_down(&Keystroke::parse(primary).expect("select all"));
view.send(crate::view::input::Input::Copy { cut: false });
})
});
flush(&cx);
let Some(Clip::Html { html, text }) = clipboard::read().expect("the clipboard reads") else {
panic!("the copy lands as html");
};
assert!(
html.contains("Hello") && text == "Hello 世界",
"{html} / {text}"
);
clipboard::write(&Clip::Html {
html: "<table><tr><td>left</td><td>right</td></tr></table>".into(),
text: "left\tright".into(),
})
.expect("the table writes");
cx.update(|app| view.update(app, |view, _| view.send(crate::view::input::Input::Paste)));
flush(&cx);
let text = saved(&view, &mut cx);
assert!(
text.contains(&"left".to_string()) && text.contains(&"right".to_string()),
"{text:?}"
);
let mut png = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("the png encodes");
clipboard::write(&Clip::Png(png)).expect("the image writes");
cx.update(|app| view.update(app, |view, _| view.send(crate::view::input::Input::Paste)));
flush(&cx);
let out = tempfile::tempdir()
.expect("a temp dir")
.keep()
.join("img.fodt");
cx.update(|app| {
let view = view.read(app);
let mut worker = view.worker.lock().expect("the worker lock");
view.doc
.save_as(&mut worker, &format!("file://{}", out.display()), "fodt")
.expect("the save works");
});
let xml = std::fs::read_to_string(&out).expect("the save reads");
assert!(xml.contains("<draw:image"), "the image lands");
}
+62
View File
@@ -0,0 +1,62 @@
use super::*;
/// A sheet whose last value sits 100,000 rows down.
const TALL: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S">
<table:table-row><table:table-cell><text:p>top</text:p></table:table-cell></table:table-row>
<table:table-row table:number-rows-repeated="99998"><table:table-cell/></table:table-row>
<table:table-row><table:table-cell><text:p>bottom</text:p></table:table-cell></table:table-row>
</table:table></office:spreadsheet></office:body>
</office:document>"#;
#[test]
fn a_tall_sheet_paints_and_keeps_only_tiles_near_the_screen() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view_of(app, &install, "tall.fods", TALL);
view.update(app, |view, cx| {
let bounds = Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(800.0), px(600.0)),
};
let side = view.geom.tile_pixels() as usize;
let painted = |generation| {
Ok(crate::Tile {
generation,
pixels: vec![0u8; side * side * 4],
})
};
// 800 by 600 needs 5 by 4 tiles.
view.prepare(bounds);
let top = view.on_screen.clone();
assert!(!top.is_empty() && top.len() <= 20, "{} tiles", top.len());
for key in &top {
view.finish_tile(*key, view.geom, painted(view.generation), cx);
}
assert_eq!(view.tile_count(), top.len(), "the top paints");
view.scroll_by(0.0, -3.0e6, cx);
view.prepare(bounds);
let bottom = view.on_screen.clone();
assert!(bottom.len() <= 20, "{} tiles at the bottom", bottom.len());
assert!(
bottom.iter().all(|key| key.1 > 1000),
"far down: {bottom:?}"
);
assert!(
top.iter().all(|key| !view.tiles.contains_key(key)),
"the top's tiles are gone"
);
assert!(
view.fetching.len() <= 20 + top.len(),
"only shown tiles fetch"
);
});
});
}
+97
View File
@@ -0,0 +1,97 @@
use super::*;
use gpui::TestAppContext;
/// Steps the scheduler until `done` or ten seconds pass.
fn settle(cx: &TestAppContext, done: impl Fn(&App) -> bool) -> bool {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while std::time::Instant::now() < deadline {
if !cx.executor().tick() {
cx.executor()
.advance_clock(std::time::Duration::from_millis(20));
}
if cx.update(|app| done(app)) {
return true;
}
}
false
}
/// The view's 800 by 600 pixel area.
fn area() -> Bounds<Pixels> {
Bounds {
origin: point(px(0.0), px(0.0)),
size: size(px(800.0), px(600.0)),
}
}
#[test]
fn the_view_paints_the_app_theme_and_back() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, worker) = cx.update(|app| live_view(app, &install));
let doc = cx.update(|app| view.read(app).doc.clone());
let mut shades = Vec::new();
for dark in [true, false] {
cx.update(|app| view.update(app, |view, _| view.follow_theme(dark)));
assert!(
settle(&cx, |app| view.read(app).settled()),
"the theme goes out"
);
let mut worker = worker.lock().expect("the worker");
let tile = doc
.paint_tile(&mut worker, (1440, 1440, 3840, 3840), (64, 64))
.expect("a tile");
let sum: u64 = tile
.pixels
.chunks_exact(4)
.map(|px| u64::from(px[0]) + u64::from(px[1]) + u64::from(px[2]))
.sum();
shades.push(sum / (64 * 64 * 3));
}
assert!(
shades[0] < 100 && shades[1] > 200,
"dark then light: {shades:?}"
);
}
#[test]
fn a_failed_tile_reports_and_retries_on_a_move() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = TestAppContext::single();
let (view, _) = cx.update(|app| live_view(app, &install));
let errors = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
cx.update(|app| {
let errors = errors.clone();
app.subscribe(&view, move |_, error: &LokError, _| {
errors.borrow_mut().push(error.0.clone())
})
.detach();
view.update(app, |view, cx| {
let geom = view.geom;
view.prepare(area());
view.fetching.remove(&(0, 0));
view.finish_tile((0, 0), geom, Err(io::Error::other("no paint")), cx);
assert!(view.failed.contains(&((0, 0), view.generation)));
view.prepare(area());
assert!(!view.fetching.contains(&(0, 0)), "no retry storm in place");
view.scroll_by(0.0, -40.0, cx);
view.prepare(area());
assert!(view.fetching.contains(&(0, 0)), "a move retries the tile");
});
});
assert!(
settle(&cx, |_| !errors.borrow().is_empty()),
"the failure reaches the app"
);
assert!(
errors.borrow()[0].contains("no paint"),
"{:?}",
errors.borrow()
);
}
+82
View File
@@ -0,0 +1,82 @@
//! Zooming the page view about the pointer (LOK-04).
use gpui::{Context, EventEmitter, PinchEvent, Pixels, Point, ScrollDelta, ScrollWheelEvent, Window};
use super::LokView;
/// The zoom changed, by key, wheel or pinch.
pub struct Zoomed;
impl EventEmitter<Zoomed> for LokView {}
/// The steps of zooming in and out.
pub const ZOOM_STEPS: [f32; 10] = [0.25, 0.5, 0.67, 0.8, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0];
const LEAST: f32 = 0.25;
const MOST: f32 = 4.0;
impl LokView {
/// The zoom now; 1.0 is the page's actual size.
pub fn zoom(&self) -> f32 {
self.geom.zoom
}
/// Whether the zoom follows the viewport (a whole page).
pub fn fitting(&self) -> bool {
self.fit
}
/// Sets the zoom; the grid is repainted (LOK-04).
pub fn set_zoom(&mut self, zoom: f32, cx: &mut Context<Self>) {
self.zoom_at(zoom, None, cx);
}
/// The next step in or out from the zoom now.
pub fn zoom_step(&mut self, larger: bool, cx: &mut Context<Self>) {
let now = self.geom.zoom;
let next = match larger {
true => ZOOM_STEPS.into_iter().find(|step| *step > now + 0.001).unwrap_or(MOST),
false => ZOOM_STEPS.into_iter().rev().find(|step| *step < now - 0.001).unwrap_or(LEAST),
};
self.zoom_at(next, None, cx);
}
/// Zooms keeping `at` (window pixels) still; none keeps the middle.
pub fn zoom_at(&mut self, zoom: f32, at: Option<Point<Pixels>>, cx: &mut Context<Self>) {
let zoom = zoom.clamp(LEAST, MOST);
let (ax, ay) = match at {
Some(at) => (f32::from(at.x - self.origin.x), f32::from(at.y - self.origin.y)),
None => (self.viewport.0 / 2.0, self.viewport.1 / 2.0),
};
let under = (self.scroll.0 + self.geom.twips_of(ax), self.scroll.1 + self.geom.twips_of(ay));
self.fit = false;
if (zoom - self.geom.zoom).abs() > 0.0001 {
self.geom.zoom = zoom;
self.retire_tiles();
self.failed.clear();
}
self.scroll = (under.0 - self.geom.twips_of(ax), under.1 - self.geom.twips_of(ay));
self.clamp_scroll();
log::debug!("lok: zoom {:.0}%", zoom * 100.0);
cx.emit(Zoomed);
cx.notify();
}
/// Command with the wheel zooms; otherwise it scrolls.
pub(super) fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
if !event.modifiers.platform {
return self.on_scroll(event, window, cx);
}
let dy = match event.delta {
ScrollDelta::Pixels(point) => f32::from(point.y),
ScrollDelta::Lines(point) => point.y * 40.0,
};
let zoom = self.geom.zoom * (dy / 200.0).exp();
self.zoom_at(zoom, Some(event.position), cx);
}
/// A trackpad pinch zooms about its centre.
pub(super) fn on_pinch(&mut self, event: &PinchEvent, _: &mut Window, cx: &mut Context<Self>) {
let zoom = self.geom.zoom * (1.0 + event.delta);
self.zoom_at(zoom, Some(event.position), cx);
}
}
+469
View File
@@ -0,0 +1,469 @@
use std::{
io::{self, Write},
path::Path,
sync::Mutex,
};
use crate::ffi::{Document, Lok};
use crate::ipc::{self, Pack, Unpack, tag};
mod events;
#[cfg(unix)]
mod fatal;
mod input;
mod password;
mod revision;
mod slides;
mod teardown;
mod text;
/// English kernel, desktop hints; macros stay off (LOK-11).
const LOAD_OPTIONS: &str = "Language=en-US,DeviceFormFactor=desktop";
/// The worker's whole life: init, serve frames, die on shutdown.
pub fn run(
install: &str,
profile_dir: &str,
input: impl io::Read + Send + 'static,
output: impl Write + Send + 'static,
) -> io::Result<()> {
set_output(Box::new(output));
let profile_dir = std::fs::canonicalize(profile_dir)?;
let profile_url = profile_url_of(&profile_dir);
let _ = teardown::PROFILE.set(profile_dir.clone());
let lok = Lok::hook(Path::new(install), &profile_url)?;
#[cfg(unix)]
fatal::watch();
log::info!("lok-worker: up, profile {}", profile_dir.display());
serve(lok, input)
}
#[cfg(target_os = "macos")]
fn serve(lok: Lok, input: impl io::Read + Send + 'static) -> io::Result<()> {
let lok = Box::leak(Box::new(lok));
pin(lok);
lok.register_callback(password::on_kit);
lok.register_any_input(waiting);
unsafe {
gcd::dispatch_async_f(gcd::main_queue(), std::ptr::null_mut(), mark_pumping);
}
std::thread::spawn(move || reader(input));
std::thread::spawn(events::push);
lok.run_loop();
Ok(())
}
/// Requests queued for the main thread and not yet answered.
#[cfg(target_os = "macos")]
static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// Lets idle jobs yield to a waiting request.
#[cfg(target_os = "macos")]
extern "C" fn waiting(_: *mut std::ffi::c_void, _: i32) -> bool {
PENDING.load(std::sync::atomic::Ordering::SeqCst) > 0
}
/// The queue's first drained block.
#[cfg(target_os = "macos")]
extern "C" fn mark_pumping(_: *mut std::ffi::c_void) {
PUMPING.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Set once the main queue drains its first block.
#[cfg(target_os = "macos")]
static PUMPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The queue's last drained block.
#[cfg(target_os = "macos")]
extern "C" fn quit_block(_: *mut std::ffi::c_void) {
log::info!("lok-worker: quit on drained queue");
teardown::teardown(0);
}
#[cfg(target_os = "macos")]
fn reader(mut input: impl io::Read) {
while !PUMPING.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::yield_now();
}
loop {
match ipc::read_frame(&mut input) {
Ok(Some((tag, id, payload))) => {
let request = Box::into_raw(Box::new((tag, id, payload)));
PENDING.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
unsafe {
gcd::dispatch_async_f(gcd::main_queue(), request.cast(), handle);
}
if tag == tag::SHUTDOWN {
return;
}
}
Ok(None) => {
log::info!("lok-worker: stdin closed");
unsafe {
gcd::dispatch_async_f(gcd::main_queue(), std::ptr::null_mut(), quit_block);
}
return;
}
Err(error) => {
log::warn!("lok-worker: frame read failed: {error}");
quit(1);
}
}
}
}
#[cfg(target_os = "macos")]
extern "C" fn handle(context: *mut std::ffi::c_void) {
let (tag, id, payload) = *unsafe { Box::from_raw(context.cast::<(u8, u64, Vec<u8>)>()) };
let lok = unsafe { &*LOK.load(std::sync::atomic::Ordering::SeqCst) };
PENDING.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
answer(lok, tag, id, &payload);
}
/// The pinned kit, for callbacks.
fn lok() -> &'static Lok {
unsafe { &*LOK.load(std::sync::atomic::Ordering::SeqCst) }
}
static LOK: std::sync::atomic::AtomicPtr<Lok> =
std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
#[cfg(target_os = "macos")]
mod gcd {
use std::ffi::c_void;
unsafe extern "C" {
static _dispatch_main_q: c_void;
pub fn dispatch_async_f(
queue: *mut c_void,
context: *mut c_void,
work: extern "C" fn(*mut c_void),
);
}
/// The main queue: the header's macro target.
pub fn main_queue() -> *mut c_void {
unsafe { &_raw as *const c_void as *mut c_void }
}
use _dispatch_main_q as _raw;
}
#[cfg(not(target_os = "macos"))]
fn serve(lok: Lok, mut input: impl io::Read) -> io::Result<()> {
let lok = Box::leak(Box::new(lok));
pin(lok);
lok.register_callback(password::on_kit);
std::thread::spawn(events::push);
loop {
match ipc::read_frame(&mut input)? {
Some((tag, id, payload)) => answer(lok, tag, id, &payload),
None => {
log::info!("lok-worker: stdin closed");
teardown::teardown(0);
}
}
}
}
/// Handles one frame and writes its answer.
fn answer(lok: &Lok, tag: u8, id: u64, payload: &[u8]) {
let out = OUT.get().expect("the output is set");
let mut out = out.lock().expect("the output lock");
if tag == tag::SHUTDOWN {
let outcome = teardown::teardown_work();
let (reply_tag, body) = match &outcome {
Ok(()) => (tag::OK, Vec::new()),
Err(error) => (tag::ERR, Pack::new().str(&error.to_string()).bytes()),
};
let _ = ipc::write_frame(&mut *out, reply_tag, id, &body);
log::info!("lok-worker: shutdown");
quit(if outcome.is_ok() { 0 } else { 1 });
}
// Bumped first: events it causes carry the new revision.
revision::bump(tag, payload);
let mut unpack = Unpack::new(payload);
let unpack = &mut unpack;
let outcome = match tag {
tag::BUILD_ID => Ok(Pack::new().str(&lok.build_id()).bytes()),
tag::LOAD => unpack
.str()
.and_then(|url| Ok((url, unpack.str()?)))
.and_then(|(url, password)| load(lok, &url, password, ""))
.map(|id| Pack::new().u64(id).bytes()),
tag::IMPORT => text::import(lok, unpack).map(|id| Pack::new().u64(id).bytes()),
tag::EXPORT_TEXT => text::export(unpack).map(|()| Vec::new()),
tag::DOC_SIZE => unpack
.u64()
.and_then(|id| with_doc(id, |doc| doc.size()))
.map(|(width, height)| Pack::new().i64(width).i64(height).bytes()),
tag::SAVE_AS => save(unpack).map(|()| Vec::new()),
tag::EXPORT_PDF => export_pdf(unpack).map(|()| Vec::new()),
tag::CLOSE_DOC => unpack.u64().map(|id| {
close(id);
Vec::new()
}),
tag::EXPECT => revision::expect(unpack),
tag::REVISION => revision::current(unpack),
tag::PAINT_TILE => input::painted(unpack),
tag::PAINT_PART => input::part_painted(unpack),
tag::SLIDE_LAYERS => slides::slide_layers(unpack),
tag::VERIFY => unpack
.str()
.and_then(|url| verify(lok, &url))
.map(|count| Pack::new().u64(count).bytes()),
tag::RUN_MACRO => unpack.str().and_then(|url| {
if dev_mode() && cfg!(debug_assertions) {
Ok(Pack::new().u64(lok.run_macro(&url) as u64).bytes())
} else {
Err(io::Error::other("run_macro is a dev-only probe"))
}
}),
tag::POST_KEY => input::key(unpack),
tag::POST_MOUSE => input::mouse(unpack),
tag::GRAPHIC => input::graphic(unpack),
tag::POST_TEXT => input::text(unpack),
tag::POST_UNO => input::uno(unpack),
tag::COPY => input::copy(unpack),
tag::PASTE => input::paste(unpack),
tag::CUT => input::cut(unpack),
tag::VALUES => input::values(unpack),
tag::PAGES => unpack
.u64()
.and_then(|id| with_doc(id, |doc| doc.page_rects()))
.and_then(|rects| rects)
.map(|rects| Pack::new().str(&rects).bytes()),
tag::SHEETS => unpack
.u64()
.and_then(|id| with_doc(id, sheets))
.and_then(|sheets| sheets),
tag::SHOW_SHEET => unpack
.u64()
.and_then(|id| Ok((id, unpack.u64()?)))
.and_then(|(id, part)| {
let part = i32::try_from(part).map_err(io::Error::other)?;
with_doc(id, |doc| doc.set_part(part))
})
.map(|()| Vec::new()),
tag::VISIBLE_AREA => unpack
.u64()
.and_then(|id| {
let mut number = || i32::try_from(unpack.i64()?).map_err(io::Error::other);
Ok((id, (number()?, number()?, number()?, number()?)))
})
.and_then(|(id, (x, y, w, h))| with_doc(id, |doc| doc.set_visible_area(x, y, w, h)))
.map(|()| Vec::new()),
tag::SELECTION_TEXT => unpack
.u64()
.and_then(|id| with_doc(id, |doc| doc.selection_text()))
.and_then(|text| text)
.map(|text| Pack::new().str(&text).bytes()),
tag::COMPLETE_FUNCTION => unpack
.u64()
.and_then(|id| {
let name = unpack.str()?;
with_doc(id, |doc| doc.complete_function(&name)).and_then(|done| done)
})
.map(|()| Vec::new()),
tag::SET_AUTHOR => unpack
.str()
.and_then(|name| lok.set_option("author", &name))
.map(|()| Vec::new()),
other => Err(io::Error::other(format!("unknown request {other}"))),
};
let reply = match outcome {
Ok(body) => (tag::OK, body),
Err(error) => {
// Text may quote the document: reply, never log.
log::warn!("lok-worker: request {tag} failed ({:?})", error.kind());
(tag::ERR, Pack::new().str(&error.to_string()).bytes())
}
};
let mut written = ipc::write_frame(&mut *out, reply.0, id, &reply.1);
// An oversized answer is refused; the worker lives.
if let Err(error) = &written
&& error.kind() == io::ErrorKind::InvalidInput
{
log::warn!("lok-worker: request {tag}: {error}");
written = ipc::write_frame(&mut *out, tag::ERR, id, &Pack::new().str(&error.to_string()).bytes());
}
if let Err(error) = written {
log::warn!("lok-worker: frame write failed: {error}");
quit(1);
}
}
/// Whether the dev-only probes answer (a `--dev` argv flag only).
fn dev_mode() -> bool {
static DEV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*DEV.get_or_init(|| std::env::args().any(|arg| arg == "--dev"))
}
/// Loads a document with macros disabled (LOK-11).
fn load(lok: &Lok, url: &str, password: String, filter: &str) -> io::Result<u64> {
if password.contains('\0') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"a password with NUL",
));
}
password::arm(Some(password).filter(|password| !password.is_empty()));
// LOK hands what it does not take to the filter.
let options = match filter {
"" => LOAD_OPTIONS.to_owned(),
filter => format!("{LOAD_OPTIONS},{filter}"),
};
let loaded = lok.load(url, &options);
let refused = password::refused();
password::arm(None);
let doc = match loaded {
Err(_) if refused => return Err(io::Error::other(ipc::LOCKED)),
loaded => loaded?,
};
// A session number per load; native pointers get reused.
let id = revision::session();
crate::events::watch(id, &doc);
doc.enable_a11y();
crate::events::seed_a11y(id, &doc.a11y_paragraph()?);
// Settle the initial layout now; later paints see it (LOK-03).
doc.post_uno(".uno:Repaginate", None)?;
let mut docs = docs().lock().expect("the docs lock");
docs.insert(id, doc);
log::info!("lok-worker: {} documents open", docs.len());
drop(docs);
log::info!("lok-worker: loaded {url}, filter options {filter:?}");
Ok(id)
}
/// Stops watching and frees document `id`.
fn close(id: u64) {
let mut docs = docs().lock().expect("the docs lock");
if let Some(doc) = docs.get(&id) {
crate::events::unwatch(id, doc);
}
docs.remove(&id);
revision::forget(id);
log::info!("lok-worker: {} documents open", docs.len());
}
/// The live documents, freed on CLOSE_DOC.
fn docs() -> &'static Mutex<std::collections::HashMap<u64, Document>> {
static DOCS: std::sync::OnceLock<Mutex<std::collections::HashMap<u64, Document>>> =
std::sync::OnceLock::new();
DOCS.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
}
/// Loads and paints; the bytes gained (R-01).
fn verify(lok: &Lok, url: &str) -> io::Result<u64> {
let doc = lok.load(url, LOAD_OPTIONS)?;
let mut tile = vec![0xABu8; 64 * 64 * 4];
doc.paint_tile(&mut tile, 64, 64);
drop(doc);
let gained = tile.iter().filter(|byte| **byte != 0xAB).count() as u64;
log::info!("lok-worker: tile self-check gained {gained} bytes");
Ok(gained)
}
/// Borrows a live document for a read call.
fn with_doc<T>(id: u64, call: impl FnOnce(&Document) -> T) -> io::Result<T> {
let docs = docs().lock().expect("the docs lock");
let Some(doc) = docs.get(&id) else {
return Err(io::Error::new(io::ErrorKind::NotFound, "no such document"));
};
// Calc reads the current view; every request uses its own.
doc.activate();
Ok(call(doc))
}
/// The shown part, then each part's name and info.
fn sheets(doc: &Document) -> io::Result<Vec<u8>> {
let count = doc.parts();
let mut pack = Pack::new().u64(doc.part() as u64).u64(count as u64);
for part in 0..count {
pack = pack.str(&doc.part_name(part)?).str(&doc.part_info(part)?);
}
Ok(pack.bytes())
}
/// Saves a document under a new url and format (LOK-09).
fn save(unpack: &mut Unpack) -> io::Result<()> {
let id = unpack.u64()?;
let url = unpack.str()?;
let format = unpack.str()?;
let options = unpack.str()?;
if !options.is_empty() && options != "TakeOwnership" {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"unknown save option",
));
}
with_doc(id, |doc| doc.save_as(&url, &format, &options))??;
log::info!("lok-worker: saved as {format} to {url} ({options})");
Ok(())
}
/// Writes a PDF from typed options, never raw text.
fn export_pdf(unpack: &mut Unpack) -> io::Result<()> {
let (id, url) = (unpack.u64()?, unpack.str()?);
let (from, to) = (unpack.u64()?, unpack.u64()?);
let (comments, changes) = (unpack.u64()? != 0, unpack.u64()? != 0);
let handouts = unpack.u64()?;
let flag = |on: bool| serde_json::json!({ "type": "boolean", "value": on.to_string() });
let mut options = serde_json::json!({
"ExportNotes": flag(false),
"ExportNotesInMargin": flag(comments),
"ExportTrackedChanges": flag(changes),
});
if handouts != 0 {
let per = handouts.to_string();
options["ExportHandouts"] = serde_json::json!({ "type": "long", "value": per });
}
if from != 0 {
if from > to {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"a page range ends first",
));
}
let range = format!("{from}-{to}");
options["PageRange"] = serde_json::json!({ "type": "string", "value": range });
}
with_doc(id, |doc| doc.save_as(&url, "pdf", &options.to_string()))??;
log::info!(
"lok-worker: exported PDF pages {from}-{to}, comments {comments}, changes {changes}, handouts {handouts}"
);
Ok(())
}
/// The one shared output for every handler.
static OUT: std::sync::OnceLock<Mutex<Box<dyn Write + Send>>> = std::sync::OnceLock::new();
/// Sets the response sink once.
pub fn set_output(out: Box<dyn Write + Send>) {
let _ = OUT.set(Mutex::new(out));
}
/// Sets the kit for the handlers once.
fn pin(lok: &'static Lok) {
LOK.store(
lok as *const Lok as *mut Lok,
std::sync::atomic::Ordering::SeqCst,
);
}
/// The profile directory as a `file:` URL.
fn profile_url_of(dir: &Path) -> String {
ipc::file_url_of(dir)
}
/// Exits without LO's atexit handlers (R-01's probe does the same).
#[cfg(unix)]
fn quit(code: i32) -> ! {
unsafe { libc::_exit(code) };
}
/// Exits without LO's atexit handlers, the msvcrt way.
#[cfg(windows)]
fn quit(code: i32) -> ! {
unsafe extern "C" {
fn _exit(code: i32) -> !;
}
unsafe { _exit(code) };
}
+86
View File
@@ -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()
}
+28
View File
@@ -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) };
}
}
+447
View File
@@ -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());
}
}
+45
View File
@@ -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());
}
+73
View File
@@ -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)
}
+37
View File
@@ -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())
})?
}
Loaded 100 of 817 files, more files were not shown because too many files have changed in this diff. Show more