omap 0.6.1

Interact with or write new Open Orienteering Mapper omap-files
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use std::str::FromStr;

use geo_types::Coord;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::{Reader, Writer};

use crate::colors::Argb;
use crate::templates::Templates;
use crate::utils::{self, UnitF64, parse_attr_raw, try_get_attr_raw};
use crate::{Error, NonNegativeF64, Result};

/// Visibility settings for a template or the map layer.
#[derive(Debug, Clone, Copy)]
pub struct TemplateVisibility {
    /// Opacity from 0.0 (invisible) to 1.0 (opaque).
    pub opacity: UnitF64,
    /// Whether this layer is visible.
    pub visible: bool,
}

impl Default for TemplateVisibility {
    fn default() -> Self {
        Self {
            opacity: UnitF64::one(),
            visible: false,
        }
    }
}

impl TemplateVisibility {
    fn parse_map_attrs(bs: &BytesStart<'_>) -> Self {
        let mut tv = Self::default();
        for attr in bs.attributes().filter_map(std::result::Result::ok) {
            match attr.key.local_name().as_ref() {
                b"opacity" => {
                    tv.opacity = UnitF64::clamped_from(
                        parse_attr_raw(attr.value).unwrap_or(tv.opacity.get()),
                    )
                }
                b"visible" => tv.visible = attr.as_bool().unwrap_or(tv.visible),
                _ => (),
            }
        }
        tv
    }
}

/// How the grid is displayed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridDisplay {
    /// Grid is hidden.
    #[default]
    Hidden = 0,
    /// All grid lines are shown.
    AllLines = 1,
    /// Only horizontal lines are shown.
    HorizontalLines = 2,
    /// Only vertical lines are shown.
    VerticalLines = 3,
}

impl FromStr for GridDisplay {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "0" => Ok(GridDisplay::Hidden),
            "1" => Ok(GridDisplay::AllLines),
            "2" => Ok(GridDisplay::HorizontalLines),
            "3" => Ok(GridDisplay::VerticalLines),
            _ => Err(Error::ViewError),
        }
    }
}

impl From<u8> for GridDisplay {
    fn from(value: u8) -> GridDisplay {
        match value {
            1 => GridDisplay::AllLines,
            2 => GridDisplay::HorizontalLines,
            3 => GridDisplay::VerticalLines,
            _ => GridDisplay::Hidden,
        }
    }
}

impl AsRef<str> for GridDisplay {
    fn as_ref(&self) -> &str {
        match self {
            GridDisplay::Hidden => "0",
            GridDisplay::AllLines => "1",
            GridDisplay::HorizontalLines => "2",
            GridDisplay::VerticalLines => "3",
        }
    }
}

/// Grid alignment reference direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridAlignment {
    /// Aligned to magnetic north.
    #[default]
    MagneticNorth = 0,
    /// Aligned to grid north.
    GridNorth = 1,
    /// Aligned to true north.
    TrueNorth = 2,
}

impl FromStr for GridAlignment {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "0" => Ok(GridAlignment::MagneticNorth),
            "1" => Ok(GridAlignment::GridNorth),
            "2" => Ok(GridAlignment::TrueNorth),
            _ => Err(Error::ViewError),
        }
    }
}

impl From<u8> for GridAlignment {
    fn from(value: u8) -> GridAlignment {
        match value {
            1 => GridAlignment::GridNorth,
            2 => GridAlignment::TrueNorth,
            _ => GridAlignment::MagneticNorth,
        }
    }
}

impl AsRef<str> for GridAlignment {
    fn as_ref(&self) -> &str {
        match self {
            Self::MagneticNorth => "0",
            Self::GridNorth => "1",
            Self::TrueNorth => "2",
        }
    }
}

/// Grid spacing unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridUnit {
    /// Meters on the ground.
    #[default]
    MetersOnGround = 0,
    /// Millimetres on the map.
    MillimetresOnMap = 1,
    /// Pixels on screen.
    PixelsOnScreen = 2,
}

impl FromStr for GridUnit {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "0" => Ok(GridUnit::MetersOnGround),
            "1" => Ok(GridUnit::MillimetresOnMap),
            "2" => Ok(GridUnit::PixelsOnScreen),
            _ => Err(Error::ViewError),
        }
    }
}

impl From<u8> for GridUnit {
    fn from(value: u8) -> GridUnit {
        match value {
            1 => GridUnit::MillimetresOnMap,
            2 => GridUnit::PixelsOnScreen,
            _ => GridUnit::MetersOnGround,
        }
    }
}

impl AsRef<str> for GridUnit {
    fn as_ref(&self) -> &str {
        match self {
            GridUnit::MetersOnGround => "0",
            GridUnit::MillimetresOnMap => "1",
            GridUnit::PixelsOnScreen => "2",
        }
    }
}

