Skip to content
Merged
37 changes: 37 additions & 0 deletions crates/engine/src/tests/qgis_layouts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,40 @@ fn a_long_layout_name_numbered_keeps_its_page_and_says_the_cut() {
let answer = s.run("project.importQgis", &sheets()).unwrap();
assert!(!said(&answer), "{answer}");
}

/// A QGIS layout's scale bar, north arrow and map overview come in showing the frames the import
/// made, inline and from a copy, and the layout exports.
#[test]
fn a_layouts_surrounds_show_the_imported_frames() {
let text = r#"<qgis><title>T</title><projectCrs><spatialrefsys><authid>EPSG:2056</authid></spatialrefsys></projectCrs>
<Layouts><Layout name="Surrounds"><PageCollection><LayoutItem type="65638" position="0,0,mm" size="297,210,mm"/></PageCollection>
<LayoutItem type="65639" uuid="{main}" zValue="1" position="10,10,mm" size="150,100,mm"><Extent xmin="2696300" ymin="1261200" xmax="2698000" ymax="1262475"/></LayoutItem>
<LayoutItem type="65639" uuid="{ov}" zValue="0" position="170,10,mm" size="60,50,mm"><Extent xmin="2690000" ymin="1255000" xmax="2705000" ymax="1270000"/><ComposerMapOverview show="1" frameMap="{main}"/></LayoutItem>
<LayoutItem type="65646" mapUuid="{main}" style="Single Box" segmentSizeMode="1" zValue="2" position="10,115,mm" size="60,12,mm"/>
<LayoutItem type="65640" mapUuid="{main}" northMode="0" file=":/images/north_arrows/layout_default_north_arrow.svg" zValue="2" position="170,70,mm" size="20,20,mm"/>
</Layout></Layouts></qgis>"#;
let check = |s: &Session| {
let l = s.project.layouts.iter().find(|l| l.name == "Surrounds").unwrap();
let frames: Vec<u32> = l.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).map(|e| e.id).collect();
let (overview, main) = (frames[0], frames[1]);
assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::ScaleBar { frame, .. } if frame == main)));
assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame, .. } if frame == main)));
let shown = l.elements.iter().find(|e| e.id == overview).unwrap().kind.extent_indicators();
assert_eq!(shown.iter().map(|i| i.of).collect::<Vec<_>>(), [main]);
};
let mut s = Session::new(Project::default());
s.run("project.importQgis", &json!({"text": text})).unwrap();
check(&s);
let dir = std::env::temp_dir().join(format!("rustgis-qgis-surrounds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let png = dir.join("surrounds.png");
s.run("layout.export", &json!({"layout": "Surrounds", "path": png.display().to_string(), "dpi": 36})).unwrap();
assert!(std::fs::metadata(&png).unwrap().len() > 0);
let _ = std::fs::remove_dir_all(&dir);
// From a copy.
let mut s = Session::new(Project::default());
let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &json!({"text": text})).unwrap();
let done = read.run(&Control::new()).unwrap();
crate::cmd::reads::read_land(&mut s, done).unwrap();
check(&s);
}
236 changes: 184 additions & 52 deletions crates/map/src/qgis/layout.rs

Large diffs are not rendered by default.

488 changes: 488 additions & 0 deletions crates/map/src/qgis/layout/surround.rs

Large diffs are not rendered by default.

610 changes: 610 additions & 0 deletions crates/map/src/qgis/layout_surround_tests.rs

Large diffs are not rendered by default.

