milsymbol-rs 0.3.2

A Rust wrapper for the milsymbol JavaScript library to generate military symbols (MIL-STD-2525 and APP-6).
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use crate::error::MilsymbolError;
use crate::options::MilsymbolOptions;
use crate::types::{
    ColorMode, DashArrays, SymbolColors, SymbolMetadata, SymbolOutput, SymbolStyle,
    ValidationDetails,
};
use deno_core::{JsRuntime, RuntimeOptions, scope, serde_v8, v8};
use eyre::{Result, WrapErr};

#[cfg(feature = "cache")]
use crate::cache::{CacheData, SymbolCache};

/// Builder for constructing a `Milsymbol` engine with global configurations.
pub struct MilsymbolBuilder {
    hq_staff_length: Option<u32>,
    standard: Option<String>,
    dash_arrays: Option<DashArrays>,
    color_modes: Vec<(String, ColorMode)>,
    #[cfg(feature = "custom-parts")]
    symbol_parts: Vec<crate::types::SymbolPart>,
}

impl Default for MilsymbolBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl MilsymbolBuilder {
    /// Creates a new `MilsymbolBuilder` with default configurations.
    pub fn new() -> Self {
        Self {
            hq_staff_length: None,
            standard: None,
            dash_arrays: None,
            color_modes: Vec::new(),
            #[cfg(feature = "custom-parts")]
            symbol_parts: Vec::new(),
        }
    }

    /// Sets the length of the HQ staff line globally.
    pub fn hq_staff_length(mut self, length: u32) -> Self {
        self.hq_staff_length = Some(length);
        self
    }

    /// Sets the preferred standard ("2525" or "APP6").
    pub fn standard(mut self, standard: &str) -> Self {
        self.standard = Some(standard.to_string());
        self
    }

    /// Sets the dash arrays used for pending, anticipated, and feint/dummy symbols.
    pub fn dash_arrays(mut self, arrays: DashArrays) -> Self {
        self.dash_arrays = Some(arrays);
        self
    }

    /// Registers or overrides a color mode.
    pub fn color_mode(mut self, name: &str, mode: ColorMode) -> Self {
        self.color_modes.push((name.to_string(), mode));
        self
    }

    /// Registers a custom symbol part using typed instructions.
    #[cfg(feature = "custom-parts")]
    pub fn add_symbol_part(mut self, part: crate::types::SymbolPart) -> Self {
        self.symbol_parts.push(part);
        self
    }

    /// Builds the `Milsymbol` engine by initializing the V8 runtime and injecting the configuration.
    pub fn build(self) -> Result<Milsymbol> {
        let mut runtime = JsRuntime::new(RuntimeOptions::default());
        let ms_code = include_str!(concat!(env!("OUT_DIR"), "/milsymbol/dist/milsymbol.js"));
        runtime
            .execute_script("<milsymbol>", ms_code)
            .wrap_err("Failed to load milsymbol.js into the V8 runtime")?;

        let mut setup_script = String::from(include_str!("wrapper.js"));

        let mut color_modes_map = std::collections::HashMap::new();
        for (name, mode) in self.color_modes {
            color_modes_map.insert(name, mode);
        }

        let config = serde_json::json!({
            "hqStaffLength": self.hq_staff_length,
            "standard": self.standard,
            "dashArrays": self.dash_arrays,
            "colorModes": color_modes_map,
        });

        let config_json = serde_json::to_string(&config).unwrap();
        setup_script.push_str(&format!("\n__ms_setup({});\n", config_json));

        #[cfg(feature = "custom-parts")]
        {
            for part in self.symbol_parts {
                let part_json = serde_json::to_string(&part).unwrap();
                setup_script.push_str(&format!(
                    "\nms.addSymbolPart(function(ms) {{ return {}; }});\n",
                    part_json
                ));
            }
        }

        runtime
            .execute_script("<setup>", setup_script)
            .wrap_err("Failed to setup pre-compiled milsymbol functions")?;

        Ok(Milsymbol {
            runtime,
            #[cfg(feature = "cache")]
            cache: SymbolCache::new(),
        })
    }
}

/// The main entry point for generating symbols.
/// Encapsulates the V8 engine and handles rendering.
pub struct Milsymbol {
    runtime: JsRuntime,
    #[cfg(feature = "cache")]
    cache: SymbolCache,
}

