durthang 0.1.0

A modern, terminal-based MUD client with TLS, GMCP, automap, aliases, triggers, and a sidebar panel system
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Copyright (c) 2026 Raimo Geisel
// SPDX-License-Identifier: GPL-3.0-only
//
// Durthang is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, version 3.  See <https://www.gnu.org/licenses/gpl-3.0.html>.

//! Durthang — a terminal MUD client.
//!
//! This is the binary entry point.  It is responsible for:
//!
//! * Parsing CLI arguments via [`clap`].
//! * Bootstrapping structured file logging with [`tracing_subscriber`].
//! * Constructing the root [`App`] state and entering raw-mode TUI.
//! * Running the main event loop ([`run_loop`]) which alternates between
//!   draining non-blocking network events, redrawing the screen with
//!   [`ratatui`], and dispatching keyboard/mouse input to the appropriate
//!   view module.
//!
//! The application is structured as a simple state machine driven by
//! [`AppState`]: it starts on the selection screen and transitions to the
//! game view once a connection is established.  All long-running I/O lives
//! in a background Tokio task ([`net`] module) and communicates with the
//! UI thread via bounded MPSC channels.

mod app;
mod config;
mod map;
mod net;
mod ui;
#[cfg(test)]
mod tests;

use app::{App, AppState};
use clap::Parser;
use config::Config;
use crossterm::{
    event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers, MouseEventKind,
    },
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use net::{Connection, NetEvent};
use ratatui::prelude::*;
use std::{fs, io, path::PathBuf, sync::Mutex};
use tracing::info;
use ui::game::GameAction;

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

