LOK runs on Windows and Linux; packaging stages engines (W-01, K-01)
The kernel is the merged library on every platform; Windows and Linux find it beside the app in libreoffice/program. All three run unipoll: macOS through GCD, Linux by answering one request per poll, Windows through a message-only window on the loop's thread (LOK's own main thread had deadlocked Calc loads). Patch 0043 flushes callbacks inline everywhere, so a request sees its result; 0042 stops MSVC's Boost auto-link. Linux paints with cairo, BGRA; the start-up check now paints red text and finds red in byte two on every platform, since getTileMode does not see Skia. ely-lok on Windows: 180 of 189 pass; on Linux 187. The rest are listed after 0.1.3 (spelling, Calc dark tiles, show layers and fields, a11y selection). Tests build file URLs portably and accept CRLF where Windows writes it. packaging/stage.sh lays out an app with its engines for Windows and Linux; licenses.sh finds each licence on all three. ElyMark finds its page beside the app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc4c1ed0fe
commit
c96d39a342
34 files changed
+658
-214
No files matched your search
@@ -150,14 +150,14 @@ impl Worker {
|
||||
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",
|
||||
.env("SAL_FORCE_HIDPI_SCALING", "1");
|
||||
// Linux tiles via cairo are BGRA; Skia there is RGBA.
|
||||
match cfg!(target_os = "linux") {
|
||||
true => command.env("SAL_DISABLESKIA", "1"),
|
||||
false => command.env("SAL_SKIA", "raster"),
|
||||
};
|
||||
command.env("SAL_LOK_OPTIONS", options);
|
||||
// Calc reports in document twips; unipoll lends LOK's loop.
|
||||
command.env("SAL_LOK_OPTIONS", "unipoll:sc_print_twips_msgs");
|
||||
if dev {
|
||||
command.arg("--dev");
|
||||
}
|
||||
@@ -370,7 +370,9 @@ impl Worker {
|
||||
// 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)?;
|
||||
if let Err(error) = ipc::write_frame(&mut self.stdin, request, self.asked, payload) {
|
||||
return Err(self.broken(request, error));
|
||||
}
|
||||
let (reply, id, body) = match self.replies.recv() {
|
||||
Ok(Ok(frame)) => frame,
|
||||
Ok(Err(error)) => return Err(self.broken(request, error)),
|
||||
|
||||
@@ -22,6 +22,12 @@ pub fn templates(kind: &str) -> io::Result<Vec<PathBuf>> {
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// The kernel's folder beside the app, and in this build.
|
||||
#[cfg(target_os = "macos")]
|
||||
const LAYOUT: (&str, &str) = ("../Frameworks", "instdir/LibreOffice.app/Contents/Frameworks");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
const LAYOUT: (&str, &str) = ("libreoffice/program", "instdir/program");
|
||||
|
||||
/// 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") {
|
||||
@@ -35,17 +41,15 @@ pub fn install_dir() -> io::Result<PathBuf> {
|
||||
))
|
||||
};
|
||||
}
|
||||
let (beside, built) = LAYOUT;
|
||||
let library = crate::ffi::KERNEL;
|
||||
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()? {
|
||||
let bundled = exe.parent().unwrap_or(Path::new(".")).join(beside);
|
||||
if bundled.join(library).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()? {
|
||||
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../engines/lo-src").join(built);
|
||||
if dev.join(library).try_exists()? {
|
||||
return Ok(dev);
|
||||
}
|
||||
Err(io::Error::new(
|
||||
|
||||
@@ -157,20 +157,20 @@ fn the_worker_round_trips_a_document() {
|
||||
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let url = format!("file://{}", source.display());
|
||||
let url = crate::file_url(&source);
|
||||
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")
|
||||
doc.save_as(&mut worker, &crate::file_url(&odt), "odt")
|
||||
.expect("the odt save");
|
||||
assert!(odt.try_exists().expect("the odt exists"));
|
||||
let doc2 = worker
|
||||
.load(&format!("file://{}", odt.display()))
|
||||
.load(&crate::file_url(&odt))
|
||||
.expect("the odt reloads");
|
||||
let pdf = dir.path().join("note.pdf");
|
||||
doc2.save_as(&mut worker, &format!("file://{}", pdf.display()), "pdf")
|
||||
doc2.save_as(&mut worker, &crate::file_url(&pdf), "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");
|
||||
@@ -187,7 +187,7 @@ fn a_missing_file_is_an_error_never_a_success() {
|
||||
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()));
|
||||
let outcome = worker.load(&crate::file_url(&missing));
|
||||
assert!(outcome.is_err(), "LOK-09: the failure is an error");
|
||||
}
|
||||
|
||||
@@ -209,7 +209,12 @@ fn a_failed_check_refuses_every_later_request() {
|
||||
|
||||
/// Initializes the profile fully, the CLI way (registers Basic).
|
||||
fn seed_basic(install: &Path, profile: &Path) {
|
||||
#[cfg(target_os = "macos")]
|
||||
let soffice = install.parent().expect("the app dir").join("MacOS/soffice");
|
||||
#[cfg(target_os = "linux")]
|
||||
let soffice = install.join("soffice.bin");
|
||||
#[cfg(windows)]
|
||||
let soffice = install.join("soffice.exe");
|
||||
let url = ipc::file_url_of(profile);
|
||||
let status = std::process::Command::new(&soffice)
|
||||
.args(["--headless", "--norestore", "--terminate_after_init"])
|
||||
@@ -249,7 +254,7 @@ fn a_macro_never_writes_its_marker() {
|
||||
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()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the macro document loads");
|
||||
std::thread::sleep(std::time::Duration::from_millis(800));
|
||||
assert!(
|
||||
@@ -313,7 +318,7 @@ fn shutdown_leaves_no_locks_or_temp() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let lock = dir.path().join(".~lock.note.fodt#");
|
||||
worker.close_doc(doc).expect("the document closes");
|
||||
@@ -347,7 +352,7 @@ fn each_load_is_its_own_session() {
|
||||
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());
|
||||
let url = crate::file_url(&source);
|
||||
// Freed native documents reuse addresses; sessions never repeat.
|
||||
let mut old = Vec::new();
|
||||
for _ in 0..4 {
|
||||
@@ -375,7 +380,7 @@ fn a_document_belongs_to_its_worker() {
|
||||
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 url = crate::file_url(&source);
|
||||
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");
|
||||
|
||||
@@ -240,7 +240,7 @@ fn a_kernel_dialog_is_closed_and_reported() {
|
||||
let source = dir.path().join("in.fods");
|
||||
write(&source, FODS);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the sheet loads");
|
||||
let base = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
|
||||
// Calc's Backspace opens Delete Contents.
|
||||
@@ -436,7 +436,7 @@ fn an_owned_save_clears_the_modified_state() {
|
||||
state(seen, ".uno:ModifiedStatus") == Some("true")
|
||||
});
|
||||
let copy = dir.path().join("copy.docx");
|
||||
doc.save_owned(&mut worker, &format!("file://{}", copy.display()), "docx")
|
||||
doc.save_owned(&mut worker, &crate::file_url(©), "docx")
|
||||
.expect("the owned save");
|
||||
let saved = poll_until(&mut worker, &doc, &base, SETTLE, |seen| {
|
||||
state(seen, ".uno:ModifiedStatus") == Some("false")
|
||||
|
||||
@@ -12,7 +12,7 @@ fn open() -> (tempfile::TempDir, Worker, Doc, Events) {
|
||||
let source = dir.path().join("in.fods");
|
||||
write(&source, FODS);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the sheet loads");
|
||||
let seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |seen| {
|
||||
seen.cell.cursor.is_some()
|
||||
@@ -29,7 +29,8 @@ fn type_text(worker: &mut Worker, doc: &Doc, text: &str) {
|
||||
/// 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")
|
||||
// Windows ends copied lines with CRLF.
|
||||
doc.selection_text(worker).expect("the text").replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(super) fn open(body: &str) -> (tempfile::TempDir, Worker, Doc) {
|
||||
let source = dir.path().join("in.fodt");
|
||||
write(&source, body);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
(dir, worker, doc)
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub(super) fn open(body: &str) -> (tempfile::TempDir, 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")
|
||||
doc.save_as(worker, &crate::file_url(&out), "fodt")
|
||||
.expect("the save works");
|
||||
std::fs::read_to_string(&out).expect("the save reads")
|
||||
}
|
||||
@@ -210,7 +210,7 @@ fn copy_gives_text_and_html_and_paste_takes_html() {
|
||||
let target = dir.path().join("b.fodt");
|
||||
write(&target, FODT);
|
||||
let other = worker
|
||||
.load(&format!("file://{}", target.display()))
|
||||
.load(&crate::file_url(&target))
|
||||
.expect("b loads");
|
||||
click(&mut worker, &other, 150, 150);
|
||||
worker
|
||||
@@ -312,7 +312,7 @@ fn a_calc_cut_finishes_without_a_dialog() {
|
||||
let source = root.join("in.fods");
|
||||
write(&source, FODS);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the sheet loads");
|
||||
worker
|
||||
.post_key(&doc, 0, 1027 | 0x1000)
|
||||
@@ -320,7 +320,7 @@ fn a_calc_cut_finishes_without_a_dialog() {
|
||||
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")
|
||||
doc.save_as(&mut worker, &crate::file_url(&out), "fods")
|
||||
.expect("the save works");
|
||||
let xml = std::fs::read_to_string(&out).expect("the save reads");
|
||||
done.send((copied.len(), xml.contains("Hello")))
|
||||
@@ -367,7 +367,7 @@ fn a_table_survives_copy_and_paste() {
|
||||
let target = dir.path().join("b.fodt");
|
||||
write(&target, FODT);
|
||||
let other = worker
|
||||
.load(&format!("file://{}", target.display()))
|
||||
.load(&crate::file_url(&target))
|
||||
.expect("b loads");
|
||||
click(&mut worker, &other, 150, 150);
|
||||
worker
|
||||
|
||||
@@ -13,7 +13,7 @@ fn keys_never_wait_behind_the_event_watch() {
|
||||
let source = dir.path().join("in.fods");
|
||||
write(&source, FODS);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.unwrap();
|
||||
let feed = worker.feed();
|
||||
let shared = std::sync::Arc::new(std::sync::Mutex::new(worker));
|
||||
|
||||
@@ -44,8 +44,7 @@ fn a_locked_document_asks_for_its_password() {
|
||||
for password in ["", "wrong"] {
|
||||
let error = worker
|
||||
.unlock(&url, password)
|
||||
.err()
|
||||
.expect("a locked load fails");
|
||||
.expect_err("a locked load fails");
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
|
||||
@@ -16,7 +16,7 @@ fn a_tile_paints_real_pixels() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let tile = doc
|
||||
.paint_tile(&mut worker, (0, 0, 960, 960), (64, 64))
|
||||
@@ -51,7 +51,7 @@ fn an_edit_bumps_the_generation_and_invalidates() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
|
||||
let before = doc
|
||||
@@ -95,7 +95,7 @@ fn uno_commands_invalidate_and_repaint() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
|
||||
let before = doc
|
||||
@@ -137,7 +137,7 @@ fn a_red_span_paints_red_bytes() {
|
||||
let source = dir.path().join("red.html");
|
||||
write(&source, RED_HTML);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let tile = doc
|
||||
.paint_tile(&mut worker, (0, 0, 2000, 1000), (64, 64))
|
||||
@@ -162,12 +162,12 @@ fn a_key_press_edits_the_document() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.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")
|
||||
doc.save_as(&mut worker, &crate::file_url(&out), "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");
|
||||
@@ -187,7 +187,7 @@ fn selection_only_requests_keep_the_generation() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let base = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
|
||||
click(&mut worker, &doc, 150, 150);
|
||||
@@ -211,7 +211,7 @@ fn bad_tile_geometry_is_an_error_and_the_worker_lives() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
for (x, y, w, h, pw, ph) in [
|
||||
(0, 0, 0, 960, 64, 64),
|
||||
@@ -243,7 +243,7 @@ fn a_long_wait_is_clamped_and_requests_flow() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let started = std::time::Instant::now();
|
||||
let batch = worker
|
||||
@@ -270,7 +270,7 @@ fn polling_times_out_with_the_same_generation() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.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);
|
||||
@@ -291,16 +291,16 @@ fn uno_commands_reach_their_own_document() {
|
||||
write(&first, FODT);
|
||||
write(&second, FODT);
|
||||
let a = worker
|
||||
.load(&format!("file://{}", first.display()))
|
||||
.load(&crate::file_url(&first))
|
||||
.expect("a loads");
|
||||
let b = worker
|
||||
.load(&format!("file://{}", second.display()))
|
||||
.load(&crate::file_url(&second))
|
||||
.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")
|
||||
doc.save_as(worker, &crate::file_url(&out), "fodt")
|
||||
.expect("the save works");
|
||||
std::fs::read_to_string(&out).expect("the save reads")
|
||||
};
|
||||
@@ -327,7 +327,7 @@ fn writer_reports_its_page_rects() {
|
||||
let source = dir.path().join("note.fodt");
|
||||
write(&source, FODT);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let pages = doc.pages(&mut worker).expect("the page rects");
|
||||
let (width, height) = doc.size(&mut worker).expect("the size");
|
||||
@@ -361,7 +361,7 @@ fn the_page_follows_a_dark_theme_and_back() {
|
||||
let source = dir.path().join(name);
|
||||
write(&source, text);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
let area = (1440, 1440, 3840, 3840);
|
||||
let seen = poll_until(&mut worker, &doc, &Events::default(), QUIET, |_| false);
|
||||
|
||||
@@ -154,12 +154,13 @@ fn text_exports_write_the_shown_sheet_as_values() {
|
||||
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");
|
||||
// Windows writes CSV lines with CRLF, as RFC 4180 does.
|
||||
let first = std::fs::read_to_string(&out).expect("reads").replace("\r\n", "\n");
|
||||
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");
|
||||
let second = std::fs::read_to_string(&out).expect("reads").replace("\r\n", "\n");
|
||||
assert_eq!(second, "Item;Note\nPen;\"a;b\"\nInk;2\n", "only S2");
|
||||
}
|
||||
|
||||
@@ -284,11 +285,16 @@ fn excel_caches_recompute_and_unknown_functions_show_errors() {
|
||||
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")
|
||||
// Python's zipfile, as ooxml.py uses: no zip on Windows.
|
||||
let pack = "import os, sys, zipfile
|
||||
with zipfile.ZipFile(sys.argv[1], 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
for d, _, fs in os.walk('.'):
|
||||
for f in fs:
|
||||
z.write(os.path.join(d, f))";
|
||||
let zip = std::process::Command::new("python3")
|
||||
.current_dir(&unpacked)
|
||||
.args(["-q", "-r"])
|
||||
.args(["-c", pack])
|
||||
.arg(&excel)
|
||||
.arg(".")
|
||||
.status()
|
||||
.expect("zip runs");
|
||||
assert!(zip.success());
|
||||
|
||||
@@ -50,7 +50,8 @@ fn open() -> (tempfile::TempDir, Worker, Doc, Events) {
|
||||
/// 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")
|
||||
// Windows ends copied lines with CRLF.
|
||||
doc.selection_text(worker).expect("the text").replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
/// The latest report of `name`.
|
||||
@@ -112,7 +113,7 @@ fn number_formats_alignment_and_fills_apply() {
|
||||
// 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")
|
||||
doc.save_as(worker, &crate::file_url(&out), "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");
|
||||
|
||||
@@ -37,7 +37,7 @@ fn open_sheet() -> (tempfile::TempDir, Worker, Doc) {
|
||||
let source = dir.path().join("in.fods");
|
||||
write(&source, FODS);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the sheet loads");
|
||||
(dir, worker, doc)
|
||||
}
|
||||
@@ -174,7 +174,7 @@ pub(super) fn open_book(text: &str) -> (tempfile::TempDir, Worker, Doc) {
|
||||
let source = dir.path().join("book.fods");
|
||||
write(&source, text);
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the book loads");
|
||||
doc.visible_area(&mut worker, (0, 0, 15000, 10000), (256, 3840))
|
||||
.expect("the area");
|
||||
|
||||
+46
-73
@@ -185,7 +185,6 @@ impl Lok {
|
||||
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;
|
||||
@@ -196,29 +195,30 @@ impl Lok {
|
||||
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) {}
|
||||
/// Runs LOK's loop until kit exit; unipoll calls `poll`.
|
||||
pub fn run_loop(&self, poll: Option<Poll>, wake: Option<Wake>) {
|
||||
// VCL calls neither hook while their data is null.
|
||||
static DATA: u8 = 0;
|
||||
let data = std::ptr::addr_of!(DATA).cast_mut().cast();
|
||||
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()
|
||||
);
|
||||
type F = unsafe extern "C" fn(*mut Kit, Option<Poll>, Option<Wake>, *mut c_void);
|
||||
call!(class, 12, F, self.kit, poll, wake, data);
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel library: every build here merges its libraries.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub const KERNEL: &str = "libmergedlo.dylib";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const KERNEL: &str = "libmergedlo.so";
|
||||
#[cfg(windows)]
|
||||
pub const KERNEL: &str = "mergedlo.dll";
|
||||
|
||||
/// Waits up to its microseconds; above zero, work was done.
|
||||
pub type Poll = extern "C" fn(*mut c_void, i32) -> i32;
|
||||
/// The kernel has work for its loop.
|
||||
pub type Wake = extern "C" fn(*mut c_void);
|
||||
|
||||
impl Drop for Lok {
|
||||
fn drop(&mut self) {
|
||||
if self.kit.is_null() {
|
||||
@@ -244,37 +244,17 @@ struct Library {
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Library {
|
||||
/// dlopens the LOK library, merged candidates in order.
|
||||
/// dlopens the merged kernel from `install`.
|
||||
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 });
|
||||
let path = install.join(KERNEL);
|
||||
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() {
|
||||
return Err(io::Error::other(format!("dlopen {}: {}", path.display(), dl_error())));
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!(
|
||||
"no loadable LOK library under {}: {last}",
|
||||
install.display()
|
||||
),
|
||||
))
|
||||
Ok(Self { handle })
|
||||
}
|
||||
|
||||
/// dlsyms `name` from the library.
|
||||
@@ -308,36 +288,29 @@ struct Library {
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Library {
|
||||
/// Loads `<install>/sofficeapp.dll`, merged fallback.
|
||||
/// Loads the merged kernel from `install`.
|
||||
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,
|
||||
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, 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,
|
||||
});
|
||||
let path = install.join(KERNEL);
|
||||
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(),
|
||||
// Its dependencies sit beside it, in program/.
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
|
||||
)
|
||||
};
|
||||
if handle.is_null() {
|
||||
let error = io::Error::last_os_error();
|
||||
return Err(io::Error::other(format!("LoadLibrary {}: {error}", path.display())));
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("no LOK library under {}", install.display()),
|
||||
))
|
||||
Ok(Self {
|
||||
handle: handle as isize,
|
||||
})
|
||||
}
|
||||
|
||||
/// Gets `name` from the library.
|
||||
|
||||
@@ -80,25 +80,6 @@ impl Document {
|
||||
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)
|
||||
|
||||
@@ -3,12 +3,10 @@
|
||||
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>";
|
||||
/// Red text: a BGRA tile shows red in byte two.
|
||||
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: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\" office:version=\"1.3\" office:mimetype=\"application/vnd.oasis.opendocument.text\"><office:automatic-styles><style:style style:name=\"T1\" style:family=\"text\"><style:text-properties fo:color=\"#ff0000\" fo:font-size=\"28pt\" fo:font-weight=\"bold\"/></style:style></office:automatic-styles><office:body><office:text><text:p><text:span text:style-name=\"T1\">verify</text:span></text:p></office:text></office:body></office:document>";
|
||||
|
||||
impl Worker {
|
||||
/// Rejects builds that are not the pinned one (LOK-01).
|
||||
@@ -16,13 +14,11 @@ impl Worker {
|
||||
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)"
|
||||
"the pinned build {BUILD_ID} paints no BGRA red (unpatched, or another order)"
|
||||
));
|
||||
}
|
||||
let _ = profile_dir;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -53,15 +49,14 @@ impl Worker {
|
||||
Ok(build)
|
||||
}
|
||||
|
||||
/// Paints one tile; the bytes it gained.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Paints the red text; whether BGRA red came out.
|
||||
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)
|
||||
let red = Unpack::new(&payload).u64()?;
|
||||
Ok(red > 0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,6 +92,9 @@ pub mod tag {
|
||||
pub const ERR: u8 = 101;
|
||||
}
|
||||
|
||||
/// How a refusal for a changed document begins.
|
||||
pub const STALE: &str = "stale: ";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -103,6 +106,3 @@ mod tests {
|
||||
assert!(super::path_of_file_url("file:///bad%zz").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// How a refusal for a changed document begins.
|
||||
pub const STALE: &str = "stale: ";
|
||||
@@ -81,7 +81,7 @@ fn a_failed_input_still_reports_the_revision_it_reached() {
|
||||
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 doc = worker.load(&crate::file_url(&source)).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 };
|
||||
|
||||
@@ -50,7 +50,7 @@ pub(super) fn live_view_of(
|
||||
let source = dir.path().join(name);
|
||||
std::fs::write(&source, body).expect("the fixture writes");
|
||||
let doc = worker
|
||||
.load(&format!("file://{}", source.display()))
|
||||
.load(&crate::file_url(&source))
|
||||
.expect("the document loads");
|
||||
std::mem::forget(dir);
|
||||
let shared = Arc::new(Mutex::new(worker));
|
||||
|
||||
@@ -39,7 +39,7 @@ fn saved(view: &Entity<LokView>, cx: &mut TestAppContext) -> String {
|
||||
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")
|
||||
.save_as(&mut worker, &crate::file_url(&out), "fods")
|
||||
.expect("the save works");
|
||||
});
|
||||
std::fs::read_to_string(&out).expect("the save reads")
|
||||
|
||||
@@ -20,7 +20,7 @@ fn saved(view: &Entity<LokView>, cx: &mut TestAppContext) -> Vec<String> {
|
||||
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")
|
||||
.save_as(&mut worker, &crate::file_url(&out), "fodt")
|
||||
.expect("the save works");
|
||||
});
|
||||
paragraphs(&std::fs::read_to_string(&out).expect("the save reads"))
|
||||
@@ -263,7 +263,7 @@ fn the_clipboard_moves_html_tables_and_images() {
|
||||
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")
|
||||
.save_as(&mut worker, &crate::file_url(&out), "fodt")
|
||||
.expect("the save works");
|
||||
});
|
||||
let xml = std::fs::read_to_string(&out).expect("the save reads");
|
||||
|
||||
@@ -16,6 +16,14 @@ mod revision;
|
||||
mod slides;
|
||||
mod teardown;
|
||||
mod text;
|
||||
#[cfg(windows)]
|
||||
mod messages;
|
||||
#[cfg(windows)]
|
||||
use messages::serve;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod unipoll;
|
||||
#[cfg(target_os = "linux")]
|
||||
use unipoll::serve;
|
||||
|
||||
/// English kernel, desktop hints; macros stay off (LOK-11).
|
||||
const LOAD_OPTIONS: &str = "Language=en-US,DeviceFormFactor=desktop";
|
||||
@@ -49,7 +57,12 @@ fn serve(lok: Lok, input: impl io::Read + Send + 'static) -> io::Result<()> {
|
||||
}
|
||||
std::thread::spawn(move || reader(input));
|
||||
std::thread::spawn(events::push);
|
||||
lok.run_loop();
|
||||
// Aqua never polls: GCD brings the requests.
|
||||
extern "C" fn poll(_: *mut std::ffi::c_void, _: i32) -> i32 {
|
||||
0
|
||||
}
|
||||
extern "C" fn wake(_: *mut std::ffi::c_void) {}
|
||||
lok.run_loop(Some(poll), Some(wake));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -146,23 +159,6 @@ mod gcd {
|
||||
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");
|
||||
@@ -375,15 +371,16 @@ fn docs() -> &'static Mutex<std::collections::HashMap<u64, Document>> {
|
||||
DOCS.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
|
||||
}
|
||||
|
||||
/// Loads and paints; the bytes gained (R-01).
|
||||
/// Loads and paints red text; its BGRA red pixels (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);
|
||||
// Past the 2 cm margin, where the text sits.
|
||||
doc.paint_rect(&mut tile, (64, 64), (0, 0, 3000, 3000));
|
||||
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)
|
||||
let red = tile.chunks_exact(4).filter(|px| px[2] > 200 && px[0] < 80 && px[1] < 80).count();
|
||||
log::info!("lok-worker: tile self-check found {red} red pixels");
|
||||
Ok(red as u64)
|
||||
}
|
||||
|
||||
/// Borrows a live document for a read call.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Windows: requests ride the kernel's message loop to a window.
|
||||
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
io,
|
||||
sync::atomic::{AtomicPtr, AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HWND, LPARAM, LRESULT, WPARAM},
|
||||
System::LibraryLoader::GetModuleHandleW,
|
||||
UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, HWND_MESSAGE, PostMessageW, RegisterClassW, WM_APP,
|
||||
WNDCLASSW,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{answer, events, lok, password, pin, quit, teardown};
|
||||
use crate::ffi::Lok;
|
||||
use crate::ipc;
|
||||
|
||||
const ASK: u32 = WM_APP + 1;
|
||||
const CLOSED: u32 = WM_APP + 2;
|
||||
|
||||
/// The message-only window the requests go to.
|
||||
static WINDOW: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
|
||||
|
||||
/// Requests posted and not yet answered.
|
||||
static PENDING: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
pub(super) 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);
|
||||
WINDOW.store(window()?, Ordering::SeqCst);
|
||||
std::thread::spawn(move || reader(input));
|
||||
std::thread::spawn(events::push);
|
||||
// Unipoll needs hooks; the Windows loop never calls them.
|
||||
extern "C" fn poll(_: *mut c_void, _: i32) -> i32 {
|
||||
0
|
||||
}
|
||||
extern "C" fn wake(_: *mut c_void) {}
|
||||
lok.run_loop(Some(poll), Some(wake));
|
||||
log::info!("lok-worker: the kernel's loop ended");
|
||||
teardown::teardown(0);
|
||||
}
|
||||
|
||||
/// A window on this thread that only takes messages.
|
||||
fn window() -> io::Result<HWND> {
|
||||
let name: Vec<u16> = "ElyLokWorker\0".encode_utf16().collect();
|
||||
let instance = unsafe { GetModuleHandleW(std::ptr::null()) };
|
||||
let class = WNDCLASSW {
|
||||
lpfnWndProc: Some(procedure),
|
||||
hInstance: instance,
|
||||
lpszClassName: name.as_ptr(),
|
||||
..unsafe { std::mem::zeroed() }
|
||||
};
|
||||
if unsafe { RegisterClassW(&class) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let made = unsafe {
|
||||
CreateWindowExW(
|
||||
0,
|
||||
name.as_ptr(),
|
||||
std::ptr::null(),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
HWND_MESSAGE,
|
||||
std::ptr::null_mut(),
|
||||
instance,
|
||||
std::ptr::null(),
|
||||
)
|
||||
};
|
||||
match made.is_null() {
|
||||
true => Err(io::Error::last_os_error()),
|
||||
false => Ok(made),
|
||||
}
|
||||
}
|
||||
|
||||
fn reader(mut input: impl io::Read) {
|
||||
loop {
|
||||
let (message, request) = match ipc::read_frame(&mut input) {
|
||||
Ok(Some(request)) => {
|
||||
PENDING.fetch_add(1, Ordering::SeqCst);
|
||||
(ASK, Box::into_raw(Box::new(request)))
|
||||
}
|
||||
Ok(None) => {
|
||||
log::info!("lok-worker: stdin closed");
|
||||
(CLOSED, std::ptr::null_mut())
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("lok-worker: frame read failed: {error}");
|
||||
quit(1);
|
||||
}
|
||||
};
|
||||
let window = WINDOW.load(Ordering::SeqCst);
|
||||
if unsafe { PostMessageW(window, message, 0, request as LPARAM) } == 0 {
|
||||
log::error!("lok-worker: a request did not post: {}", io::Error::last_os_error());
|
||||
quit(1);
|
||||
}
|
||||
if message == CLOSED {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Idle jobs yield to a waiting request.
|
||||
extern "C" fn waiting(_: *mut c_void, _: i32) -> bool {
|
||||
PENDING.load(Ordering::SeqCst) > 0
|
||||
}
|
||||
|
||||
unsafe extern "system" fn procedure(
|
||||
window: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
match message {
|
||||
ASK => {
|
||||
let request = unsafe { Box::from_raw(lparam as *mut (u8, u64, Vec<u8>)) };
|
||||
let (tag, id, payload) = *request;
|
||||
PENDING.fetch_sub(1, Ordering::SeqCst);
|
||||
answer(lok(), tag, id, &payload);
|
||||
0
|
||||
}
|
||||
CLOSED => teardown::teardown(0),
|
||||
_ => unsafe { DefWindowProcW(window, message, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Linux: LOK runs its loop; requests arrive in its poll.
|
||||
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
io,
|
||||
sync::{
|
||||
Mutex, OnceLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError, channel},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use super::{answer, events, lok, password, pin, quit, teardown};
|
||||
use crate::ffi::Lok;
|
||||
use crate::ipc;
|
||||
|
||||
/// A request, the kernel's wake, or the end.
|
||||
enum Note {
|
||||
Ask(u8, u64, Vec<u8>),
|
||||
Woken,
|
||||
Closed,
|
||||
}
|
||||
|
||||
type Notes = (Mutex<Sender<Note>>, Mutex<Receiver<Note>>);
|
||||
|
||||
static NOTES: OnceLock<Notes> = OnceLock::new();
|
||||
|
||||
/// Requests read and not yet answered.
|
||||
static PENDING: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
pub(super) 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);
|
||||
let (send, receive) = channel();
|
||||
let reading = send.clone();
|
||||
NOTES
|
||||
.set((Mutex::new(send), Mutex::new(receive)))
|
||||
.map_err(|_| io::Error::other("the loop is served twice"))?;
|
||||
std::thread::spawn(move || reader(input, reading));
|
||||
std::thread::spawn(events::push);
|
||||
lok.run_loop(Some(poll), Some(wake));
|
||||
log::info!("lok-worker: the kernel's loop ended");
|
||||
teardown::teardown(0);
|
||||
}
|
||||
|
||||
fn reader(mut input: impl io::Read, notes: Sender<Note>) {
|
||||
loop {
|
||||
let note = match ipc::read_frame(&mut input) {
|
||||
Ok(Some((tag, id, payload))) => {
|
||||
PENDING.fetch_add(1, Ordering::SeqCst);
|
||||
Note::Ask(tag, id, payload)
|
||||
}
|
||||
Ok(None) => {
|
||||
log::info!("lok-worker: stdin closed");
|
||||
Note::Closed
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("lok-worker: frame read failed: {error}");
|
||||
quit(1);
|
||||
}
|
||||
};
|
||||
let closed = matches!(note, Note::Closed);
|
||||
if notes.send(note).is_err() || closed {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Idle jobs yield to a waiting request.
|
||||
extern "C" fn waiting(_: *mut c_void, _: i32) -> bool {
|
||||
PENDING.load(Ordering::SeqCst) > 0
|
||||
}
|
||||
|
||||
/// The kernel's wait: one request answered, or its own wake.
|
||||
extern "C" fn poll(_: *mut c_void, timeout_us: i32) -> i32 {
|
||||
let notes = &NOTES.get().expect("the loop is served").1;
|
||||
let notes = notes.lock().expect("the notes lock");
|
||||
let note = match timeout_us {
|
||||
0 => notes.try_recv().map_err(|error| error == TryRecvError::Disconnected),
|
||||
wait if wait < 0 => notes.recv().map_err(|_| true),
|
||||
wait => notes
|
||||
.recv_timeout(Duration::from_micros(wait as u64))
|
||||
.map_err(|error| error == RecvTimeoutError::Disconnected),
|
||||
};
|
||||
drop(notes);
|
||||
match note {
|
||||
Ok(Note::Ask(tag, id, payload)) => {
|
||||
PENDING.fetch_sub(1, Ordering::SeqCst);
|
||||
answer(lok(), tag, id, &payload);
|
||||
1
|
||||
}
|
||||
Ok(Note::Woken) => 1,
|
||||
Ok(Note::Closed) | Err(true) => teardown::teardown(0),
|
||||
Err(false) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Another thread posted work for the kernel's loop.
|
||||
extern "C" fn wake(_: *mut c_void) {
|
||||
let notes = &NOTES.get().expect("the loop is served").0;
|
||||
if notes.lock().expect("the notes lock").send(Note::Woken).is_err() {
|
||||
log::info!("lok-worker: a wake after the loop ended");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user