geolith 0.2.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! Names in the tiles, as the protomaps basemap schema carries them.
//!
//! The `@protomaps/basemaps` style draws a label with `get_multiline_name`
//! (and `get_country_name` for countries). It reads these attributes of a
//! feature, and no others:
//!
//! | Attribute | Meaning |
//! | --- | --- |
//! | `name` | the first script segment of the local name |
//! | `script` | its Unicode script, absent for `Latin` and `Generic` text |
//! | `name2`, `script2`, `name3`, `script3` | the second and third segment |
//! | `name:<lang>` | the name in one language of the allow-list ([`languages`]) |
//!
//! [`push_names`] writes them for a feature from OSM (`name`, `name:*`), from
//! Overture (`names.primary`, `names.common.*`) or from Natural Earth (`name`,
//! `name_*`). It ports `OsmNames.java` and `ScriptSegmenter.java` of
//! protomaps/basemaps, and applies the same rules to the other two sources.
//! The `pgf:` attributes of protomaps hold pre-shaped Devanagari glyphs for a
//! font bundle. Without that bundle protomaps writes none, and neither do we.

mod script;
mod segment;

pub use script::script_of;
pub use segment::segment_by_script;

use crate::source::input::{DataSource, InputFeature};
use crate::tile::feature::PropValue;

/// One language of the allow-list and the key it has in each source.
struct Lang {
    /// The tile attribute suffix: `en` for `name:en`.
    code: &'static str,
    /// The OSM tag, `name:en`.
    osm: &'static str,
    /// The flattened Overture property, `names.common.en`.
    overture: &'static str,
    /// The Natural Earth column, `name_en`.
    natural_earth: &'static str,
}

macro_rules! langs {
    ($($code:literal),+ $(,)?) => {
        [$(Lang {
            code: $code,
            osm: concat!("name:", $code),
            overture: concat!("names.common.", $code),
            natural_earth: concat!("name_", $code),
        }),+]
    };
}

/// The language allow-list of `OsmNames.ALLOWED_LANGS` in protomaps/basemaps.
///
/// Order is the order of the attributes in a tile. `zh` is not in the list:
/// it fills `zh-Hans` and `zh-Hant` when those are missing.
const ALLOWED: [Lang; 41] = langs![
    "ar", "cs", "bg", "da", "de", "el", "en", "es", "et", "fa", "fi", "fr", "ga", "he", "hi", "hr",
    "hu", "id", "it", "ja", "ko", "lt", "lv", "ne", "nl", "no", "mr", "mt", "pl", "pt", "ro", "ru",
    "sk", "sl", "sv", "tr", "uk", "ur", "vi", "zh-Hans", "zh-Hant",
];

/// The language codes of the allow-list, in tile order.
pub fn languages() -> impl Iterator<Item = &'static str> {
    ALLOWED.iter().map(|lang| lang.code)
}

/// The code in the allow-list that spells like `code`, ignoring case.
///
/// Overture writes language tags in lower case or in BCP 47 case, so the
/// reader asks for the spelling the tile uses.
#[must_use]
pub fn canonical_language(code: &str) -> Option<&'static str> {
    ALLOWED
        .iter()
        .find(|lang| lang.code.eq_ignore_ascii_case(code))
        .map(|lang| lang.code)
}

/// Append the name attributes of `feature` to `out`.
///
/// The local name is `names.primary` (Overture) or `name` (OSM, Natural
/// Earth). The language names come from the source of the feature. The
/// attributes are written in a fixed order: the local name and its scripts,
/// then `name:<lang>` in allow-list order.
pub fn push_names(feature: &InputFeature, out: &mut Vec<(String, PropValue)>) {
    if let Some(local) = feature
        .get_str("names.primary")
        .or_else(|| feature.get_str("name"))
    {
        push_local(local, out);
    }
    match &feature.source {
        DataSource::Osm { .. } => push_langs(feature, out, |l| l.osm, "name:zh"),
        DataSource::Overture { .. } => push_langs(feature, out, |l| l.overture, "names.common.zh"),
        DataSource::NaturalEarth { .. } => push_natural_earth_langs(feature, out),
        _ => {}
    }
}

/// `name`, `script`, `name2`, `script2`, `name3`, `script3` of a local name.
fn push_local(name: &str, out: &mut Vec<(String, PropValue)>) {
    const KEYS: [(&str, &str); 3] = [
        ("name", "script"),
        ("name2", "script2"),
        ("name3", "script3"),
    ];
    for (segment, (name_key, script_key)) in segment_by_script(name).iter().zip(KEYS) {
        out.push((name_key.to_string(), PropValue::Str(segment.clone())));
        let script = script_of(segment);
        if script != "Latin" && script != "Generic" {
            out.push((script_key.to_string(), PropValue::Str(script)));
        }
    }
}