66 changes: 60 additions & 6 deletions crates/map/src/qgis/layout_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,14 @@ fn qgis_layout_items_without_a_place_are_noted() {
let mut report = Report::default();
let p = super::read_project(&text, &root.to_string_lossy(), &mut |_, _| Err((super::IMAGE_UNOPENED, false)), &mut report).unwrap();
assert_eq!(p.layouts.len(), 1);
// Its scale bar and north arrow come in, showing its map's frame.
let l = &p.layouts[0].layout;
let frame = l.first_frame().unwrap();
assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::ScaleBar { frame: f, .. } if f == frame)));
assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame: f, .. } if f == frame)));
for part in [
"legends (1)",
"scale bars (1)",
"north arrows (pictures turned with a map) (1)",
"north arrows (pictures turned with a map), drawn as RustGIS's arrow (1)",
"attribute tables (1)",
"HTML frames (1)",
"marker items (1)",
Expand Down Expand Up @@ -529,9 +533,8 @@ fn merged_notes_keep_their_count_past_the_cap() {
assert_eq!((closing.count, closing.text.as_str()), (4, "4 more note(s) not listed"), "{closing:?}");
}

/// Pictures that never come in as elements (north arrows, SVGs, no file, a path that doesn't
/// check) aren't counted past a full layout: they are said as what they are; a picture that
/// would come in is.
/// Pictures that never come in as elements (SVGs, no file, a path that doesn't check) aren't
/// counted past a full layout: they are said as what they are; a picture that would come in is.
#[test]
fn a_full_layout_counts_only_pictures_that_would_come_in() {
let mut items = String::new();
Expand All @@ -552,8 +555,9 @@ fn a_full_layout_counts_only_pictures_that_would_come_in() {
let qgs = format!(r#"<qgis><Layouts><Layout name="F">{page}{items}</Layout></Layouts></qgis>"#);
let mut report = Report::default();
read(&qgs, &mut report);
// The north arrows' map isn't in the layout: they are said as that, not counted past it.
assert!(!said(&report, "elements past the 500"), "{:?}", report.notes);
assert!(said(&report, "north arrows (pictures turned with a map) (3)"), "{:?}", report.notes);
assert!(said(&report, "scale bars and north arrows whose map isn't on their page, or is left out (3)"), "{:?}", report.notes);
assert!(said(&report, "pictures that can't be read (1;"), "{:?}", report.notes);
// What doesn't come in isn't said as drawn otherwise.
assert!(!said(&report, "blending modes"), "{:?}", report.notes);
Expand Down Expand Up @@ -1001,3 +1005,53 @@ fn a_label_read_short_is_said_cut() {
read(&qgs("TT"), &mut report);
assert!(said(&report, "labels longer than 5000 characters, cut there (1)"), "{:?}", report.notes);
}

/// A page's fill takes its first layer switched on: one switched off gives no colour.
#[test]
fn a_pages_switched_off_fill_layer_gives_no_paper() {
let layer = |enabled: &str, c: &str| {
format!(
r#"<layer class="SimpleFill" enabled="{enabled}"><Option type="Map"><Option name="color" type="QString" value="{c}"/></Option></layer>"#
)
};
let qgs = |layers: &str| {
format!(
r#"<qgis><Layouts><Layout name="P"><PageCollection><LayoutItem type="65638" position="0,0,mm" size="210,297,mm"><symbol type="fill" name="">{layers}</symbol></LayoutItem></PageCollection></Layout></Layouts></qgis>"#
)
};
let p = read(&qgs(&(layer("0", "0,0,255,255") + &layer("1", "255,255,200,255"))), &mut Report::default());
assert_eq!(p.layouts[0].layout.paper, Some(Rgba::rgb(255, 255, 200)));
let p = read(&qgs(&layer("0", "0,0,255,255")), &mut Report::default());
assert_eq!(p.layouts[0].layout.paper, None);
}

/// A page's fill switched off gives no paper; one of several layers or a pattern is said as drawn
/// in a plain colour; a plain one isn't.
#[test]
fn a_pages_fill_beyond_a_colour_is_said() {
let layer = |c: &str, style: &str| {
format!(
r#"<layer class="SimpleFill" enabled="1"><Option type="Map"><Option name="color" type="QString" value="{c}"/><Option name="style" type="QString" value="{style}"/></Option></layer>"#
)
};
let page = |layers: &str| {
let qgs = format!(
r#"<qgis><Layouts><Layout name="P"><PageCollection><LayoutItem type="65638" position="0,0,mm" size="210,297,mm"><symbol type="fill" name="">{layers}</symbol></LayoutItem></PageCollection></Layout></Layouts></qgis>"#
);
let mut report = Report::default();
let p = read(&qgs, &mut report);
(
p.layouts[0].layout.paper,
said(&report, "pages whose fill has several layers, a pattern, an outline or is of another kind, drawn as a plain colour (1)"),
)
};
assert_eq!(page(&layer("0,0,255,255", "no")), (None, false));
assert_eq!(page(&layer("0,0,255,255", "solid")), (Some(Rgba::rgb(0, 0, 255)), false));
assert_eq!(page(&layer("0,0,255,255", "dense3")), (Some(Rgba::rgb(0, 0, 255)), true));
assert_eq!(page(&(layer("0,0,255,255", "solid") + &layer("255,0,0,255", "solid"))), (Some(Rgba::rgb(0, 0, 255)), true));
let outlined = layer("0,0,255,255", "solid")
.replace("</Option></layer>", r#"<Option name="outline_style" type="QString" value="solid"/></Option></layer>"#);
assert_eq!(page(&outlined), (Some(Rgba::rgb(0, 0, 255)), true));
let gradient = layer("0,0,255,255", "solid").replace(r#"class="SimpleFill""#, r#"class="GradientFill""#);
assert_eq!(page(&gradient), (Some(Rgba::rgb(0, 0, 255)), true));
}
2 changes: 2 additions & 0 deletions crates/map/src/qgis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ mod expr;
mod labels;
mod layout;
#[cfg(test)]
mod layout_surround_tests;
#[cfg(test)]
mod layout_tests;
mod raster;
mod renderer;
Expand Down
2 changes: 1 addition & 1 deletion crates/map/src/qgis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1152,7 +1152,7 @@ fn every_corpus_file_reads() {
}
}
let projects = files("generated/qgs", &["qgs", "qgz"]);
assert_eq!(projects.len(), 39, "project corpus changed: {projects:?}");
assert_eq!(projects.len(), 40, "project corpus changed: {projects:?}");
for path in &projects {
let bytes = std::fs::read(path).unwrap();
let text = if path.extension().is_some_and(|e| e == "qgz") {
Expand Down
4 changes: 2 additions & 2 deletions crates/map/testdata/qgis/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ no specification of these formats, so the corpus stands in for one: `every_corpu
| Folder | What | Licence |
|---|---|---|
| `generated/qml/` | 126 styles written through QGIS's API (4.2.3; the SVG marker ones 4.4.0), each varying one thing: every symbol layer type with its defaults, raster image markers (a PNG and a JPEG, in a file and embedded; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), SVG markers (an SVG with `param(…)` colours and outline width and one without, in a file and embedded, one from QGIS's own library, which isn't copied here; colours with alpha; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), every renderer (categorized and graduated by expression, rule-based with nested and else rules), every paint effect, data-defined size, angle and colour, labels (every placement, buffer, background, shadow, font, wrap, expression text, offsets, data-defined settings, scale ranges, curved labels, each callout, rule-based labels), layer settings (opacity, blend mode, scale range, reference scale, subset), diagrams (pie, by fields and expressions, a histogram, a stacked bar and a text diagram, two of them sized between two values) and raster renderers (grey, pseudocolour interpolated, discrete and exact, multiband, paletted, hillshade, contour) | Apache-2.0, like RustGIS: made by Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project |
| `generated/qgs/` | 39 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; `layout-sheets.qgs`, print layouts as map sheets (an A4 landscape sheet of two pages with a framed, turned map, a title and a note with an expression, a turned label with a background and frame, a picture, a rounded rectangle, a translucent ellipse, a triangle and a dashed line, items placed in mm, cm, in and pt, a hidden item, one left out of exports and two grouped; and a Letter portrait sheet in inches), written by QGIS 4.4.0; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 |
| `generated/qgs/` | 40 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; `layout-sheets.qgs`, print layouts as map sheets (an A4 landscape sheet of two pages with a framed, turned map, a title and a note with an expression, a turned label with a background and frame, a picture, a rounded rectangle, a translucent ellipse, a triangle and a dashed line, items placed in mm, cm, in and pt, a hidden item, one left out of exports and two grouped; and a Letter portrait sheet in inches), written by QGIS 4.4.0; `layout-surrounds.qgs`, a sheet with the surrounds tied to a map (scale bars of a single box, ticks up and a stepped line fitted to their box, a numeric one, a north arrow following the map, and an overview map outlining its extent), written by QGIS 4.4.0; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 |
| `generated/data/` | The data those files use: `sample.gpkg` (layers `points`, `lines` and `polygons`, 9 made-up features each, fields `id`, `name`, `kind`, `value`, `angle`, `day`), `dem.tif` (3 bands of a linear surface), two CSVs, a GPX file, `picture.png` (a red 40 × 20 picture), `marker.png` (32 × 16, a red square and a blue bar) and `marker.jpg` (24 × 24, green with a yellow corner), the raster image markers' images; `icon.svg` (the same square and bar) and `marker.svg` (a triangle and a rectangle in `param(…)` colours), the SVG markers' images | Apache-2.0 |
| `generated/generate.py`, `scrub.py` | The generator, and the step that removes the user's name and absolute paths from what QGIS writes | Apache-2.0 |
| `generated/types.txt` | The element types QGIS 4.2.3 knows (symbol layers, renderers, providers, label placements, callouts, annotation and layout items, paint effects): the checklist the corpus was made from. A few have no file yet: the single-colour raster renderer, and the text table, fixed table, elevation profile and chart layout items | Apache-2.0 |
Expand Down Expand Up @@ -40,7 +40,7 @@ QGIS 4.2.3 wrote the corpus, and 4.4.0 the SVG marker files. The command runs wh
installed (here the Flathub Flatpak, whose `/tmp` is private, so it writes under `~/.cache`) and
writes the whole corpus again, so copy only the files you mean to replace: for the SVG markers,
`data/icon.svg`, `data/marker.svg`, `qml/symbol-svg-marker-*.qml` and `qgs/svg-markers.qgs`; for the map sheets,
`qgs/layout-sheets.qgs`.
`qgs/layout-sheets.qgs` and `qgs/layout-surrounds.qgs`.

```sh
mkdir -p ~/.cache/qgis-corpus
Expand Down
75 changes: 75 additions & 0 deletions crates/map/testdata/qgis/generated/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1387,6 +1387,81 @@ def __exit__(self, *a):

# (After the annotations, which write `picture.png`.)
attempt("layout sheets", layout_sheets)


# A sheet with the surrounds tied to a map (piece 12b): scale bars in the styles RustGIS draws
# (fitted to their box) and a numeric one, a north arrow following the map, and an overview map
# outlining the main map's extent. QGIS's own export is written to `renders/` for comparing.
def layout_surrounds():
from qgis.core import QgsLayoutItemPage, QgsLayoutItemScaleBar, QgsLayoutItemMapOverview, QgsLayoutExporter, QgsFillSymbol, QgsTextFormat
from qgis.PyQt.QtGui import QFont
mm = Qgis.LayoutUnit.Millimeters
p = new_project()
p.relationManager().setPolymorphicRelations([])
p.setTitle("Surrounds")
pts, polys = layer("points"), layer("polygons")
p.addMapLayers([pts, polys])
lay = QgsPrintLayout(p)
lay.initializeDefaults()
lay.setName("Surrounds")
lay.pageCollection().page(0).setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape)
m = QgsLayoutItemMap(lay)
lay.addLayoutItem(m)
m.attemptMove(QgsLayoutPoint(10, 10, mm))
m.attemptResize(QgsLayoutSize(180, 130, mm))
m.setExtent(QgsRectangle(2696300, 1261200, 2698000, 1262475))
m.setFrameEnabled(True)
ov = QgsLayoutItemMap(lay)
lay.addLayoutItem(ov)
ov.attemptMove(QgsLayoutPoint(200, 10, mm))
ov.attemptResize(QgsLayoutSize(85, 65, mm))
ov.setExtent(QgsRectangle(2694000, 1259500, 2700000, 1264000))
ov.setFrameEnabled(True)
o = QgsLayoutItemMapOverview("Overview", ov)
ov.overviews().addOverview(o)
o.setLinkedMap(m)
o.setFrameSymbol(QgsFillSymbol.createSimple({"style": "no", "outline_color": "200,0,0,255", "outline_width": "0.6"}))
fmt = QgsTextFormat()
fmt.setFont(QFont("DejaVu Sans"))
fmt.setSize(9)
for i, style in enumerate(["Single Box", "Line Ticks Up", "stepped"]):
sb = QgsLayoutItemScaleBar(lay)
lay.addLayoutItem(sb)
sb.setLinkedMap(m)
sb.setStyle(style)
sb.setTextFormat(fmt)
sb.setUnits(Qgis.DistanceUnit.Meters)
sb.setUnitLabel("m")
sb.setNumberOfSegments(4)
sb.setNumberOfSegmentsLeft(0)
sb.setSegmentSizeMode(Qgis.ScaleBarSegmentSizeMode.FitWidth)
sb.setMinimumBarWidth(50)
sb.setMaximumBarWidth(60)
sb.attemptMove(QgsLayoutPoint(10 + i * 80, 150, mm))
sb.attemptResize(QgsLayoutSize(60, 15, mm))
num = QgsLayoutItemScaleBar(lay)
lay.addLayoutItem(num)
num.setLinkedMap(m)
num.setStyle("Numeric")
num.setTextFormat(fmt)
num.attemptMove(QgsLayoutPoint(10, 175, mm))
num.attemptResize(QgsLayoutSize(60, 10, mm))
na = QgsLayoutItemPicture(lay)
lay.addLayoutItem(na)
na.setLinkedMap(m)
na.setNorthMode(QgsLayoutItemPicture.NorthMode.GridNorth)
na.setPicturePath(":/images/north_arrows/layout_default_north_arrow.svg")
na.attemptMove(QgsLayoutPoint(230, 90, mm))
na.attemptResize(QgsLayoutSize(20, 25, mm))
p.layoutManager().addLayout(lay)
save_project(p, "layout-surrounds")
os.makedirs(os.path.join(OUT, "renders"), exist_ok=True)
settings = QgsLayoutExporter.ImageExportSettings()
settings.dpi = 96
QgsLayoutExporter(lay).exportToImage(os.path.join(OUT, "renders", "Surrounds.png"), settings)


attempt("layout surrounds", layout_surrounds)
attempt("all styles project", all_styles)


Expand Down
Loading
Loading