mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 18:46:51 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa61ab1ba8 |
@@ -8,7 +8,7 @@ workflows:
|
||||
'.github/workflows/house-rules.yml': []
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
@@ -16,7 +16,7 @@ workflows:
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
'.github/workflows/release.yml': []
|
||||
'.github/workflows/sonarcloud.yml': []
|
||||
'.github/workflows/windows-arm64.yml': []
|
||||
@@ -26,8 +26,8 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'step-security/harden-runner@v2.22.4':
|
||||
ref: 'v2.22.4'
|
||||
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
|
||||
'step-security/harden-runner@v2.23.0':
|
||||
ref: 'v2.23.0'
|
||||
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
|
||||
owner_id: 88700172
|
||||
repo_id: 422287306
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
Generated
-1
@@ -3078,7 +3078,6 @@ dependencies = [
|
||||
name = "gridcraft-web"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
|
||||
@@ -25,10 +25,9 @@ log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
@@ -227,7 +227,11 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
log::error!("download of {name} failed: {e}");
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(craft_print::browser::print_pdf)),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
if let Some(w) = web_sys::window()
|
||||
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
|
||||
@@ -276,6 +280,75 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
if let Err(e) = body.append_child(&iframe) {
|
||||
cleanup_print(&iframe, &url);
|
||||
return Err(js(e));
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
iframe_for_load.set_onload(None);
|
||||
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
|
||||
cleanup_print(&iframe_for_load, &url_for_cleanup);
|
||||
log::error!("print failed: {e:?}");
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
|
||||
// Both operations are idempotent: print can fail after dispatching `afterprint`.
|
||||
web_sys::Url::revoke_object_url(url).ok();
|
||||
iframe.remove();
|
||||
}
|
||||
|
||||
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
|
||||
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
|
||||
let iframe_for_cleanup = iframe.clone();
|
||||
let url_for_cleanup = url.to_owned();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
|
||||
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
|
||||
});
|
||||
// Listen before `print()`, which can dispatch `afterprint` before it returns.
|
||||
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
|
||||
let options = web_sys::AddEventListenerOptions::new();
|
||||
options.set_once(true);
|
||||
let callback = on_after_print.as_ref().unchecked_ref();
|
||||
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
|
||||
if let Err(e) = content_window.print() {
|
||||
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = on_after_print.into_js_value();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
|
||||
@@ -249,11 +249,6 @@ pub trait Dialect {
|
||||
fn boolean(&self, b: bool) -> &'static str {
|
||||
if b { "TRUE" } else { "FALSE" }
|
||||
}
|
||||
/// Maximum UTF-16 units in a scalar text literal in this syntax. Longer strings are
|
||||
/// emitted as a parenthesized concatenation of literals.
|
||||
fn scalar_text_limit(&self) -> Option<std::num::NonZeroUsize> {
|
||||
None
|
||||
}
|
||||
/// The separators between a call's arguments, between an inline array's columns, and between
|
||||
/// its rows (`,` `,` `;` in A1).
|
||||
fn separators(&self) -> (char, char, char) {
|
||||
@@ -306,38 +301,15 @@ fn write_list<'e>(s: &mut String, items: impl IntoIterator<Item = &'e Expr>, sep
|
||||
}
|
||||
}
|
||||
|
||||
fn write_text(s: &mut String, t: &str) {
|
||||
s.push('"');
|
||||
s.push_str(&t.replace('"', "\"\""));
|
||||
s.push('"');
|
||||
}
|
||||
|
||||
fn write_scalar_text(s: &mut String, t: &str, d: &dyn Dialect) {
|
||||
let Some(limit) = d.scalar_text_limit().map(std::num::NonZeroUsize::get) else { return write_text(s, t) };
|
||||
if t.encode_utf16().count() <= limit {
|
||||
return write_text(s, t);
|
||||
}
|
||||
s.push('(');
|
||||
let mut start = 0;
|
||||
let mut units = 0;
|
||||
for (at, c) in t.char_indices() {
|
||||
if units != 0 && units + c.len_utf16() > limit {
|
||||
write_text(s, &t[start..at]);
|
||||
s.push('&');
|
||||
start = at;
|
||||
units = 0;
|
||||
}
|
||||
units += c.len_utf16();
|
||||
}
|
||||
write_text(s, &t[start..]);
|
||||
s.push(')');
|
||||
}
|
||||
|
||||
fn write_expr(s: &mut String, e: &Expr, d: &dyn Dialect) {
|
||||
let (arg_sep, col_sep, row_sep) = d.separators();
|
||||
match e {
|
||||
Expr::Number(n) => s.push_str(&number(*n)),
|
||||
Expr::Text(t) => write_scalar_text(s, t, d),
|
||||
Expr::Text(t) => {
|
||||
s.push('"');
|
||||
s.push_str(&t.replace('"', "\"\""));
|
||||
s.push('"');
|
||||
}
|
||||
Expr::Bool(b) => s.push_str(d.boolean(*b)),
|
||||
Expr::Error(err) => s.push_str(err.as_str()),
|
||||
Expr::Array(rows) => {
|
||||
@@ -346,17 +318,7 @@ fn write_expr(s: &mut String, e: &Expr, d: &dyn Dialect) {
|
||||
if ri > 0 {
|
||||
s.push(row_sep);
|
||||
}
|
||||
for (ci, item) in row.iter().enumerate() {
|
||||
if ci > 0 {
|
||||
s.push(col_sep);
|
||||
}
|
||||
// An inline array takes constants, so a concatenation cannot replace one.
|
||||
if let Expr::Text(t) = item {
|
||||
write_text(s, t);
|
||||
} else {
|
||||
write_expr(s, item, d);
|
||||
}
|
||||
}
|
||||
write_list(s, row, col_sep, d);
|
||||
}
|
||||
s.push('}');
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ impl SheetApp {
|
||||
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
self.print_feedback_seen = None;
|
||||
} else if let Some(print) = &self.services.print {
|
||||
print(&bytes)?;
|
||||
print(&bytes);
|
||||
} else {
|
||||
return Err("Printing is unavailable here; export a PDF instead.".into());
|
||||
}
|
||||
|
||||
@@ -39,10 +39,8 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
|
||||
&& app.commit_edit(0, 0, false, false)
|
||||
{
|
||||
match app.run("ui.printSubmit", params.clone()) {
|
||||
Ok(_) => out.close = app.services.print_native.is_none(),
|
||||
Err(error) => app.alert(error),
|
||||
}
|
||||
app.print_now(params.clone());
|
||||
out.close = app.services.print_native.is_none();
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
|
||||
@@ -4,7 +4,7 @@ type PickSave = Box<dyn Fn(&str) -> Option<String>>;
|
||||
type OpenUrl = Box<dyn Fn(&str)>;
|
||||
type CopyHtml = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
|
||||
type Download = Box<dyn Fn(&str, &[u8])>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8]) -> Result<(), String>>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8])>;
|
||||
|
||||
/// Host services the platform shell provides (file pickers, opening URLs).
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -21,10 +21,7 @@ fn harness(jobs: Rc<RefCell<Vec<Vec<u8>>>>) -> egui_kittest::Harness<'static, Sh
|
||||
app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
app.run("selection.set", json!({"range": "A1:B2"})).unwrap();
|
||||
app.services.print = Some(Box::new(move |bytes| {
|
||||
jobs.borrow_mut().push(bytes.to_vec());
|
||||
Ok(())
|
||||
}));
|
||||
app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec())));
|
||||
app.run("ui.backstage", json!({"page": "print"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
@@ -79,30 +76,3 @@ fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() {
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_browser_handoff_keeps_the_print_selection_available_for_retry() {
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut h = harness(jobs.clone());
|
||||
choose_selection(&mut h);
|
||||
let accepted = h.state_mut().services.print.take();
|
||||
h.state_mut().services.print = Some(Box::new(|_| Err("The browser blocked the print window".into())));
|
||||
let error = h.state_mut().run("ui.printSubmit", json!({})).unwrap_err();
|
||||
assert!(error.contains("blocked the print window"));
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_some());
|
||||
assert!(h.state().message.as_ref().unwrap().1.contains("blocked the print window"));
|
||||
assert!(jobs.borrow().is_empty());
|
||||
|
||||
h.state_mut().message = None;
|
||||
h.state_mut().services.print = accepted;
|
||||
h.run_steps(3);
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_none());
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(contains(&jobs[0], "(Inside) Tj"));
|
||||
assert!(!contains(&jobs[0], "(Outside) Tj"));
|
||||
}
|
||||
|
||||
+2
-19
@@ -4,19 +4,11 @@
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::Formula;
|
||||
|
||||
struct Xlsx;
|
||||
|
||||
impl gridcraft_formula::printer::Dialect for Xlsx {
|
||||
fn scalar_text_limit(&self) -> Option<std::num::NonZeroUsize> {
|
||||
std::num::NonZeroUsize::new(255)
|
||||
}
|
||||
}
|
||||
|
||||
/// Formula text for a file.
|
||||
pub fn to_file(f: &Formula) -> String {
|
||||
match f.expr_arc() {
|
||||
// Most formulas have nothing the file spells differently: print them without copying.
|
||||
Some(e) if !needs_file_spelling(&e) => gridcraft_formula::printer::print_with(&e, &Xlsx),
|
||||
Some(e) if !needs_file_spelling(&e) => gridcraft_formula::print(&e),
|
||||
Some(e) => expr_to_file(Expr::clone(&e)),
|
||||
None => f.text.clone(),
|
||||
}
|
||||
@@ -142,7 +134,7 @@ fn expr_to_file(e: Expr) -> String {
|
||||
}
|
||||
other => other,
|
||||
});
|
||||
gridcraft_formula::printer::print_with(&e, &Xlsx)
|
||||
gridcraft_formula::print(&e)
|
||||
}
|
||||
|
||||
/// The operands whose parentheses the reader adds back to `_xlfn.SINGLE(x)` (see the formula
|
||||
@@ -279,15 +271,6 @@ pub(crate) fn test_known_function(n: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn xlsx_long_text_is_written_as_short_quoted_literals() {
|
||||
let first = "a".repeat(254);
|
||||
let rest = "😀\"last";
|
||||
let input = format!("LEN(\"{first}{}\")", rest.replace('"', "\"\""));
|
||||
let expected = format!("LEN((\"{first}\"&\"😀\"\"last\"))");
|
||||
assert_eq!(to_file(&Formula::new(&input)), expected);
|
||||
assert_eq!(text_to_file(&input), expected);
|
||||
}
|
||||
use super::*;
|
||||
|
||||
/// Formulas without a file spelling skip the rewrite; the text must be what it would give.
|
||||
|
||||
Reference in New Issue
Block a user