/// The map grid display settings.
#[derive(Debug, Clone)]
pub struct Grid {
    /// Rgb Grid colour parsed from a hex string, e.g. `"#646464"`.
    pub color: Argb,
    /// Display mode.
    pub display: GridDisplay,
    /// Grid alignment reference direction.
    pub alignment: GridAlignment,
    /// Additional rotation in radians.
    pub additional_rotation: f64,
    /// Grid spacing unit.
    pub unit: GridUnit,
    /// Horizontal spacing.
    pub h_spacing: f64,
    /// Vertical spacing.
    pub v_spacing: f64,
    /// Horizontal offset.
    pub h_offset: f64,
    /// Vertical offset.
    pub v_offset: f64,
    /// Whether snapping to the grid is enabled.
    pub snapping_enabled: bool,
}

impl Default for Grid {
    fn default() -> Self {
        Self {
            color: Argb {
                a: UnitF64::one(),
                r: UnitF64::clamped_from(100. / 255.),
                g: UnitF64::clamped_from(100. / 255.),
                b: UnitF64::clamped_from(100. / 255.),
            },
            display: Default::default(),
            alignment: Default::default(),
            additional_rotation: 0.0,
            unit: Default::default(),
            h_spacing: 500.0,
            v_spacing: 500.0,
            h_offset: 0.0,
            v_offset: 0.0,
            snapping_enabled: false,
        }
    }
}

impl Grid {
    fn parse_attrs(bs: &BytesStart<'_>) -> Self {
        let mut g = Self::default();
        for attr in bs.attributes().filter_map(std::result::Result::ok) {
            match attr.key.local_name().as_ref() {
                b"color" => g.color = parse_attr_raw(attr.value).unwrap_or(g.color),
                b"display" => g.display = parse_attr_raw(attr.value).unwrap_or(g.display),
                b"alignment" => g.alignment = parse_attr_raw(attr.value).unwrap_or(g.alignment),
                b"unit" => g.unit = parse_attr_raw(attr.value).unwrap_or(g.unit),
                b"additional_rotation" => {
                    g.additional_rotation =
                        parse_attr_raw(attr.value).unwrap_or(g.additional_rotation)
                }
                b"h_spacing" => g.h_spacing = parse_attr_raw(attr.value).unwrap_or(g.h_spacing),
                b"v_spacing" => g.v_spacing = parse_attr_raw(attr.value).unwrap_or(g.v_spacing),
                b"h_offset" => g.h_offset = parse_attr_raw(attr.value).unwrap_or(g.h_offset),
                b"v_offset" => g.v_offset = parse_attr_raw(attr.value).unwrap_or(g.v_offset),
                b"snapping_enabled" => {
                    g.snapping_enabled = attr.as_bool().unwrap_or(g.snapping_enabled)
                }
                _ => (),
            }
        }
        g
    }

    fn write<W: std::io::Write>(&self, writer: &mut Writer<W>) -> Result<()> {
        writer.write_event(Event::Empty(BytesStart::new("grid").with_attributes([
            ("color", self.color.to_string().as_str()),
            ("display", self.display.as_ref()),
            ("alignment", self.alignment.as_ref()),
            (
                "additional_rotation",
                self.additional_rotation.to_string().as_str(),
            ),
            ("unit", self.unit.as_ref()),
            ("h_spacing", self.h_spacing.to_string().as_str()),
            ("v_spacing", self.v_spacing.to_string().as_str()),
            ("h_offset", self.h_offset.to_string().as_str()),
            ("v_offset", self.v_offset.to_string().as_str()),
            (
                "snapping_enabled",
                self.snapping_enabled.to_string().as_str(),
            ),
        ])))?;
        Ok(())
    }
}

/// The view onto the map, including zoom, position, rotation, grid settings,
/// and visibility of the map layer and templates.
#[derive(Debug, Clone)]
pub struct View {
    /// Grid display settings.
    pub grid: Grid,
    /// Zoom factor.
    pub zoom: NonNegativeF64,
    /// View rotation in radians (counter-clockwise).
    pub rotation: f64,
    /// Horizontal position of the view centre (in mm map coordinates).
    pub view_centre: Coord,
    /// Visibility of the map drawing itself.
    pub map_visibility: TemplateVisibility,
    /// Whether all templates are hidden in this view.
    pub all_templates_hidden: bool,
    /// Whether the grid is visible.
    pub grid_visible: bool,
    /// Whether overprinting simulation is enabled.
    pub overprinting_simulation_enabled: bool,
    /// Render hatched polygons for the area objects
    pub area_hatching_enabled: bool,
    /// Render only baselines for the objects
    pub baseline_view_enabled: bool,
}

impl Default for View {
    fn default() -> Self {
        Self {
            grid: Grid::default(),
            zoom: NonNegativeF64::one(),
            rotation: 0.0,
            view_centre: Coord::zero(),
            map_visibility: TemplateVisibility {
                opacity: UnitF64::one(),
                visible: true,
            },
            all_templates_hidden: false,
            grid_visible: false,
            overprinting_simulation_enabled: false,
            area_hatching_enabled: false,
            baseline_view_enabled: false,
        }
    }
}

