egui-map-view 0.6.3

An slippy map viewer for egui applications.
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
//! A layer for placing text on the map.

use crate::layers::{Layer, default_opacity, serde_color32};
use crate::projection::{GeoPos, MapProjection};
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Response};
use serde::{Deserialize, Serialize};
use std::any::Any;

/// The size of the text.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum TextSize {
    /// Size is in screen points, and does not scale with zoom.
    Static(f32),

    /// Size is in meters at the equator, and scales with zoom.
    Relative(f32),
}

impl Default for TextSize {
    fn default() -> Self {
        // A reasonable default.
        Self::Static(12.0)
    }
}

/// A piece of text on the map.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Text {
    /// The text to display.
    pub text: String,

    /// The geographical position of the text.
    pub pos: GeoPos,

    /// The size of the text.
    pub size: TextSize,

    /// The color of the text.
    #[serde(with = "serde_color32")]
    pub color: Color32,

    /// The color of the background.
    #[serde(with = "serde_color32")]
    pub background: Color32,
}

impl Default for Text {
    fn default() -> Self {
        Self {
            text: "New Text".to_string(),
            pos: GeoPos { lon: 0.0, lat: 0.0 }, // This will be updated on click.
            size: TextSize::default(),
            color: Color32::BLACK,
            background: Color32::from_rgba_unmultiplied(255, 255, 255, 180),
        }
    }
}

/// The state of the text currently being edited or added.
#[derive(Clone, Debug)]
pub struct EditingText {
    /// The index of the text being edited, if it's an existing one.
    pub index: Option<usize>,
    /// The properties of the text being edited.
    pub properties: Text,
}

/// The mode of the `TextLayer`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextLayerMode {
    /// The layer is not interactive.
    #[default]
    Disabled,
    /// The user can add, remove, and modify text elements.
    Modify,
}

/// Layer implementation that allows placing text on the map.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TextLayer {
    texts: Vec<Text>,

    /// The current mode.
    #[serde(skip)]
    pub mode: TextLayerMode,

    /// The properties for the next text to be added.
    #[serde(skip)]
    pub new_text_properties: Text,

    /// The state of the text currently being edited or added.
    #[serde(skip)]
    pub editing: Option<EditingText>,

    #[serde(skip)]
    dragged_text_index: Option<usize>,

    /// The opacity of the layer.
    #[serde(default = "default_opacity")]
    pub opacity: f32,
}

impl Default for TextLayer {
    fn default() -> Self {
        Self {
            texts: Vec::new(),
            mode: TextLayerMode::default(),
            new_text_properties: Text::default(),
            editing: None,
            dragged_text_index: None,
            opacity: 1.0,
        }
    }
}

impl TextLayer {
    /// Starts editing an existing text element.
    pub fn start_editing(&mut self, index: usize) {
        if let Some(text) = self.texts.get(index) {
            self.editing = Some(EditingText {
                index: Some(index),
                properties: text.clone(),
            });
        }
    }

    /// Deletes a text element.
    pub fn delete(&mut self, index: usize) {
        if index < self.texts.len() {
            self.texts.remove(index);
        }
    }

    /// Saves the changes made in the editing dialog.
    pub fn commit_edit(&mut self) {
        if let Some(editing) = self.editing.take() {
            if let Some(index) = editing.index {
                // It's an existing text.
                if let Some(text) = self.texts.get_mut(index) {
                    *text = editing.properties;
                }
            } else {
                // It's a new text.
                self.texts.push(editing.properties);
            }
        }
    }

    /// Discards the changes made in the editing dialog.
    pub fn cancel_edit(&mut self) {
        self.editing = None;
    }

    /// Serializes the layer to a `GeoJSON` `FeatureCollection`.
    #[cfg(feature = "geojson")]
    pub fn to_geojson_str(&self) -> Result<String, serde_json::Error> {
        let features: Vec<geojson::Feature> = self
            .texts
            .clone()
            .into_iter()
            .map(geojson::Feature::from)
            .collect();
        let mut foreign_members = serde_json::Map::new();
        foreign_members.insert(
            "opacity".to_string(),
            serde_json::Value::from(f64::from(self.opacity)),
        );

        let feature_collection = geojson::FeatureCollection {
            bbox: None,
            features,
            foreign_members: Some(foreign_members),
        };
        serde_json::to_string(&feature_collection)
    }