/// `name:<lang>` for each allow-listed language the feature has.
///
/// `zh_key` is the source's key for plain Chinese, which fills the two
/// script variants when the feature has neither.
fn push_langs(
    feature: &InputFeature,
    out: &mut Vec<(String, PropValue)>,
    key_of: fn(&Lang) -> &'static str,
    zh_key: &str,
) {
    for lang in &ALLOWED {
        let backfill = match lang.code {
            "zh-Hans" | "zh-Hant" => feature.get_str(zh_key),
            _ => None,
        };
        if let Some(value) = feature.get_str(key_of(lang)).or(backfill) {
            out.push((
                format!("name:{}", lang.code),
                PropValue::Str(value.to_string()),
            ));
        }
    }
}

/// Natural Earth has `name_zh` (simplified) and `name_zht` (traditional) and
/// `name_<code>` for the other languages.
fn push_natural_earth_langs(feature: &InputFeature, out: &mut Vec<(String, PropValue)>) {
    for lang in &ALLOWED {
        let column = match lang.code {
            "zh-Hans" => "name_zh",
            "zh-Hant" => "name_zht",
            _ => lang.natural_earth,
        };
        if let Some(value) = feature.get_str(column) {
            out.push((
                format!("name:{}", lang.code),
                PropValue::Str(value.to_string()),
            ));
        }
    }
}

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

    fn osm(tags: &[(&str, &str)]) -> InputFeature {
        feature(
            DataSource::Osm {
                element_type: crate::source::input::OsmElementType::Node,
                relations: Vec::new(),
            },
            tags,
        )
    }

    fn overture(props: &[(&str, &str)]) -> InputFeature {
        feature(
            DataSource::Overture {
                theme: "divisions".to_string(),
                otype: "division".to_string(),
            },
            props,
        )
    }

    fn natural_earth(columns: &[(&str, &str)]) -> InputFeature {
        feature(
            DataSource::NaturalEarth {
                source_layer: "ne_50m_lakes".to_string(),
            },
            columns,
        )
    }

    fn feature(source: DataSource, props: &[(&str, &str)]) -> InputFeature {
        InputFeature {
            id: 1,
            geometry: std::sync::Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
            properties: props
                .iter()
                .map(|(k, v)| (k.to_string(), PropValue::Str(v.to_string())))
                .collect::<HashMap<_, _>>(),
            bbox: None,
            source,
        }
    }

    fn names_of(feature: &InputFeature) -> Vec<(String, String)> {
        let mut out = Vec::new();
        push_names(feature, &mut out);
        out.into_iter()
            .map(|(k, v)| match v {
                PropValue::Str(s) => (k, s),
                other => panic!("name attribute {k} is not a string: {other:?}"),
            })
            .collect()
    }

    fn pairs(want: &[(&str, &str)]) -> Vec<(String, String)> {
        want.iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn urdu_place_with_an_english_name() {
        let karachi = osm(&[
            ("place", "city"),
            ("name", "کراچی"),
            ("name:en", "Karachi"),
            ("name:ur", "کراچی"),
        ]);
        assert_eq!(
            names_of(&karachi),
            pairs(&[
                ("name", "کراچی"),
                ("script", "Arabic"),
                ("name:en", "Karachi"),
                ("name:ur", "کراچی"),
            ])
        );
    }

    #[test]
    fn latin_local_name_has_no_script() {
        let delhi = osm(&[("name", "Delhi"), ("name:hi", "दिल्ली")]);
        assert_eq!(
            names_of(&delhi),
            pairs(&[("name", "Delhi"), ("name:hi", "दिल्ली")])
        );
    }

    #[test]
    fn two_script_local_name_is_split() {
        let street = osm(&[("name", "Quartier 7 / حارة 7"), ("name:en", "Quarter 7")]);
        assert_eq!(
            names_of(&street),
            pairs(&[
                ("name", "Quartier 7"),
                ("name2", "حارة 7"),
                ("script2", "Arabic"),
                ("name:en", "Quarter 7"),
            ])
        );
    }

    #[test]
    fn three_script_local_name_keeps_three_segments() {
        let casablanca = osm(&[("name", "Casablanca ⴰⵏⴼⴰ الدار البيضاء")]);
        assert_eq!(
            names_of(&casablanca),
            pairs(&[
                ("name", "Casablanca"),
                ("name2", "ⴰⵏⴼⴰ"),
                ("script2", "Tifinagh"),
                ("name3", "الدار البيضاء"),
                ("script3", "Arabic"),
            ])
        );
    }

    #[test]
    fn languages_outside_the_allow_list_are_dropped() {
        let place = osm(&[
            ("name", "Köln"),
            ("name:dk", "x"),
            ("name:zh", "y"),
            ("name:de", "Köln"),
            ("name:fr", "Cologne"),
            ("name:old", "z"),
            ("alt_name", "w"),
            ("name:en:pronunciation", "v"),
        ]);
        let got = names_of(&place);
        assert!(got.contains(&("name:de".to_string(), "Köln".to_string())));
        assert!(got.contains(&("name:fr".to_string(), "Cologne".to_string())));
        for dropped in ["name:dk", "name:old", "alt_name", "name:en:pronunciation"] {
            assert!(got.iter().all(|(k, _)| k != dropped), "{dropped} was kept");
        }
    }

    #[test]
    fn plain_chinese_fills_both_script_variants() {
        let beijing = osm(&[("name", "北京"), ("name:zh", "北京市")]);
        assert_eq!(
            names_of(&beijing),
            pairs(&[
                ("name", "北京"),
                ("script", "Han"),
                ("name:zh-Hans", "北京市"),
                ("name:zh-Hant", "北京市"),
            ])
        );
    }

    #[test]
    fn explicit_chinese_variants_are_not_overwritten() {
        let taipei = osm(&[
            ("name", "台北"),
            ("name:zh", "台北市"),
            ("name:zh-Hant", "臺北市"),
        ]);
        assert_eq!(
            names_of(&taipei),
            pairs(&[
                ("name", "台北"),
                ("script", "Han"),
                ("name:zh-Hans", "台北市"),
                ("name:zh-Hant", "臺北市"),
            ])
        );
    }

    #[test]
    fn overture_division_takes_names_primary_and_common() {
        let lahore = overture(&[
            ("names.primary", "لاہور"),
            ("names.common.en", "Lahore"),
            ("names.common.ur", "لاہور"),
            ("names.common.xx", "ignored"),
        ]);
        assert_eq!(
            names_of(&lahore),
            pairs(&[
                ("name", "لاہور"),
                ("script", "Arabic"),
                ("name:en", "Lahore"),
                ("name:ur", "لاہور"),
            ])
        );
    }

    #[test]
    fn overture_chinese_fills_both_variants_too() {
        let place = overture(&[
            ("names.primary", "香港"),
            ("names.common.zh", "香港特别行政区"),
        ]);
        let got = names_of(&place);
        assert!(got.contains(&("name:zh-Hans".to_string(), "香港特别行政区".to_string())));
        assert!(got.contains(&("name:zh-Hant".to_string(), "香港特别行政区".to_string())));
    }

    #[test]
    fn natural_earth_lake_maps_its_columns() {
        let lake = natural_earth(&[
            ("name", "Ladoga"),
            ("name_en", "Lake Ladoga"),
            ("name_ru", "Ладожское озеро"),
            ("name_zh", "拉多加湖"),
            ("name_zht", "拉多加湖"),
            ("name_bn", "not in the list"),
        ]);
        assert_eq!(
            names_of(&lake),
            pairs(&[
                ("name", "Ladoga"),
                ("name:en", "Lake Ladoga"),
                ("name:ru", "Ладожское озеро"),
                ("name:zh-Hans", "拉多加湖"),
                ("name:zh-Hant", "拉多加湖"),
            ])
        );
    }

    #[test]
    fn feature_without_a_name_gets_no_attributes() {
        assert!(names_of(&osm(&[("highway", "service")])).is_empty());
        assert!(names_of(&osm(&[("name", "")])).is_empty());
    }

    #[test]
    fn languages_are_the_protomaps_allow_list() {
        let codes: Vec<_> = languages().collect();
        assert_eq!(codes.len(), 41);
        assert_eq!(codes.first(), Some(&"ar"));
        assert_eq!(codes.last(), Some(&"zh-Hant"));
        assert!(codes.contains(&"en") && codes.contains(&"zh-Hans"));
        assert!(!codes.contains(&"zh") && !codes.contains(&"dk"));
    }

    #[test]
    fn canonical_language_ignores_case() {
        assert_eq!(canonical_language("EN"), Some("en"));
        assert_eq!(canonical_language("zh-hans"), Some("zh-Hans"));
        assert_eq!(canonical_language("zh"), None);
        assert_eq!(canonical_language("dk"), None);
    }
}