impl View {
    pub(crate) fn parse<R: std::io::BufRead>(
        reader: &mut Reader<R>,
        bs: &BytesStart<'_>,
        templates: &mut Templates,
    ) -> Result<Self> {
        let mut view = Self::default();
        let mut buf = Vec::new();

        view.area_hatching_enabled = try_get_attr_raw(bs, "area_hatching_enabled").unwrap_or(false);
        view.baseline_view_enabled = try_get_attr_raw(bs, "baseline_view_enabled").unwrap_or(false);

        loop {
            match reader.read_event_into(&mut buf)? {
                Event::Start(bs) => match bs.local_name().as_ref() {
                    b"grid" => view.grid = Grid::parse_attrs(&bs),
                    b"map_view" => view.parse_map_view(reader, &bs, templates)?,
                    _ => {}
                },
                Event::End(be) if be.local_name().as_ref() == b"view" => break,
                Event::Eof => break,
                _ => {}
            }
        }

        Ok(view)
    }

    fn parse_map_view<R: std::io::BufRead>(
        &mut self,
        reader: &mut Reader<R>,
        bs: &BytesStart<'_>,
        templates: &mut Templates,
    ) -> Result<()> {
        self.zoom = NonNegativeF64::clamped_from(try_get_attr_raw(bs, "zoom").unwrap_or(1.0));
        self.rotation = try_get_attr_raw(bs, "rotation").unwrap_or(0.0);
        self.view_centre.x =
            utils::from_file_value(try_get_attr_raw(bs, "position_x").unwrap_or(0));
        self.view_centre.y =
            utils::from_file_value(try_get_attr_raw(bs, "position_y").unwrap_or(0));

        let mut buf = Vec::new();
        loop {
            match reader.read_event_into(&mut buf)? {
                Event::Start(bs) => match bs.local_name().as_ref() {
                    b"map" => {
                        self.map_visibility = TemplateVisibility::parse_map_attrs(&bs);
                    }
                    b"templates" => {
                        if !templates.is_empty() {
                            self.parse_template_visibilities(reader, templates)?;
                        }
                    }
                    _ => {}
                },
                Event::End(be) if be.local_name().as_ref() == b"map_view" => break,
                Event::Eof => break,
                _ => {}
            }
        }

        Ok(())
    }

    fn parse_template_visibilities<R: std::io::BufRead>(
        &mut self,
        reader: &mut Reader<R>,
        templates: &mut Templates,
    ) -> Result<()> {
        let mut buf = Vec::new();
        loop {
            match reader.read_event_into(&mut buf)? {
                Event::Start(bs) if bs.local_name().as_ref() == b"ref" => {
                    if let Some(index) = try_get_attr_raw::<usize>(&bs, "template")
                        && index < templates.len()
                    {
                        templates.template_entries[index].visibilty =
                            TemplateVisibility::parse_map_attrs(&bs);
                    }
                }
                Event::End(be) if be.local_name().as_ref() == b"templates" => break,
                Event::Eof => break,
                _ => {}
            }
        }
        Ok(())
    }

    pub(crate) fn write<W: std::io::Write>(
        self,
        writer: &mut Writer<W>,
        visibilities: Vec<TemplateVisibility>,
    ) -> Result<()> {
        let mut bs = BytesStart::new("view");
        if self.area_hatching_enabled {
            bs.push_attribute(("area_hatching_enabled", "true"));
        }
        if self.baseline_view_enabled {
            bs.push_attribute(("baseline_view_enabled", "true"));
        }
        writer.write_event(Event::Start(bs))?;

        self.grid.write(writer)?;

        let position_x = utils::to_file_value(self.view_centre.x)?;
        let position_y = utils::to_file_value(self.view_centre.y)?;
        let mut mv = BytesStart::new("map_view").with_attributes([
            ("zoom", format!("{:.4}", self.zoom.get()).as_str()),
            ("position_x", position_x.to_string().as_str()),
            ("position_y", position_y.to_string().as_str()),
        ]);

        if self.rotation != 0.0 {
            mv.push_attribute(("rotation", format!("{:.4}", self.rotation).as_str()));
        }

        writer.write_event(Event::Start(mv))?;

        writer.write_event(Event::Empty(BytesStart::new("map").with_attributes([
            (
                "opacity",
                format!("{:.2}", self.map_visibility.opacity.get()).as_str(),
            ),
            ("visible", self.map_visibility.visible.to_string().as_str()),
        ])))?;

        if visibilities.is_empty() {
            writer.write_event(Event::Empty(
                BytesStart::new("templates").with_attributes([("count", "0")]),
            ))?;
        } else {
            writer
                .write_event(Event::Start(BytesStart::new("templates").with_attributes(
                    [("count", visibilities.len().to_string().as_str())],
                )))?;

            for (index, vis) in visibilities.into_iter().enumerate() {
                writer.write_event(Event::Empty(BytesStart::new("ref").with_attributes([
                    ("template", index.to_string().as_str()),
                    ("opacity", format!("{:.2}", vis.opacity.get()).as_str()),
                    ("visible", vis.visible.to_string().as_str()),
                ])))?;
            }
            writer.write_event(Event::End(BytesEnd::new("templates")))?;
        }

        // </map_view>
        writer.write_event(Event::End(BytesEnd::new("map_view")))?;

        // </view>
        writer.write_event(Event::End(BytesEnd::new("view")))?;

        Ok(())
    }
}