/// Command-line interface definition for Durthang.
///
/// Parsed by [`clap`] before the TUI is initialised so that `--help` and
/// `--version` work without entering raw mode.
#[derive(Parser)]
#[command(version, about = "Durthang — a terminal MUD client")]
struct Cli {
    /// Path to the configuration file.
    /// Defaults to $XDG_CONFIG_HOME/durthang/config.toml
    /// (typically ~/.config/durthang/config.toml).
    #[arg(long, value_name = "FILE")]
    config: Option<PathBuf>,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Return the application data directory (`$XDG_DATA_HOME/durthang` or
/// `~/.local/share/durthang` when the environment variable is absent).
///
/// The directory is used for the log file and per-server map JSON files.
/// It is *not* created here; callers are responsible for that.
fn data_dir() -> PathBuf {
    let base = std::env::var("XDG_DATA_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let home = std::env::var("HOME").expect("HOME environment variable not set");
            PathBuf::from(home).join(".local/share")
        });
    base.join("durthang")
}

/// Initialise structured logging for the lifetime of the process.
///
/// A log file is created at `<data_dir>/durthang.log` (previous contents are
/// overwritten on each run).  The log level is read from the `RUST_LOG`
/// environment variable and falls back to `info`.
///
/// No logs are written to stderr so as not to interfere with the TUI output.
fn init_logging() -> io::Result<()> {
    let dir = data_dir();
    fs::create_dir_all(&dir)?;
    let log_file = fs::File::create(dir.join("durthang.log"))?;
    tracing_subscriber::fmt()
        .with_writer(Mutex::new(log_file))
        .with_ansi(false)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();
    Ok(())
}

/// Query the current terminal size and return `(cols, rows)`.
///
/// Falls back to `(80, 24)` when the underlying `ioctl` is unavailable
/// (e.g. when stdout is redirected).
fn terminal_size() -> (u16, u16) {
    crossterm::terminal::size().unwrap_or((80, 24))
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Binary entry point.
///
/// Performs the following steps in order:
/// 1. Parse CLI arguments.
/// 2. Initialise file logging.
/// 3. Load (or create) the TOML configuration file.
/// 4. Set the terminal to raw mode and enter the alternate screen.
/// 5. Hand off to [`run_loop`] inside a blocking Tokio runtime.
/// 6. Restore the terminal to its previous state before exiting.
fn main() -> io::Result<()> {
    let cli = Cli::parse();
    let config_path = cli.config.unwrap_or_else(Config::default_path);

    init_logging()?;
    info!("Durthang starting up");
    info!("Using config file: {}", config_path.display());

    let config = Config::load(&config_path).unwrap_or_else(|e| {
        tracing::warn!("Could not load config from {}: {e}", config_path.display());
        Config::default()
    });

    let rt = tokio::runtime::Runtime::new()?;

    let mut app = App::new(config, config_path);

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Enter tokio context so we can call .await helpers inside the sync loop.
    rt.block_on(async {
        run_loop(&mut app, &mut terminal).await;
    });

    info!("Durthang shutting down");
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Main async loop
// ---------------------------------------------------------------------------

/// Main async event loop.
///
/// Each iteration:
/// 1. Drains all pending network events via [`drain_net_events`] (non-blocking).
/// 2. Redraws the TUI with [`ratatui`].
/// 3. Waits up to 100 ms for the next crossterm event.
/// 4. Dispatches the event to the appropriate view handler.
///
/// The loop exits when [`App::running`] is set to `false`.
async fn run_loop(app: &mut App, terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) {
    loop {
        // Drain non-blocking net events before drawing.
        drain_net_events(app);

        terminal
            .draw(|frame| match app.state {
                AppState::ServerSelect => ui::selection::draw(frame, &app.select, &app.config),
                AppState::Game => {
                    let server = app.connected_server.as_deref().unwrap_or("?");
                    let character = app.connected_char.as_deref().unwrap_or("?");
                    ui::game::draw(frame, &mut app.game, server, character);
                }
            })
            .expect("terminal draw failed");

        // Poll for the next crossterm event (100 ms timeout so net events are drained regularly).
        if !event::poll(std::time::Duration::from_millis(100)).expect("event poll failed") {
            continue;
        }

        match event::read().expect("event read failed") {
            Event::Resize(cols, rows) => {
                if let Some(conn) = &app.connection {
                    conn.send_naws(cols, rows).await;
                }
            }
            Event::Mouse(mouse) => {
                if matches!(app.state, AppState::Game) {
                    match mouse.kind {
                        MouseEventKind::ScrollUp => app.game.scroll_up(3),
                        MouseEventKind::ScrollDown => app.game.scroll_down(3),
                        _ => {}
                    }
                }
            }
            Event::Key(key) => {
                // Global Ctrl-C always quits.
                if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
                    if let Some(conn) = &app.connection {
                        conn.disconnect().await;
                    }
                    app.quit();
                    break;
                }

                match app.state {
                    AppState::ServerSelect => {
                        let quit = ui::selection::handle_key(
                            &mut app.select,
                            &mut app.config,
                            &app.config_path,
                            key,
                        );
                        if quit {
                            app.quit();
                            break;
                        }
                        if let Some((server_id, char_id)) = app.select.pending_connect.take() {
                            do_connect(app, &server_id, char_id.as_deref()).await;
                        }
                    }
                    AppState::Game => {
                        match ui::game::handle_key(&mut app.game, key) {
                            Some(GameAction::SendLine(line)) => {
                                if let Some(conn) = &app.connection {
                                    conn.send_line(line).await;
                                }
                            }
                            Some(GameAction::Disconnect) => {
                                save_map_quiet(app);
                                if let Some(conn) = &app.connection {
                                    conn.disconnect().await;
                                }
                                app.connection = None;
                                app.connected_server_id = None;
                                app.game.on_disconnect();
                                app.state = AppState::ServerSelect;
                            }
                            Some(GameAction::Quit) => {
                                save_map_quiet(app);
                                if let Some(conn) = &app.connection {
                                    conn.disconnect().await;
                                }
                                app.quit();
                                break;
                            }
                            Some(GameAction::CopyToClipboard(text)) => {
                                copy_to_clipboard(&text);
                            }
                            Some(GameAction::AddAlias { name, expansion }) => {
                                game_add_alias(app, name, expansion);
                            }
                            Some(GameAction::RemoveAlias(name)) => {
                                game_remove_alias(app, name);
                            }
                            Some(GameAction::AddTrigger {
                                pattern,
                                color,
                                send,
                            }) => {
                                game_add_trigger(app, pattern, color, send);
                            }
                            Some(GameAction::RemoveTrigger(id_prefix)) => {
                                game_remove_trigger(app, id_prefix);
                            }
                            Some(GameAction::SaveSidebarLayout) => {
                                save_sidebar_layout(app);
                            }
                            None => {}
                        }
                        // Drain any trigger-generated auto-sends.
                        let sends: Vec<String> = app.game.auto_send_queue.drain(..).collect();
                        for line in sends {
                            if let Some(conn) = &app.connection {
                                conn.send_line(line).await;
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        if !app.running {
            break;
        }
    }
}

// ---------------------------------------------------------------------------
// Net event draining
// ---------------------------------------------------------------------------

/// Drain all currently available [`NetEvent`]s from the connection's channel.
///
/// This is called before each frame draw to ensure the scrollback buffer and
/// the automap are up to date.  The function returns immediately if there is
/// no active connection.
fn drain_net_events(app: &mut App) {
    let conn = match app.connection.as_mut() {
        Some(c) => c,
        None => return,
    };

    loop {
        match conn.rx.try_recv() {
            Ok(NetEvent::Line(line)) => {
                info!(target: "game", "{line}");
                app.game.push_line(&line);
                app.game.sidebar.map_apply_output_line(&line);
            }
            Ok(NetEvent::Prompt(prompt)) => {
                app.game.push_prompt(&prompt);
                app.game.sidebar.map_apply_output_line(&prompt);
            }
            Ok(NetEvent::Connected) => {
                info!("Network: connected");
                app.game.on_connect();
            }
            Ok(NetEvent::Gmcp(msg)) => {
                app.game.sidebar.map_apply_gmcp(&msg);
            }
            Ok(NetEvent::Disconnected(reason)) => {
                tracing::warn!("Disconnected: {reason}");
                let msg = format!("\x1b[33m-- Disconnected: {reason} --\x1b[0m");
                app.game.push_line(&msg);
                save_map_quiet(app);
                app.game.on_disconnect();
                app.connection = None;
                app.connected_server_id = None;
                app.state = AppState::ServerSelect;
                break;
            }
            Ok(NetEvent::Latency(ms)) => {
                app.game.record_latency(ms);
            }
            Err(_) => break,
        }
    }
}

// ---------------------------------------------------------------------------
// Connect helper
// ---------------------------------------------------------------------------

/// Establish a new [`Connection`] to the server identified by `server_id`.
///
/// If `char_id` is `Some`, the corresponding character's aliases, triggers,
/// and sidebar layout are loaded from the config and the credential stored in
/// the OS keyring is used for auto-login.  Passing `None` opens an
/// unauthenticated session without any character-specific configuration.
///
/// On success the application state transitions to [`AppState::Game`].
async fn do_connect(app: &mut App, server_id: &str, char_id: Option<&str>) {
    let server = match app.config.servers.iter().find(|s| s.id == server_id) {
        Some(s) => s.clone(),
        None => {
            tracing::warn!("Connect: server_id {server_id} not found in config");
            return;
        }
    };

    // Resolve character name and auto-login credentials.
    let (char_name, auto_login, char_id_owned) = if let Some(cid) = char_id {
        match app.config.characters.iter().find(|c| c.id == cid) {
            Some(c) => {
                info!(
                    "Connecting to {} ({}) as {}",
                    server.name, server.host, c.name
                );
                let login = c.effective_login().to_string();
                let password = config::get_password(&server.id, &login).unwrap_or(None);
                let auto_login = if c.login.is_some() || password.is_some() {
                    Some((login, password))
                } else {
                    None
                };
                (c.name.clone(), auto_login, Some(cid.to_string()))
            }
            None => {
                tracing::warn!("Connect: char_id {cid} not found in config");
                return;
            }
        }
    } else {
        info!(
            "Connecting to {} ({}) without a saved character",
            server.name, server.host
        );
        (String::from("(anonymous)"), None, None)
    };

    let size = terminal_size();
    let conn = Connection::spawn(
        server.host.clone(),
        server.port,
        server.tls,
        auto_login,
        size,
    );

    app.connection = Some(conn);
    app.connected_server = Some(server.name.clone());
    app.connected_server_id = Some(server.id.clone());
    app.connected_char = Some(char_name);
    app.connected_char_id = char_id_owned;
    // Clear the game view for the new session and mark as connected.
    app.game = crate::ui::game::GameState::new();
    app.game.on_connect();

    // Load aliases, triggers, and sidebar layout for this character.
    if let Some(cid) = &app.connected_char_id {
        if let Some(ch) = app.config.characters.iter().find(|c| &c.id == cid) {
            app.game.set_aliases(ch.aliases.clone());
            app.game.set_triggers(ch.triggers.clone());
            app.game.sidebar = crate::ui::sidebar::SidebarState::new(ch.sidebar.clone());
        }
    }

    match crate::map::load_server_map(&server.id) {
        Ok(world) => {
            app.game.sidebar.automap = world;
        }
        Err(e) => {
            tracing::warn!("Failed to load map for server {}: {e}", server.id);
        }
    }

    app.state = AppState::Game;
}

// ---------------------------------------------------------------------------
// In-game config mutation helpers
// ---------------------------------------------------------------------------

/// Persist the current [`Config`] to disk, logging a warning on failure.
///
/// Errors are intentionally swallowed here because config saves happen as
/// a side-effect of in-game commands; a failure should not crash the session.
fn save_config_quiet(app: &App) {
    if let Err(e) = app.config.save(&app.config_path) {
        tracing::warn!("Failed to save config: {e}");
    }
}

/// Persist the automap for the currently connected server to disk.
///
/// Like [`save_config_quiet`] this silently logs and swallows I/O errors.
/// No-op when no server is connected.
fn save_map_quiet(app: &App) {
    let Some(server_id) = app.connected_server_id.as_deref() else {
        return;
    };
    if let Err(e) = crate::map::save_server_map(server_id, &app.game.sidebar.automap) {
        tracing::warn!("Failed to save map for server {server_id}: {e}");
    }
}

/// Copy the in-memory sidebar layout back to the active character's config entry
/// and persist the config to disk.
fn save_sidebar_layout(app: &mut App) {
    let Some(cid) = app.connected_char_id.clone() else {
        return;
    };
    if let Some(ch) = app.config.characters.iter_mut().find(|c| c.id == cid) {
        ch.sidebar = app.game.sidebar.layout.clone();
    }
    save_config_quiet(app);
}

/// Add or replace an alias for the currently connected character and persist
/// the change.  The updated alias list is immediately reflected in the live
/// session.
fn game_add_alias(app: &mut App, name: String, expansion: String) {
    let Some(cid) = app.connected_char_id.clone() else {
        return;
    };
    if let Some(ch) = app.config.characters.iter_mut().find(|c| c.id == cid) {
        ch.aliases.retain(|a| a.name != name);
        ch.aliases.push(config::Alias {
            name: name.clone(),
            expansion: expansion.clone(),
        });
    }
    save_config_quiet(app);
    // Sync updated list back to game state.
    if let Some(ch) = app.config.characters.iter().find(|c| c.id == cid) {
        app.game.set_aliases(ch.aliases.clone());
        app.game
            .push_system(&format!("Alias added: {} \u{2192} {}", name, expansion));
    }
}

/// Remove an alias by exact name for the currently connected character.
///
/// Emits an in-game system message confirming removal (or noting that the
/// alias was not found).
fn game_remove_alias(app: &mut App, name: String) {
    let Some(cid) = app.connected_char_id.clone() else {
        return;
    };
    let removed = if let Some(ch) = app.config.characters.iter_mut().find(|c| c.id == cid) {
        let before = ch.aliases.len();
        ch.aliases.retain(|a| a.name != name);
        ch.aliases.len() < before
    } else {
        false
    };
    if removed {
        save_config_quiet(app);
        if let Some(ch) = app.config.characters.iter().find(|c| c.id == cid) {
            app.game.set_aliases(ch.aliases.clone());
        }
        app.game.push_system(&format!("Alias '{}' removed.", name));
    } else {
        app.game.push_system(&format!("No alias named '{}'.", name));
    }
}

/// Validate and add a trigger rule for the currently connected character.
///
/// The regex `pattern` is compiled before storing to provide immediate
/// feedback on syntax errors via an in-game system message.  On success the
/// trigger is appended to the character config, persisted to disk, and
/// immediately activated in the live session.
fn game_add_trigger(app: &mut App, pattern: String, color: Option<String>, send: Option<String>) {
    let Some(cid) = app.connected_char_id.clone() else {
        return;
    };
    // Validate regex before storing.
    if let Err(e) = regex::Regex::new(&pattern) {
        app.game.push_system(&format!("Invalid regex pattern: {e}"));
        return;
    }
    let trigger = config::Trigger {
        id: uuid::Uuid::new_v4().to_string(),
        pattern,
        color,
        send,
    };
    let id_short = trigger.id[..8].to_string();
    if let Some(ch) = app.config.characters.iter_mut().find(|c| c.id == cid) {
        ch.triggers.push(trigger);
    }
    save_config_quiet(app);
    if let Some(ch) = app.config.characters.iter().find(|c| c.id == cid) {
        app.game.set_triggers(ch.triggers.clone());
        app.game
            .push_system(&format!("Trigger [{id_short}] added."));
    }
}

/// Remove all trigger rules whose id starts with `id_prefix`.
///
/// Intended to be called with the first 8 characters of a UUID as displayed
/// by `/trigger list`.  Emits an in-game system message on success or failure.
fn game_remove_trigger(app: &mut App, id_prefix: String) {
    let Some(cid) = app.connected_char_id.clone() else {
        return;
    };
    let removed = if let Some(ch) = app.config.characters.iter_mut().find(|c| c.id == cid) {
        let before = ch.triggers.len();
        ch.triggers.retain(|t| !t.id.starts_with(&id_prefix));
        ch.triggers.len() < before
    } else {
        false
    };
    if removed {
        save_config_quiet(app);
        if let Some(ch) = app.config.characters.iter().find(|c| c.id == cid) {
            app.game.set_triggers(ch.triggers.clone());
        }
        app.game
            .push_system(&format!("Trigger '{}...' removed.", id_prefix));
    } else {
        app.game
            .push_system(&format!("No trigger with id prefix '{}'.", id_prefix));
    }
}

/// Copy text to the clipboard using the OSC 52 terminal escape sequence.
/// Works in most modern terminal emulators (kitty, alacritty, foot, tmux, …).
fn copy_to_clipboard(text: &str) {
    use std::io::Write;
    let b64 = base64_encode(text.as_bytes());
    let seq = format!("\x1b]52;c;{b64}\x07");
    let _ = std::io::stdout().write_all(seq.as_bytes());
    let _ = std::io::stdout().flush();
}

/// Minimal base64 encoder — no external dependency needed.
fn base64_encode(data: &[u8]) -> String {
    const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let v = (b0 << 16) | (b1 << 8) | b2;
        out.push(T[((v >> 18) & 0x3F) as usize] as char);
        out.push(T[((v >> 12) & 0x3F) as usize] as char);
        out.push(if chunk.len() >= 2 {
            T[((v >> 6) & 0x3F) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() >= 3 {
            T[(v & 0x3F) as usize] as char
        } else {
            '='
        });
    }
    out
}