cartography 0.11.0

Cartography is a map rendering library for Geographic features expressed using [georust](https://georust.org/) libraries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! YAML style loader for cartography-rs
//!
//! Provides a way to load rendering styles from YAML files instead of hardcoding them in Rust.

use std::{path::Path, sync::Arc};

use serde::Deserialize;

use crate::{
  Result,
  styling::{self, LabelConfig, Style, StyleBuilder, SymbolColor},
};

mod color;
mod filter;

pub use color::parse_hex_color;

/// YAML style configuration
#[derive(Debug, Deserialize)]
pub struct YamlStyle
{
  /// Background color (CSS hex format: #rrggbb or #rrggbbaa)
  #[serde(default)]
  pub background: Option<String>,
  /// Rendering rules
  #[serde(default)]
  pub rules: Vec<YamlRule>,
}

/// YAML rule configuration
#[derive(Debug, Deserialize)]
pub struct YamlRule
{
  /// Filter criteria for this rule
  pub filter: YamlFilter,
  /// Symbol/rendering properties for matching features
  pub symbol: YamlSymbol,
}

/// Value of a tag
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum TagValue
{
  /// String
  String(String),
  /// Sequence
  Sequence(Vec<String>),
}

/// YAML geometry filter
#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum YamlGeometry
{
  /// Point geometry
  Point,
  /// LineString geometry
  Linestring,
  /// Polygon geometry
  Polygon,
  /// MultiPolygon geometry
  Multipolygon,
}

/// YAML filter configuration
#[derive(Debug, Deserialize)]
pub struct YamlFilter
{
  /// Geometry type filter
  #[serde(default)]
  pub geometry: Option<YamlGeometry>,
  /// Tag filter: key -> value(s) with AND semantics across keys, OR semantics for values
  #[serde(default)]
  pub tag: Option<std::collections::HashMap<String, TagValue>>,
  /// Minimum zoom level for this rule
  #[serde(default)]
  pub min_zoom: Option<f64>,
  /// Maximum zoom level for this rule
  #[serde(default)]
  pub max_zoom: Option<f64>,
}

/// YAML symbol configuration
#[derive(Debug, Deserialize)]
pub struct YamlSymbol
{
  /// Fill color (CSS hex format)
  #[serde(default)]
  pub fill: Option<String>,
  /// Stroke color (CSS hex format)
  #[serde(default)]
  pub stroke: Option<String>,
  /// Stroke width in pixels
  #[serde(default)]
  pub stroke_width: Option<f64>,
  /// Point radius in pixels
  #[serde(default)]
  pub radius: Option<f64>,
  /// Optional icon path, relative to the style file.
  #[serde(default)]
  pub icon: Option<String>,
  /// Icon size in pixels (screen-space).
  #[serde(default)]
  pub icon_size: Option<f64>,
  /// Icon anchor: center | top-left | bottom-center.
  #[serde(default)]
  pub icon_anchor: Option<String>,
  /// Optional text label
  #[serde(default)]
  pub label: Option<YamlLabel>,
}

/// YAML label configuration
#[derive(Debug, Deserialize)]
pub struct YamlLabel
{
  /// OSM tag field used as label text
  pub field: String,
  /// Label font size in pixels
  #[serde(default)]
  pub font_size: Option<f32>,
  /// Label text color (CSS hex format)
  #[serde(default)]
  pub color: Option<String>,
  /// Label halo color (CSS hex format)
  #[serde(default)]
  pub halo_color: Option<String>,
  /// Minimum zoom level at which to display labels
  #[serde(default)]
  pub min_zoom: Option<f64>,
}

/// Load a style from a YAML file
///
/// # Arguments
///
/// * `path` - Path to the YAML style file
///
/// # Returns
///
/// A `Style<OsmFeature>` that can be used for rendering
pub fn load_style(path: impl AsRef<Path>) -> Result<Style<crate::osm::OsmFeature>>
{
  let path = path.as_ref();
  let yaml_str = std::fs::read_to_string(path)?;
  let yaml_style: YamlStyle = serde_saphyr::from_str(&yaml_str)?;
  let style_dir = path.parent().unwrap_or_else(|| Path::new("."));

  let mut builder = StyleBuilder::new();

  if let Some(bg_color) = &yaml_style.background
  {
    let rgba = parse_hex_color(bg_color)?;
    builder = builder.set_background_color(rgba);
  }

  for rule in yaml_style.rules
  {
    builder = add_rule_to_builder(builder, rule, style_dir)?;
  }

  Ok(builder.into())
}

fn add_rule_to_builder(
  builder: StyleBuilder<crate::osm::OsmFeature>,
  rule: YamlRule,
  style_dir: &Path,
) -> Result<StyleBuilder<crate::osm::OsmFeature>>
{
  let symbol = build_symbol(&rule.symbol, style_dir)?;
  let checker = filter::compile_filter(&rule.filter);
  Ok(builder.add_rule(symbol).check(checker).finish_rule())
}

fn build_symbol(
  yaml_symbol: &YamlSymbol,
  style_dir: &Path,
) -> Result<styling::Symbol<crate::osm::OsmFeature>>
{
  let fill_color = if let Some(fill_str) = &yaml_symbol.fill
  {
    let rgba = parse_hex_color(fill_str)?;
    SymbolColor::new(move |_, _| rgba)
  }
  else
  {
    styling::Rgba::TRANSPARENT.into()
  };

  let stroke_color = if let Some(stroke_str) = &yaml_symbol.stroke
  {
    let rgba = parse_hex_color(stroke_str)?;
    SymbolColor::new(move |_, _| rgba)
  }
  else
  {
    styling::Rgba::BLACK.into()
  };

  let stroke_width = yaml_symbol.stroke_width.unwrap_or(0.0);
  let radius = yaml_symbol.radius.unwrap_or(1.0);
  let icon = if let Some(icon_str) = &yaml_symbol.icon
  {
    let size = yaml_symbol.icon_size.unwrap_or(24.0) as f32;
    let anchor = match yaml_symbol.icon_anchor.as_deref()
    {
      Some("top-left") => styling::IconAnchor::TopLeft,
      Some("bottom-center") => styling::IconAnchor::BottomCenter,
      _ => styling::IconAnchor::Center,
    };
    #[cfg(feature = "image")]
    {
      let icon_path = style_dir.join(icon_str);
      let image = crate::open_image(
        &icon_path,
        geo::Rect::new(
          geo::coord! { x: 0.0, y: 0.0 },
          geo::coord! { x: 1.0, y: 1.0 },
        ),
      )?;
      Some(styling::IconConfig {
        image: Arc::new(image),
        size,
        anchor,
      })
    }
    #[cfg(not(feature = "image"))]
    {
      let _ = (style_dir, size, anchor);
      return Err(anyhow::anyhow!(
        "symbol.icon requires the `image` feature (icon: {icon_str})"
      ));
    }
  }
  else
  {
    None
  };
  let label = yaml_symbol.label.as_ref().map(build_label).transpose()?;

  Ok(styling::Symbol {
    fill_color,
    stroke_color,
    stroke_width,
    radius,
    icon,
    label,
  })
}

fn build_label(yaml_label: &YamlLabel) -> Result<LabelConfig<crate::osm::OsmFeature>>
{
  let field = yaml_label.field.clone();
  let font_size = yaml_label.font_size.unwrap_or(12.0);

  let color = if let Some(color_str) = &yaml_label.color
  {
    parse_hex_color(color_str)?
  }
  else
  {
    styling::Rgba::BLACK
  };

  let halo_color = if let Some(halo_str) = &yaml_label.halo_color
  {
    parse_hex_color(halo_str)?
  }
  else
  {
    styling::Rgba::WHITE
  };

  Ok(LabelConfig {
    text: std::sync::Arc::new(Box::new(move |feature: &crate::osm::OsmFeature| {
      feature.tag(&field).map(str::to_owned)
    })),
    font_size,
    color: color.into(),
    halo_color: halo_color.into(),
    min_zoom: yaml_label.min_zoom.unwrap_or(0.0),
  })
}

#[cfg(test)]
mod tests
{
  use super::*;
  use std::{fs, time::SystemTime};

  #[test]
  fn test_parse_hex_color_6_digits()
  {
    let color = parse_hex_color("#ff0000").unwrap();
    assert!((color.red() - 1.0).abs() < 0.01);
    assert!((color.green() - 0.0).abs() < 0.01);
    assert!((color.blue() - 0.0).abs() < 0.01);
    assert!((color.alpha() - 1.0).abs() < 0.01);
  }

  #[test]
  fn test_parse_hex_color_8_digits()
  {
    let color = parse_hex_color("#ff000080").unwrap();
    assert!((color.red() - 1.0).abs() < 0.01);
    assert!((color.green() - 0.0).abs() < 0.01);
    assert!((color.blue() - 0.0).abs() < 0.01);
    assert!((color.alpha() - 0.5).abs() < 0.01);
  }

  #[test]
  fn test_parse_hex_color_invalid()
  {
    assert!(parse_hex_color("red").is_err());
    assert!(parse_hex_color("#ffff").is_err());
    assert!(parse_hex_color("#gggggg").is_err());
  }

  #[test]
  fn test_yaml_deserialize()
  {
    let yaml_str = "background: \"#aad3df\"\nrules:\n  - filter:\n      geometry: polygon\n      tag:\n        natural: water\n      min_zoom: 8\n    symbol:\n      fill: \"#4a90d9\"\n      stroke: \"#2c6fad\"\n      stroke_width: 0.5\n      label:\n        field: name\n        font_size: 11";

    let style: YamlStyle = serde_saphyr::from_str(yaml_str).unwrap();
    assert_eq!(style.background, Some("#aad3df".to_string()));
    assert_eq!(style.rules.len(), 1);
    assert_eq!(style.rules[0].filter.geometry, Some(YamlGeometry::Polygon));
    assert_eq!(style.rules[0].filter.min_zoom, Some(8.0));
    assert_eq!(
      style.rules[0]
        .symbol
        .label
        .as_ref()
        .map(|label| label.field.as_str()),
      Some("name")
    );
  }

  #[test]
  fn test_build_symbol_label_text()
  {
    let yaml_symbol: YamlSymbol =
      serde_saphyr::from_str("fill: \"#4a90d9\"\nlabel:\n  field: name\n  min_zoom: 5").unwrap();
    let symbol = build_symbol(&yaml_symbol, Path::new(".")).unwrap();
    let label = symbol.label.as_ref().unwrap();
    let feature = crate::osm::OsmFeature {
      id: 1,
      geometry: geo::Geometry::Point(geo::Point::new(0.0, 0.0)),
      tags: vec![("name".to_string(), "Paris".to_string())],
    };
    assert_eq!((label.text)(&feature), Some("Paris".to_string()));
    assert_eq!(label.min_zoom, 5.0);
  }

  #[test]
  fn test_yaml_symbol_with_icon_deserializes()
  {
    let yaml = "icon: \"assets/test.png\"\nicon_size: 32";
    let sym: YamlSymbol = serde_saphyr::from_str(yaml).unwrap();
    assert_eq!(sym.icon, Some("assets/test.png".to_string()));
    assert_eq!(sym.icon_size, Some(32.0));
  }

  #[cfg(feature = "image")]
  #[test]
  fn test_icon_config_loads_from_style()
  {
    let uniq = SystemTime::now()
      .duration_since(SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_nanos();
    let base_dir = std::env::temp_dir().join(format!("cartography_style_icon_{uniq}"));
    let icon_dir = base_dir.join("assets");
    let style_path = base_dir.join("style.yaml");
    let icon_path = icon_dir.join("test.png");
    fs::create_dir_all(&icon_dir).unwrap();
    let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
    img.save(&icon_path).unwrap();

    let style = "rules:\n  - filter:\n      geometry: point\n    symbol:\n      icon: \"assets/test.png\"\n      icon_size: 32\n      fill: \"#ff0000\"";
    fs::write(&style_path, style).unwrap();

    let loaded = load_style(&style_path).unwrap();
    let first_rule = loaded.rules().next().unwrap();
    let icon = first_rule.symbol.icon.as_ref().unwrap();
    assert_eq!(icon.size, 32.0);
    assert_eq!(icon.anchor, styling::IconAnchor::Center);

    fs::remove_file(&style_path).unwrap();
    fs::remove_file(&icon_path).unwrap();
    fs::remove_dir_all(&base_dir).unwrap();
  }

  #[cfg(feature = "image")]
  #[test]
  fn test_style_with_missing_icon_returns_error()
  {
    let uniq = SystemTime::now()
      .duration_since(SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_nanos();
    let base_dir = std::env::temp_dir().join(format!("cartography_style_icon_missing_{uniq}"));
    let style_path = base_dir.join("style.yaml");
    fs::create_dir_all(&base_dir).unwrap();

    let style = "rules:\n  - filter:\n      geometry: point\n    symbol:\n      icon: \"assets/does-not-exist.png\"";
    fs::write(&style_path, style).unwrap();

    let result = load_style(&style_path);
    assert!(result.is_err());

    fs::remove_file(&style_path).unwrap();
    fs::remove_dir_all(&base_dir).unwrap();
  }
}