impl Milsymbol {
    /// Calls a JavaScript function in the V8 runtime.
    pub(crate) fn call_js_function<T: serde::de::DeserializeOwned>(
        &mut self,
        func_name_str: &str,
        sidc: &str,
        options: &MilsymbolOptions,
    ) -> Result<T> {
        scope!(scope, &mut self.runtime);
        let global = scope.get_current_context().global(scope);

        let func_name = v8::String::new(scope, func_name_str).unwrap();
        let func_val = global.get(scope, func_name.into()).unwrap();
        let func = v8::Local::<v8::Function>::try_from(func_val)
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))?;

        let sidc_v8 = serde_v8::to_v8(scope, sidc).map_err(MilsymbolError::JsSerializationError)?;
        let options_v8 =
            serde_v8::to_v8(scope, options).map_err(MilsymbolError::JsSerializationError)?;

        let result = func
            .call(scope, global.into(), &[sidc_v8, options_v8])
            .ok_or_else(|| {
                MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(
                    "JS function returned null"
                ))
            })?;

        let res = serde_v8::from_v8::<T>(scope, result)
            .map_err(MilsymbolError::JsDeserializationError)?;
        Ok(res)
    }

    /// Clears the in-memory cache of rendered symbols for this engine instance.
    #[cfg(feature = "cache")]
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }

    /// Removes a specific symbol from the in-memory cache for this engine instance.
    #[cfg(feature = "cache")]
    pub fn remove_from_cache(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<()> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        self.cache.remove(sidc, options)
    }

    /// Generates an SVG string representation of a military symbol.
    pub fn as_svg(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<SymbolOutput> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("output", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::Output(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let result = self
            .call_js_function::<SymbolOutput>("__ms_renderSymbol", sidc, options)
            .wrap_err("Failed to extract SymbolOutput from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::Output(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Generates a static image (RGBA) representation of a military symbol.
    #[cfg(feature = "image")]
    pub fn as_image(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<image::DynamicImage> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("image", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::Image(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let output = self.as_svg(sidc, Some(options))?;
        let result = output.to_image()?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::Image(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Checks if a SIDC is valid.
    pub fn is_valid(&mut self, sidc: &str, options: Option<&MilsymbolOptions>) -> Result<bool> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("is_valid", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::IsValid(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok(**val);
        }

        let result = self
            .call_js_function::<bool>("__ms_isValid", sidc, options)
            .wrap_err("Failed to deserialize validation result")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::IsValid(Box::new(result)),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Checks if a SIDC is valid and returns detailed validation results.
    pub fn is_valid_extended(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<ValidationDetails> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("validation_details", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::ValidationDetails(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let result = self
            .call_js_function::<ValidationDetails>("__ms_isValidExtended", sidc, options)
            .wrap_err("Failed to extract ValidationDetails from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::ValidationDetails(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Retrieves the resolved color palette for a specific SIDC and options.
    pub fn get_colors(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<SymbolColors> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("colors", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::Colors(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let result = self
            .call_js_function::<SymbolColors>("__ms_getColors", sidc, options)
            .wrap_err("Failed to extract SymbolColors from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::Colors(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Retrieves rich parsed metadata for a specific SIDC and options.
    pub fn get_symbol_metadata(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<SymbolMetadata> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("symbol_metadata", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::SymbolMetadata(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let result = self
            .call_js_function::<SymbolMetadata>("__ms_getMetadata", sidc, options)
            .wrap_err("Failed to extract SymbolMetadata from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::SymbolMetadata(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Retrieves the resolved style information for a specific SIDC and options.
    pub fn get_style(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<SymbolStyle> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("style", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::Style(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).clone());
        }

        let result = self
            .call_js_function::<SymbolStyle>("__ms_getStyle", sidc, options)
            .wrap_err("Failed to extract SymbolStyle from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::Style(Box::new(result.clone())),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Retrieves the low-level draw instructions for a specific SIDC and options.
    pub fn get_draw_instructions(
        &mut self,
        sidc: &str,
        options: Option<&MilsymbolOptions>,
    ) -> Result<Vec<crate::types::DrawInstruction>> {
        let default_opts = MilsymbolOptions::default();
        let options = options.unwrap_or(&default_opts);
        let options_json =
            serde_json::to_string(options).map_err(MilsymbolError::SerializationError)?;

        #[cfg(feature = "cache")]
        let cache_key = ("draw_instructions", sidc.to_string(), options_json.clone());

        #[cfg(feature = "cache")]
        if let Some(item) = self.cache.map.get_mut(&cache_key)
            && let CacheData::DrawInstructions(val) = &item.data
        {
            item.last_accessed = std::time::Instant::now();
            return Ok((**val).to_vec());
        }

        let result = self
            .call_js_function::<Vec<crate::types::DrawInstruction>>(
                "__ms_getDrawInstructions",
                sidc,
                options,
            )
            .wrap_err("Failed to extract DrawInstructions from V8 payload")?;

        #[cfg(feature = "cache")]
        self.cache.map.insert(
            cache_key,
            crate::cache::CacheItem {
                data: CacheData::DrawInstructions(result.clone()),
                last_accessed: std::time::Instant::now(),
            },
        );

        Ok(result)
    }

    /// Returns the current HQ staff length used for HQ symbols.
    pub fn get_hq_staff_length(&mut self) -> Result<u32> {
        let result_global = self
            .runtime
            .execute_script("<exec>", "ms.getHqStaffLength()")
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))?;

        scope!(scope, &mut self.runtime);
        let local = v8::Local::new(scope, result_global);
        serde_v8::from_v8::<u32>(scope, local)
            .map_err(MilsymbolError::JsDeserializationError)
            .wrap_err("Failed to deserialize HQ staff length")
    }

    /// Returns the current dash arrays used for dashed line rendering.
    pub fn get_dash_arrays(&mut self) -> Result<DashArrays> {
        let result_global = self
            .runtime
            .execute_script("<exec>", "ms.getDashArrays()")
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))?;

        scope!(scope, &mut self.runtime);
        let local = v8::Local::new(scope, result_global);
        serde_v8::from_v8::<DashArrays>(scope, local)
            .map_err(MilsymbolError::JsDeserializationError)
            .wrap_err("Failed to deserialize dash arrays")
    }

    /// Returns the named color mode registered in the JS runtime.
    ///
    /// Returns an error if the name is unknown (the JS library returns `undefined`).
    pub fn get_color_mode(&mut self, name: &str) -> Result<ColorMode> {
        let name_json = serde_json::to_string(name).map_err(MilsymbolError::SerializationError)?;
        let script = format!("ms.getColorMode({})", name_json);

        let result_global = self
            .runtime
            .execute_script("<exec>", script)
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))?;

        scope!(scope, &mut self.runtime);
        let local = v8::Local::new(scope, result_global);
        serde_v8::from_v8::<ColorMode>(scope, local)
            .map_err(MilsymbolError::JsDeserializationError)
            .wrap_err(format!("Failed to deserialize color mode '{}'", name))
    }

    /// Retrieves the version of the underlying `milsymbol` JavaScript library.
    pub fn get_version(&mut self) -> Result<String> {
        #[cfg(feature = "cache")]
        if let Some(version) = crate::cache::VERSION_CACHE.get() {
            return Ok(version.clone());
        }

        let exec_script = "ms.getVersion()";
        let result_global = self
            .runtime
            .execute_script("<exec>", exec_script)
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))?;

        scope!(scope, &mut self.runtime);
        let local = v8::Local::new(scope, result_global);
        let version = serde_v8::from_v8::<String>(scope, local)
            .map_err(MilsymbolError::JsDeserializationError)
            .wrap_err("Failed to deserialize version string")?;

        #[cfg(feature = "cache")]
        let _ = crate::cache::VERSION_CACHE.set(version.clone());

        Ok(version)
    }

    /// Retrieves the allowed entities and modifiers for a specific symbol set.
    pub fn get_sidc_entities_and_modifiers(
        &mut self,
        symbol_set: &str,
    ) -> Result<crate::metadata::SidcEntitiesAndModifiers> {
        #[cfg(feature = "cache")]
        {
            let cache_mutex = crate::cache::ENTITIES_CACHE
                .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
            if let Ok(cache) = cache_mutex.lock()
                && let Some(data) = cache.get(symbol_set)
            {
                return Ok(data.clone());
            }
        }

        let symbol_set_json =
            serde_json::to_string(symbol_set).map_err(MilsymbolError::SerializationError)?;

        let script = format!("__ms_getEntitiesAndModifiers({})", symbol_set_json);

        let result_global = self
            .runtime
            .execute_script("<extraction>", script)
            .map_err(|e| MilsymbolError::JsExecutionError(deno_core::anyhow::anyhow!(e)))
            .wrap_err("Failed to execute extraction script")?;

        scope!(scope, &mut self.runtime);
        let local = v8::Local::new(scope, result_global);
        let json_string = serde_v8::from_v8::<String>(scope, local)
            .map_err(MilsymbolError::JsDeserializationError)?;

        let data: crate::metadata::SidcEntitiesAndModifiers =
            serde_json::from_str(&json_string).wrap_err("Failed to deserialize SIDC data")?;

        #[cfg(feature = "cache")]
        {
            let cache_mutex = crate::cache::ENTITIES_CACHE
                .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
            if let Ok(mut cache) = cache_mutex.lock() {
                cache.insert(symbol_set.to_string(), data.clone());
            }
        }

        Ok(data)
    }

    /// Retrieves the allowed entities (icons) for a specific symbol set.
    ///
    /// This is a convenience wrapper around `get_sidc_entities_and_modifiers`.
    pub fn get_sidc_entities(
        &mut self,
        symbol_set: &str,
    ) -> Result<Vec<crate::metadata::SidcPart>> {
        Ok(self.get_sidc_entities_and_modifiers(symbol_set)?.entities)
    }
}