    /// Deserializes a `GeoJSON` `FeatureCollection` and adds the features to the layer.
    #[cfg(feature = "geojson")]
    pub fn from_geojson_str(&mut self, s: &str) -> Result<(), serde_json::Error> {
        let feature_collection: geojson::FeatureCollection = serde_json::from_str(s)?;
        let new_texts: Vec<Text> = feature_collection
            .features
            .into_iter()
            .filter_map(|f| Text::try_from(f).ok())
            .collect();
        self.texts.extend(new_texts);

        if let Some(foreign_members) = feature_collection.foreign_members
            && let Some(value) = foreign_members.get("opacity")
            && let Some(opacity) = value.as_f64()
        {
            self.opacity = opacity as f32;
        }
        Ok(())
    }

    fn handle_modify_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        if self.editing.is_some() {
            // While editing in a dialog, we don't want to interact with the map.
            // We consume all hover events to prevent panning and zooming.
            return response.hovered();
        }

        if response.drag_started()
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            self.dragged_text_index = self.find_text_at(pointer_pos, projection, &response.ctx);
        }

        if response.dragged()
            && let Some(text_index) = self.dragged_text_index
            && let Some(text) = self.texts.get_mut(text_index)
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            text.pos = projection.unproject(pointer_pos);
        }

        if response.drag_stopped() {
            self.dragged_text_index = None;
        }

        // Change cursor on hover
        if self.dragged_text_index.is_some() {
            response.ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
        } else if let Some(hover_pos) = response.hover_pos() {
            if self
                .find_text_at(hover_pos, projection, &response.ctx)
                .is_some()
            {
                response.ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
            } else {
                response.ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
            }
        }

        if !response.dragged() && response.clicked() {
            // Left-click to add or edit a text element
            if let Some(pointer_pos) = response.interact_pointer_pos() {
                if let Some(index) = self.find_text_at(pointer_pos, projection, &response.ctx) {
                    // Clicked on an existing text, start editing it.
                    self.start_editing(index);
                } else {
                    // Clicked on an empty spot, start adding a new text.
                    let geo_pos = projection.unproject(pointer_pos);
                    let mut properties = self.new_text_properties.clone();
                    properties.pos = geo_pos;
                    self.editing = Some(EditingText {
                        index: None,
                        properties,
                    });
                }
            }
        }

        response.hovered()
    }

    /// A more robust check that considers the text's bounding box.
    fn find_text_at(
        &self,
        screen_pos: Pos2,
        projection: &MapProjection,
        ctx: &egui::Context,
    ) -> Option<usize> {
        self.texts.iter().enumerate().rev().find_map(|(i, text)| {
            let text_rect = self.get_text_rect(text, projection, ctx);
            if text_rect.expand(5.0).contains(screen_pos) {
                // Add some tolerance
                Some(i)
            } else {
                None
            }
        })
    }
}

impl Layer for TextLayer {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn opacity(&self) -> f32 {
        self.opacity
    }

    fn set_opacity(&mut self, opacity: f32) {
        self.opacity = opacity;
    }

    fn handle_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        match self.mode {
            TextLayerMode::Disabled => false,
            TextLayerMode::Modify => self.handle_modify_input(response, projection),
        }
    }

    fn draw(&self, painter: &Painter, projection: &MapProjection) {
        for text in &self.texts {
            let screen_pos = projection.project(text.pos);

            let galley = painter.layout_no_wrap(
                // We use the painter's layout function here for drawing.
                text.text.clone(),
                FontId::proportional(self.get_font_size(text, projection)),
                text.color.gamma_multiply(self.opacity),
            );

            let rect =
                Align2::CENTER_CENTER.anchor_rect(Rect::from_min_size(screen_pos, galley.size()));

            painter.rect_filled(
                rect.expand(2.0),
                3.0,
                text.background.gamma_multiply(self.opacity),
            );
            painter.galley(rect.min, galley, Color32::TRANSPARENT);
        }
    }
}

