Skip to main content

bitmapfont_creator/
config.rs

1//! Configuration parsing module
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5use serde::Deserialize;
6
7use crate::error::{BitmapFontError, Result};
8
9/// Frame definition for sprite sheet
10#[derive(Debug, Deserialize, Clone)]
11pub struct Frame {
12    /// X position in the sprite sheet
13    pub x: u32,
14    /// Y position in the sprite sheet
15    pub y: u32,
16    /// Width of the frame
17    pub w: u32,
18    /// Height of the frame
19    pub h: u32,
20}
21
22/// Character configuration entry
23#[derive(Debug, Deserialize, Clone)]
24pub struct CharConfig {
25    /// Path to the sprite sheet image
26    pub path: PathBuf,
27    /// Frame definition (optional, for sprite sheets)
28    #[serde(default)]
29    pub frame: Option<Frame>,
30    /// Padding around the character (default: 4)
31    #[serde(default = "default_padding")]
32    pub padding: u32,
33}
34
35/// Default padding value
36fn default_padding() -> u32 {
37    4
38}
39
40/// Font configuration from JSON
41#[derive(Debug, Deserialize)]
42pub struct FontConfig {
43    /// Character to config mapping
44    #[serde(flatten)]
45    pub chars: HashMap<String, CharConfig>,
46
47    /// Optional font name
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub font_name: Option<String>,
50
51    /// Optional output directory
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub output_dir: Option<PathBuf>,
54}
55
56impl FontConfig {
57    /// Parse configuration from a file
58    pub fn from_file(path: &PathBuf) -> Result<Self> {
59        let content = std::fs::read_to_string(path)
60            .map_err(|e| BitmapFontError::ConfigParse(
61                format!("Failed to read config file '{}': {}", path.display(), e)
62            ))?;
63
64        Self::from_str(&content)
65    }
66
67    /// Parse configuration from a string (JSON)
68    pub fn from_str(content: &str) -> Result<Self> {
69        serde_json::from_str(content)
70            .map_err(|e| BitmapFontError::ConfigParse(
71                format!("Invalid JSON format: {}", e)
72            ))
73    }
74
75    /// Parse configuration from stdin
76    pub fn from_stdin() -> Result<Self> {
77        use std::io::{self, Read};
78
79        let mut buffer = String::new();
80        io::stdin()
81            .read_to_string(&mut buffer)
82            .map_err(|e| BitmapFontError::ConfigParse(
83                format!("Failed to read from stdin: {}", e)
84            ))?;
85
86        Self::from_str(&buffer)
87    }
88}