flatland-client-lib 0.2.27

Flatland3 remote game client library (TCP session, bots, game state)
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
//! Persistent client settings (game host, API base) for installed play.

use std::net::SocketAddr;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

pub const DEFAULT_GAME_PORT: u16 = 7373;
pub const DEFAULT_API_PORT: u16 = 7380;

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct GfxWindowPrefs {
    /// Last window width in logical pixels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// Last window height in logical pixels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// Window X (platform coordinates; macOS AppKit bottom-left origin).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub x: Option<u32>,
    /// Window Y.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub y: Option<u32>,
}

/// Map-mode floating CHAT panel position + collapse (`flatland3-gfx`).
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct FloatingChatPrefs {
    /// Left edge in egui screen coordinates.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub x: Option<f32>,
    /// Top edge in egui screen coordinates.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub y: Option<f32>,
    /// Collapsed to the title strip.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collapsed: Option<bool>,
}

impl FloatingChatPrefs {
    pub fn is_empty(&self) -> bool {
        self.x.is_none() && self.y.is_none() && self.collapsed.is_none()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ClientConfig {
    /// Gateway host (IPv4, IPv6, or DNS name). Port defaults to 7373.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub game_host: Option<String>,
    /// Control plane HTTP port when `game_host` is set. Defaults to 7380.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_port: Option<u16>,
    /// Gateway TCP port when `game_host` is set. Defaults to 7373.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub game_port: Option<u16>,
    /// Gfx play window geometry (`flatland3-gfx`).
    #[serde(default, skip_serializing_if = "GfxWindowPrefs::is_empty")]
    pub gfx_window: GfxWindowPrefs,
    /// Map-mode floating chat panel (`flatland3-gfx`).
    #[serde(default, skip_serializing_if = "FloatingChatPrefs::is_empty")]
    pub floating_chat: FloatingChatPrefs,
    /// Last HUD view mode from `.` cycle: `normal` | `compact` | `map`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hud_view: Option<String>,
    /// Bottom system LOG dock hidden (`'` toggle).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hud_log_hidden: Option<bool>,
    /// Hired workers (`h`) menu compact vs detail (`c` toggle).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workers_menu_compact: Option<bool>,
    /// Worker route editor sheet collapsed to the corner chip (`z` toggle).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_route_panel_collapsed: Option<bool>,
}

impl GfxWindowPrefs {
    pub fn is_empty(&self) -> bool {
        self.width.is_none()
            && self.height.is_none()
            && self.x.is_none()
            && self.y.is_none()
    }
}

impl ClientConfig {
    pub fn path() -> anyhow::Result<PathBuf> {
        let base = dirs::config_dir()
            .ok_or_else(|| anyhow::anyhow!("could not resolve config directory"))?;
        Ok(base.join("flatland").join("client.json"))
    }

    pub fn load() -> Self {
        Self::path()
            .ok()
            .and_then(|path| std::fs::read(&path).ok())
            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
            .unwrap_or_default()
    }

    pub fn save(&self) -> anyhow::Result<()> {
        let path = Self::path()?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, serde_json::to_vec_pretty(self)?)?;
        Ok(())
    }

    pub fn save_gfx_window(&mut self, prefs: GfxWindowPrefs) -> anyhow::Result<()> {
        self.gfx_window = prefs;
        self.save()
    }

    /// Persist map-mode floating chat position + collapse.
    pub fn save_floating_chat(&mut self, prefs: FloatingChatPrefs) -> anyhow::Result<()> {
        self.floating_chat = prefs;
        self.save()
    }

    /// Persist the `.` HUD view mode (`normal` / `compact` / `map`).
    pub fn save_hud_view(&mut self, label: &str) -> anyhow::Result<()> {
        self.hud_view = Some(label.to_string());
        self.save()
    }

    pub fn save_hud_log_hidden(&mut self, hidden: bool) -> anyhow::Result<()> {
        self.hud_log_hidden = Some(hidden);
        self.save()
    }

    pub fn save_workers_menu_compact(&mut self, compact: bool) -> anyhow::Result<()> {
        self.workers_menu_compact = Some(compact);
        self.save()
    }

    pub fn save_worker_route_panel_collapsed(&mut self, collapsed: bool) -> anyhow::Result<()> {
        self.worker_route_panel_collapsed = Some(collapsed);
        self.save()
    }

    pub fn set_game_host(&mut self, host: impl Into<String>) -> anyhow::Result<()> {
        let host = normalize_host_input(&host.into())?;
        let default_port = self.game_port.unwrap_or(DEFAULT_GAME_PORT);
        let (host_only, port) = split_host_port(&host, default_port);
        self.game_host = Some(host_only);
        if port != DEFAULT_GAME_PORT || self.game_port.is_some() {
            self.game_port = Some(port);
        }
        self.save()
    }

    /// Host string for UI (never empty — falls back to localhost).
    pub fn display_game_host(&self) -> String {
        self.game_host
            .clone()
            .unwrap_or_else(|| "127.0.0.1".into())
    }

    /// Resolve gateway TCP address (supports DNS names like `server1.flatland3.com`).
    pub fn resolve_game_server_addr(&self) -> anyhow::Result<std::net::SocketAddr> {
        use std::net::ToSocketAddrs;
        let host = self.game_host.as_deref().unwrap_or("127.0.0.1");
        let port = self.game_port.unwrap_or(DEFAULT_GAME_PORT);
        let (host, port) = split_host_port(host, port);
        let target = format!("{host}:{port}");
        target
            .to_socket_addrs()
            .map_err(|e| anyhow::anyhow!("could not resolve {target}: {e}"))?
            .next()
            .ok_or_else(|| anyhow::anyhow!("no addresses found for {target}"))
    }

    pub fn game_server_addr(&self) -> SocketAddr {
        self.resolve_game_server_addr().unwrap_or_else(|_| {
            "127.0.0.1:7373"
                .parse()
                .expect("valid default addr")
        })
    }

    pub fn api_base_url(&self) -> String {
        if let Some(host) = self.game_host.as_deref() {
            let port = self.api_port.unwrap_or(DEFAULT_API_PORT);
            if host.starts_with("http://") || host.starts_with("https://") {
                return host.trim_end_matches('/').to_string();
            }
            let (host, _) = split_host_port(host, port);
            return format!("http://{host}:{port}");
        }
        "http://127.0.0.1:7380".into()
    }
}

pub fn default_game_server_addr() -> SocketAddr {
    if let Ok(addr) = std::env::var("FLATLAND_GATEWAY_ADDR") {
        if let Ok(parsed) = addr.parse() {
            return parsed;
        }
        // DNS host (optionally :port) via env — same rules as --host.
        if let Ok(resolved) = resolve_game_host_addr(&addr) {
            return resolved;
        }
    }
    ClientConfig::load().game_server_addr()
}

pub fn default_api_base_url() -> String {
    if let Ok(url) = std::env::var("FLATLAND_API_URL") {
        return url;
    }
    ClientConfig::load().api_base_url()
}

/// Resolve a DNS name or IP (optional `:port`) to the gateway TCP address.
///
/// Port defaults to [`DEFAULT_GAME_PORT`] (7373). Does not read or write `client.json`.
pub fn resolve_game_host_addr(host: &str) -> anyhow::Result<SocketAddr> {
    use std::net::ToSocketAddrs;
    let host = normalize_host_input(host)?;
    let (host, port) = split_host_port(&host, DEFAULT_GAME_PORT);
    let target = format!("{host}:{port}");
    target
        .to_socket_addrs()
        .map_err(|e| anyhow::anyhow!("could not resolve {target}: {e}"))?
        .next()
        .ok_or_else(|| anyhow::anyhow!("no addresses found for {target}"))
}

/// Control-plane base URL for a DNS/IP host (optional `:port` is ignored for API;
/// API always uses [`DEFAULT_API_PORT`] unless the host is already an `http(s)://` URL).
pub fn api_base_url_for_host(host: &str) -> anyhow::Result<String> {
    let host = normalize_host_input(host)?;
    if host.starts_with("http://") || host.starts_with("https://") {
        return Ok(host.trim_end_matches('/').to_string());
    }
    let (host, _) = split_host_port(&host, DEFAULT_API_PORT);
    Ok(format!("http://{host}:{DEFAULT_API_PORT}"))
}

/// Apply a one-shot host for this process only (no `client.json` write).
///
/// Sets `FLATLAND_API_URL`, `FLATLAND_GATEWAY_ADDR`, and `FLATLAND_HOST_OVERRIDE`
/// so auth, asset sync, and gateway connect use the same remote without touching
/// the machine's saved game host. Also points `FLATLAND_SESSION_PATH` at a
/// host-scoped session file so the default `session.json` stays for local play.
pub fn apply_host_override(host: &str) -> anyhow::Result<(SocketAddr, String)> {
    let normalized = normalize_host_input(host)?;
    let game = resolve_game_host_addr(&normalized)?;
    let api = api_base_url_for_host(&normalized)?;
    let (host_only, _) = split_host_port(&normalized, DEFAULT_GAME_PORT);

    std::env::set_var("FLATLAND_HOST_OVERRIDE", &host_only);
    std::env::set_var("FLATLAND_API_URL", &api);
    std::env::set_var("FLATLAND_GATEWAY_ADDR", game.to_string());

    if std::env::var_os("FLATLAND_SESSION_PATH").is_none() {
        if let Some(base) = dirs::config_dir() {
            let safe: String = host_only
                .chars()
                .map(|c| {
                    if c.is_ascii_alphanumeric() || c == '.' || c == '-' {
                        c
                    } else {
                        '_'
                    }
                })
                .collect();
            let path = base.join("flatland").join(format!("session.{safe}.json"));
            std::env::set_var("FLATLAND_SESSION_PATH", path);
        }
    }

    Ok((game, api))
}

/// True when this process applied (or inherited) a one-shot `--host` override.
pub fn host_override_active() -> bool {
    std::env::var_os("FLATLAND_HOST_OVERRIDE").is_some()
}

/// Strip scheme/path and reject empty hosts. Allows DNS names and `host:port`.
pub fn normalize_host_input(raw: &str) -> anyhow::Result<String> {
    let mut host = raw.trim().to_string();
    if host.is_empty() {
        anyhow::bail!("game host cannot be empty");
    }
    if let Some(rest) = host.strip_prefix("https://") {
        host = rest.to_string();
    } else if let Some(rest) = host.strip_prefix("http://") {
        host = rest.to_string();
    }
    if let Some((h, _)) = host.split_once('/') {
        host = h.to_string();
    }
    host = host.trim_end_matches('/').to_string();
    if host.is_empty() {
        anyhow::bail!("game host cannot be empty");
    }
    Ok(host)
}

fn split_host_port(host: &str, default_port: u16) -> (String, u16) {
    // IPv6 in brackets: [2001:db8::1]:7373
    if let Some(rest) = host.strip_prefix('[') {
        if let Some((addr, port_part)) = rest.split_once("]:") {
            if let Ok(p) = port_part.parse::<u16>() {
                return (format!("[{addr}]"), p);
            }
        }
        return (host.to_string(), default_port);
    }
    // host:port — only split on the last colon when the port is numeric
    if let Some((h, p)) = host.rsplit_once(':') {
        if !h.is_empty() && p.parse::<u16>().is_ok() && !h.contains(':') {
            return (h.to_string(), p.parse().unwrap_or(default_port));
        }
    }
    (host.to_string(), default_port)
}

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

