Skip to main content

flatland_client_lib/
client_config.rs

1//! Persistent client settings (game host, API base) for installed play.
2
3use std::net::SocketAddr;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8pub const DEFAULT_GAME_PORT: u16 = 7373;
9pub const DEFAULT_API_PORT: u16 = 7380;
10
11#[derive(Debug, Clone, Serialize, Deserialize, Default)]
12pub struct GfxWindowPrefs {
13    /// Last window width in logical pixels.
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub width: Option<u32>,
16    /// Last window height in logical pixels.
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub height: Option<u32>,
19    /// Window X (platform coordinates; macOS AppKit bottom-left origin).
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub x: Option<u32>,
22    /// Window Y.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub y: Option<u32>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize, Default)]
28pub struct ClientConfig {
29    /// Gateway host (IPv4, IPv6, or DNS name). Port defaults to 7373.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub game_host: Option<String>,
32    /// Control plane HTTP port when `game_host` is set. Defaults to 7380.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub api_port: Option<u16>,
35    /// Gateway TCP port when `game_host` is set. Defaults to 7373.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub game_port: Option<u16>,
38    /// Gfx play window geometry (`flatland3-gfx`).
39    #[serde(default, skip_serializing_if = "GfxWindowPrefs::is_empty")]
40    pub gfx_window: GfxWindowPrefs,
41    /// Last HUD view mode from `.` cycle: `normal` | `compact` | `map`.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub hud_view: Option<String>,
44    /// Bottom system LOG dock hidden (`'` toggle).
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub hud_log_hidden: Option<bool>,
47    /// Hired workers (`h`) menu compact vs detail (`c` toggle).
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub workers_menu_compact: Option<bool>,
50    /// Worker route editor sheet collapsed to the corner chip (`z` toggle).
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub worker_route_panel_collapsed: Option<bool>,
53}
54
55impl GfxWindowPrefs {
56    pub fn is_empty(&self) -> bool {
57        self.width.is_none()
58            && self.height.is_none()
59            && self.x.is_none()
60            && self.y.is_none()
61    }
62}
63
64impl ClientConfig {
65    pub fn path() -> anyhow::Result<PathBuf> {
66        let base = dirs::config_dir()
67            .ok_or_else(|| anyhow::anyhow!("could not resolve config directory"))?;
68        Ok(base.join("flatland").join("client.json"))
69    }
70
71    pub fn load() -> Self {
72        Self::path()
73            .ok()
74            .and_then(|path| std::fs::read(&path).ok())
75            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
76            .unwrap_or_default()
77    }
78
79    pub fn save(&self) -> anyhow::Result<()> {
80        let path = Self::path()?;
81        if let Some(parent) = path.parent() {
82            std::fs::create_dir_all(parent)?;
83        }
84        std::fs::write(path, serde_json::to_vec_pretty(self)?)?;
85        Ok(())
86    }
87
88    pub fn save_gfx_window(&mut self, prefs: GfxWindowPrefs) -> anyhow::Result<()> {
89        self.gfx_window = prefs;
90        self.save()
91    }
92
93    /// Persist the `.` HUD view mode (`normal` / `compact` / `map`).
94    pub fn save_hud_view(&mut self, label: &str) -> anyhow::Result<()> {
95        self.hud_view = Some(label.to_string());
96        self.save()
97    }
98
99    pub fn save_hud_log_hidden(&mut self, hidden: bool) -> anyhow::Result<()> {
100        self.hud_log_hidden = Some(hidden);
101        self.save()
102    }
103
104    pub fn save_workers_menu_compact(&mut self, compact: bool) -> anyhow::Result<()> {
105        self.workers_menu_compact = Some(compact);
106        self.save()
107    }
108
109    pub fn save_worker_route_panel_collapsed(&mut self, collapsed: bool) -> anyhow::Result<()> {
110        self.worker_route_panel_collapsed = Some(collapsed);
111        self.save()
112    }
113
114    pub fn set_game_host(&mut self, host: impl Into<String>) -> anyhow::Result<()> {
115        let host = host.into().trim().to_string();
116        if host.is_empty() {
117            anyhow::bail!("game host cannot be empty");
118        }
119        self.game_host = Some(host);
120        self.save()
121    }
122
123    pub fn game_server_addr(&self) -> SocketAddr {
124        if let Some(host) = self.game_host.as_deref() {
125            let port = self.game_port.unwrap_or(DEFAULT_GAME_PORT);
126            return parse_host_port(host, port)
127                .unwrap_or_else(|| format!("{host}:{port}").parse().expect("valid host:port"));
128        }
129        "127.0.0.1:7373".parse().expect("valid default addr")
130    }
131
132    pub fn api_base_url(&self) -> String {
133        if let Some(host) = self.game_host.as_deref() {
134            let port = self.api_port.unwrap_or(DEFAULT_API_PORT);
135            if host.starts_with("http://") || host.starts_with("https://") {
136                return host.to_string();
137            }
138            return format!("http://{host}:{port}");
139        }
140        "http://127.0.0.1:7380".into()
141    }
142}
143
144pub fn default_game_server_addr() -> SocketAddr {
145    if let Ok(addr) = std::env::var("FLATLAND_GATEWAY_ADDR") {
146        if let Ok(parsed) = addr.parse() {
147            return parsed;
148        }
149    }
150    ClientConfig::load().game_server_addr()
151}
152
153pub fn default_api_base_url() -> String {
154    if let Ok(url) = std::env::var("FLATLAND_API_URL") {
155        return url;
156    }
157    ClientConfig::load().api_base_url()
158}
159
160fn parse_host_port(host: &str, default_port: u16) -> Option<SocketAddr> {
161    if host.contains(':') {
162        host.parse().ok()
163    } else {
164        format!("{host}:{default_port}").parse().ok()
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn default_is_localhost() {
174        let cfg = ClientConfig::default();
175        assert_eq!(
176            cfg.game_server_addr(),
177            "127.0.0.1:7373".parse().unwrap()
178        );
179        assert_eq!(cfg.api_base_url(), "http://127.0.0.1:7380");
180    }
181
182    #[test]
183    fn hud_view_roundtrips_in_config() {
184        let mut cfg = ClientConfig::default();
185        cfg.hud_view = Some("map".into());
186        let json = serde_json::to_string(&cfg).unwrap();
187        let loaded: ClientConfig = serde_json::from_str(&json).unwrap();
188        assert_eq!(loaded.hud_view.as_deref(), Some("map"));
189    }
190
191    #[test]
192    fn hud_and_workers_prefs_roundtrip() {
193        let mut cfg = ClientConfig::default();
194        cfg.hud_log_hidden = Some(true);
195        cfg.workers_menu_compact = Some(true);
196        cfg.worker_route_panel_collapsed = Some(true);
197        let json = serde_json::to_string(&cfg).unwrap();
198        let loaded: ClientConfig = serde_json::from_str(&json).unwrap();
199        assert_eq!(loaded.hud_log_hidden, Some(true));
200        assert_eq!(loaded.workers_menu_compact, Some(true));
201        assert_eq!(loaded.worker_route_panel_collapsed, Some(true));
202    }
203}