Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 97 additions & 7 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,8 @@ pub struct UiState {
pub(crate) history_jump: Option<chrome::HistoryJump>,
/// Whether a layout's PDF georeferences its map frames (Layout › Export › Georeference PDF).
pub(crate) pdf_georeference: bool,
/// The resolution picked in Export Layout's menu, where files are downloaded (web, phones).
pub(crate) layout_export_dpi: u32,
/// The native title bar the header is drawn into; set by the desktop app on macOS.
pub titlebar: Option<TitlebarMetrics>,
/// Saved pane arrangements: (name, left pane, right pane in view, ribbon tab, right panes open).
Expand Down Expand Up @@ -1454,6 +1456,7 @@ impl Default for UiState {
quick_access: Vec::new(),
history_jump: None,
pdf_georeference: true,
layout_export_dpi: 150,
titlebar: None,
pane_sets: Vec::new(),
layer_filter: String::new(),
Expand Down Expand Up @@ -5386,11 +5389,21 @@ impl RustGisApp {
let li = self.session.active_layout.ok_or("open a layout first")?;
let name = self.session.project.layouts.get(li).map(|l| l.name.clone()).unwrap_or_default();
let print = id == "ui.printLayout";
let pdf_only = print || p.get("format").and_then(Value::as_str) == Some("pdf");
// Print is always a PDF at 300 dpi; Export takes a format and a resolution.
let format = match p.get("format").filter(|v| !v.is_null()) {
_ if print => Some("pdf"),
None => None,
Some(v) => Some(
["pdf", "png", "svg"].into_iter().find(|f| v == f).ok_or_else(|| tl!("format is pdf, png or svg").to_string())?,
),
};
// Passed on as given: `layout.export` reads it, a number in text too.
let dpi = p.get("dpi").filter(|v| !v.is_null() && !print).cloned();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
if self.services.download.is_some() {
let dpi = if print { 300 } else { 150 };
let dpi = dpi.unwrap_or_else(|| json!(if print { 300 } else { 150 }));
let params = json!({"layout": li, "dpi": dpi, "georeference": self.ui.pdf_georeference});
return self.run_offering("layout.export", &format!("{name}.pdf"), params, None);
let file = format!("{name}.{}", format.unwrap_or("pdf"));
return self.run_offering("layout.export", &file, params, None);
} else if print {
// Printing goes through the system's PDF viewer, which owns the printers.
let bytes = self.layout_bytes(li, true, 300.0)?;
Expand All @@ -5401,11 +5414,16 @@ impl RustGisApp {
open_with_system(&path)?;
self.session.notify(i18n::fmt("Opened {name} for printing", &[("name", &path.display().to_string())]), false);
} else {
let (exts, kinds): (&[&str], _) =
if pdf_only { (&["pdf"], tl!("PDF")) } else { (&["pdf", "png", "svg"], tl!("PDF, PNG or SVG")) };
if let Some(path) = dialogs::pick_save(&format!("{name}.pdf"), exts, kinds) {
let (exts, kinds): (&[&str], _) = match format {
Some("png") => (&["png"], tl!("PNG")),
Some("svg") => (&["svg"], tl!("SVG")),
Some(_) => (&["pdf"], tl!("PDF")),
None => (&["pdf", "png", "svg"], tl!("PDF, PNG or SVG")),
};
if let Some(path) = dialogs::pick_save(&format!("{name}.{}", exts[0]), exts, kinds) {
// Drawn on a thread of its own, with progress and Cancel in the status bar.
let params = json!({"layout": li, "path": path, "dpi": 200, "georeference": self.ui.pdf_georeference});
let dpi = dpi.unwrap_or_else(|| json!(200));
let params = json!({"layout": li, "path": path, "dpi": dpi, "georeference": self.ui.pdf_georeference});
#[cfg(not(target_arch = "wasm32"))]
return exportjob::start(self, "layout.export", params);
#[cfg(target_arch = "wasm32")]
Expand Down Expand Up @@ -10430,6 +10448,7 @@ mod download_service_tests {
("ui.exportRaster", json!({}), "Dem.tif".into()),
("ui.exportMap", json!({}), format!("{map}.png")),
("ui.exportLayout", json!({}), "Page.pdf".into()),
("ui.exportLayout", json!({"format": "png"}), "Page.png".into()),
("ui.printLayout", json!({}), "Page.pdf".into()),
("ui.saveLayout", json!({}), "Page.rgislayout".into()),
("ui.exportReport", json!({}), "List.pdf".into()),
Expand Down Expand Up @@ -10458,6 +10477,77 @@ mod download_service_tests {
assert!(path.exists());
}

/// The browser's Export Layout downloads the format and resolution asked for; without them, a
/// PDF at 150 dpi (#3461).
#[test]
fn export_layout_downloads_the_format_and_dpi_asked_for() {
let taken: std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>> = Default::default();
let downloads = taken.clone();
let mut app = RustGisApp::with_sample().with_services(Services {
download: Some(Box::new(move |name, bytes| {
downloads.lock().unwrap().push((name.to_string(), std::sync::Arc::unwrap_or_clone(bytes)));
Ok(())
})),
..Default::default()
});
let e = app.run("ui.exportLayout", json!({"format": "png"})).unwrap_err();
assert!(e.contains("open a layout first"), "{e}");
app.run("layout.new", json!({"name": "Page", "template": "blank"})).unwrap();
let width = app.session.project.layouts[0].width;
let mut export = |params: serde_json::Value| {
app.run("ui.exportLayout", params).unwrap();
let mut files = std::mem::take(&mut *taken.lock().unwrap());
assert_eq!(files.len(), 1);
files.pop().unwrap()
};
for (params, dpi) in [
(json!({"format": "png"}), 150.0),
(json!({"format": "png", "dpi": 96}), 96.0),
(json!({"format": "png", "dpi": 300}), 300.0),
(json!({"format": "png", "dpi": "96"}), 96.0),
] {
let (name, bytes) = export(params);
assert_eq!(name, "Page.png");
let got = image::load_from_memory(&bytes).unwrap().width() as f64;
assert!((got - width / 25.4 * dpi).abs() <= 1.0, "{got} px at {dpi} dpi");
}
let (name, bytes) = export(json!({"format": "svg"}));
assert_eq!(name, "Page.svg");
let text = String::from_utf8(bytes).unwrap();
assert!(text.contains("<svg"), "{text:.80}");
for params in [json!({}), json!({"format": "pdf", "dpi": 300})] {
let (name, bytes) = export(params);
assert_eq!(name, "Page.pdf");
assert!(bytes.starts_with(b"%PDF"));
}
let e = app.run("ui.exportLayout", json!({"format": "tiff"})).unwrap_err();
assert!(e.contains("format is pdf, png or svg"), "{e}");
assert!(taken.lock().unwrap().is_empty());
}

/// On the desktop the same parameters reach the saved file, and a format that isn't one is
/// refused before the save dialog (#3461).
#[test]
fn export_layout_on_the_desktop_takes_the_format_and_dpi() {
let mut app = RustGisApp::with_sample();
app.run("layout.new", json!({"name": "Page", "template": "blank"})).unwrap();
let width = app.session.project.layouts[0].width;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("page.png");
crate::dialogs::PICKED.with(|c| *c.borrow_mut() = Some(path.display().to_string()));
let e = app.run("ui.exportLayout", json!({"format": "tiff"})).unwrap_err();
assert!(e.contains("format is pdf, png or svg"), "{e}");
assert!(crate::dialogs::PICKED.with(|c| c.borrow().is_some()), "refused before asking where to save");
app.run("ui.exportLayout", json!({"format": "png", "dpi": 96})).unwrap();
let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
while crate::exportjob::land(&mut app) {
assert!(std::time::Instant::now() < end, "the export never landed");
std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: legacy polling for background export completion
}
let got = image::open(&path).unwrap().width() as f64;
assert!((got - width / 25.4 * 96.0).abs() <= 1.0, "{got} px at 96 dpi");
}

/// A file already waiting is delivered before a button's, so it says what it would have said and
/// doesn't take the button's line: a button's file the host refuses isn't said to be offered.
#[test]
Expand Down
27 changes: 25 additions & 2 deletions crates/ui-egui/src/ribbon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3336,7 +3336,7 @@ fn share_groups(app: &mut RustGisApp, ui: &mut Ui) {
});
});
group(ui, "Layout", |ui| {
big(ui, app, "export", "Export\nLayout", "Export the open layout as PDF or PNG.", "ui.exportLayout", Value::Null, false, false);
export_layout_button(ui, app, "Export\nLayout", "Export the open layout as PDF, PNG or SVG.");
big(
ui,
app,
Expand Down Expand Up @@ -3708,7 +3708,7 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) {
{}
});
group(ui, "Export", |ui| {
big(ui, app, "export", "Export", "Export the layout as PDF or PNG.", "ui.exportLayout", Value::Null, false, false);
export_layout_button(ui, app, "Export", "Export the layout as PDF, PNG or SVG.");
big(ui, app, "print", "Print", "Print the layout.", "ui.printLayout", Value::Null, false, false);
col(ui, |ui| {
small(
Expand Down Expand Up @@ -3737,6 +3737,29 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) {
});
}

/// Export Layout. Where files are downloaded there is no save dialog to pick a format in, so the
/// button opens a menu of the resolution and the formats (#3461); elsewhere it opens that dialog.
fn export_layout_button(ui: &mut Ui, app: &mut RustGisApp, label: &str, desc: &str) {
if app.services.download.is_none() {
big(ui, app, "export", label, desc, "ui.exportLayout", Value::Null, false, false);
return;
}
big_form_menu(ui, app, "export", label, desc, |ui, app| {
ui.label(tl!("Resolution"));
ui.horizontal(|ui| {
for dpi in [96, 150, 300] {
let text = crate::i18n::fmt("{dpi} dpi", &[("dpi", &dpi.to_string())]);
ui.radio_value(&mut app.ui.layout_export_dpi, dpi, text);
}
});
ui.separator();
for (format, label) in [("pdf", "PDF"), ("png", "PNG"), ("svg", "SVG")] {
let params = json!({"format": format, "dpi": app.ui.layout_export_dpi});
menu_item(ui, app, "", label, "ui.exportLayout", params);
}
});
}

fn plugins_tab(app: &mut RustGisApp, ui: &mut Ui) {
group(ui, "Plugins", |ui| {
big(
Expand Down
5 changes: 4 additions & 1 deletion docs/user-guide/layouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -1037,7 +1037,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu
and line widths can differ from PNG/PDF and can
change when edited. A picture standing for a whole element is clipped to its box;
`layout.export` accepts `dpi` and `"allPages": false` for just the current PDF
page. **Print** opens the PDF in the system viewer on desktop; **Save Layout File** and
page. In the browser and on phones, **Export** opens a menu: pick the resolution (96, 150 or
300 dpi; 150 at first) and then **PDF**, **PNG** or **SVG**, which downloads the layout in that
format. The `ui.exportLayout` command takes the same choices as `"format"` and `"dpi"`.
**Print** opens the PDF in the system viewer on desktop; **Save Layout File** and
**Import Layout** move layouts between projects (`.rgislayout`).
- **Capture To Clipboard** copies an image of the current page at 192 dpi, with any text still being
typed. A page that would pass 16 million pixels, or 12,000 pixels on a side, is copied at a lower
Expand Down
Loading