impl TextLayer {
    fn get_font_size(&self, text: &Text, projection: &MapProjection) -> f32 {
        match text.size {
            TextSize::Static(size) => size,
            TextSize::Relative(size_in_meters) => {
                let p2 = projection.project(GeoPos {
                    lon: text.pos.lon
                        + (f64::from(size_in_meters)
                            / (111_320.0 * text.pos.lat.to_radians().cos())),
                    lat: text.pos.lat,
                });
                (p2.x - projection.project(text.pos).x).abs()
            }
        }
    }

    fn get_text_rect(&self, text: &Text, projection: &MapProjection, ctx: &egui::Context) -> Rect {
        let font_size = self.get_font_size(text, projection);
        let galley = ctx
            .debug_painter()
            .layout_job(egui::text::LayoutJob::simple(
                text.text.clone(),
                FontId::proportional(font_size),
                text.color,
                f32::INFINITY,
            ));
        let screen_pos = projection.project(text.pos);
        Align2::CENTER_CENTER.anchor_rect(Rect::from_min_size(screen_pos, galley.size()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn text_layer_serde() {
        let mut layer = TextLayer {
            mode: TextLayerMode::Modify,
            ..TextLayer::default()
        };
        layer.texts.push(Text {
            text: "Hello".to_string(),
            pos: GeoPos { lon: 1.0, lat: 2.0 },
            size: TextSize::Static(14.0),
            color: Color32::from_rgb(0, 0, 255),
            background: Color32::from_rgba_unmultiplied(255, 0, 0, 128),
        });

        let json = serde_json::to_string(&layer).unwrap();

        // The serialized string should only contain texts.
        assert!(json.contains(r##""texts":[{"text":"Hello","pos":{"lon":1.0,"lat":2.0},"size":{"Static":14.0},"color":"#0000ffff","background":"#ff000080""##));

        // it should not contain skipped fields
        assert!(!json.contains("mode"));
        assert!(!json.contains("new_text_properties"));
        assert!(!json.contains("editing"));
        assert!(!json.contains("dragged_text_index"));

        let deserialized: TextLayer = serde_json::from_str(&json).unwrap();

        // Check that texts are restored correctly.
        assert_eq!(deserialized.texts.len(), 1);
        assert_eq!(deserialized.texts[0].text, "Hello");
        assert_eq!(deserialized.texts[0].pos, GeoPos { lon: 1.0, lat: 2.0 });
        assert_eq!(deserialized.texts[0].size, TextSize::Static(14.0));
        assert_eq!(deserialized.texts[0].color, Color32::from_rgb(0, 0, 255));
        assert_eq!(
            deserialized.texts[0].background,
            Color32::from_rgba_unmultiplied(255, 0, 0, 128)
        );

        // Check that skipped fields have their values from the `default()` implementation.
        let default_layer = TextLayer::default();
        assert_eq!(deserialized.mode, default_layer.mode);
        assert_eq!(
            deserialized.new_text_properties,
            default_layer.new_text_properties
        );
        assert!(deserialized.editing.is_none());
        assert!(deserialized.dragged_text_index.is_none());
    }

    #[cfg(feature = "geojson")]
    mod geojson_tests {
        use super::*;

        #[test]
        fn text_layer_geojson() {
            let mut layer = TextLayer::default();
            layer.texts.push(Text {
                text: "Hello".to_string(),
                pos: (10.0, 20.0).into(),
                size: TextSize::Static(14.0),
                color: Color32::from_rgb(0, 0, 255),
                background: Color32::from_rgba_unmultiplied(255, 0, 0, 128),
            });

            let geojson_str = layer.to_geojson_str().unwrap();
            let mut new_layer = TextLayer::default();
            new_layer.from_geojson_str(&geojson_str).unwrap();

            assert_eq!(new_layer.texts.len(), 1);
            assert_eq!(layer.texts[0], new_layer.texts[0]);
        }
    }
}