    #[test]
    fn default_is_localhost() {
        let cfg = ClientConfig::default();
        assert_eq!(
            cfg.game_server_addr(),
            "127.0.0.1:7373".parse().unwrap()
        );
        assert_eq!(cfg.api_base_url(), "http://127.0.0.1:7380");
    }

    #[test]
    fn hud_view_roundtrips_in_config() {
        let mut cfg = ClientConfig::default();
        cfg.hud_view = Some("map".into());
        let json = serde_json::to_string(&cfg).unwrap();
        let loaded: ClientConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(loaded.hud_view.as_deref(), Some("map"));
    }

    #[test]
    fn hud_and_workers_prefs_roundtrip() {
        let mut cfg = ClientConfig::default();
        cfg.hud_log_hidden = Some(true);
        cfg.workers_menu_compact = Some(true);
        cfg.worker_route_panel_collapsed = Some(true);
        let json = serde_json::to_string(&cfg).unwrap();
        let loaded: ClientConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(loaded.hud_log_hidden, Some(true));
        assert_eq!(loaded.workers_menu_compact, Some(true));
        assert_eq!(loaded.worker_route_panel_collapsed, Some(true));
    }

    #[test]
    fn floating_chat_prefs_roundtrip() {
        let mut cfg = ClientConfig::default();
        cfg.floating_chat = FloatingChatPrefs {
            x: Some(42.5),
            y: Some(100.0),
            collapsed: Some(true),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let loaded: ClientConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(loaded.floating_chat.x, Some(42.5));
        assert_eq!(loaded.floating_chat.y, Some(100.0));
        assert_eq!(loaded.floating_chat.collapsed, Some(true));
    }

    #[test]
    fn split_host_port_handles_dns_and_explicit_port() {
        assert_eq!(
            split_host_port("server1.flatland3.com", 7373),
            ("server1.flatland3.com".into(), 7373)
        );
        assert_eq!(
            split_host_port("server1.flatland3.com:7374", 7373),
            ("server1.flatland3.com".into(), 7374)
        );
        assert_eq!(
            split_host_port("127.0.0.1", 7373),
            ("127.0.0.1".into(), 7373)
        );
    }

    #[test]
    fn normalize_strips_scheme() {
        assert_eq!(
            normalize_host_input("https://server1.flatland3.com/").unwrap(),
            "server1.flatland3.com"
        );
    }

    #[test]
    fn api_base_uses_dns_host() {
        let mut cfg = ClientConfig::default();
        cfg.game_host = Some("server1.flatland3.com".into());
        assert_eq!(cfg.api_base_url(), "http://server1.flatland3.com:7380");
    }

    #[test]
    fn api_base_url_for_host_defaults_port() {
        assert_eq!(
            api_base_url_for_host("server2.flatland3.com").unwrap(),
            "http://server2.flatland3.com:7380"
        );
        assert_eq!(
            api_base_url_for_host("server2.flatland3.com:7373").unwrap(),
            "http://server2.flatland3.com:7380"
        );
    }
}