Skip to content

Architecture and Internals

buntatoes edited this page Nov 28, 2026 · 1 revision

Architecture and Internals

EU5 RPC is architected as a 100% pure-Zig (0.17.1+) native application with zero third-party packages (build.zig.zon has .dependencies = .{}) and zero external runtime requirements. The entire codebase spans 17 Zig source files (8,964 LOC) covering the runtime daemon, telemetry parsers, IPC clients, system tray, auto-updater, Windows GUI setup installer, and Linux release packager.


Module Map

File LOC Role
src/root.zig 46 Library root exposing 13 core modules, shared constants (VERSION = "4.1.0", DEFAULT_DISCORD_APP_ID, EU5_STEAM_APP_ID, DEFAULT_LARGE_IMAGE_URL), bufPrintZ, and unified test block
src/main.zig 740 CLI argument parser, single-instance lock, Linux --install/--uninstall, background update thread launcher, and main event loop
src/config.zig 326 Config, GeneralConfig, PresenceConfig, ImagesConfig, FixedStr(N) stack buffers, applyVars template engine, and platform data directory resolution
src/toml.zig 325 Zero-dependency arena-backed TOML parser and serializer ([section] headers, # comment stripping, single/double-quoted strings, escapes, booleans, signed integers)
src/logger.zig 186 ISO-8601 UTC file + stdout logger writing logs/eu5-rpc.log (Win32 CreateFileW with FILE_SHARE_READ on Windows, fopen/fflush on Linux)
src/game_state.zig 375 GamePhase state machine, GameState fixed-buffer store, RichPresenceUpdate merger, six historical Ages mapping, and formatPresence formatter
src/process.zig 430 Read-only process detection (CreateToolhelp32Snapshot on Windows, /proc/<pid>/comm + /proc/<pid>/cmdline on Linux) and graceful closeEu5()
src/eu5_files.zig 1,157 Cross-platform UTF-16/UTF-8 file I/O, Windows Registry queries, Steam VDF/ACF parsing, Proton/Wine/Native user data folder discovery, and Steam/custom command launchers
src/steam_rp.zig 929 Passive Steam Rich Presence reader (steamclient64.dll / steamclient.so vtables) and 11-language localized presence parser
src/log_watcher.zig 680 Incremental read-only log tailer (debug.log, multiplayer.log, game.log) with 2 MiB resync window, truncation recovery, and session-scoped save sync
src/save_inspector.zig 502 Zero-allocation continue_game.json field extractor, newest .eu5 save scanner, filename parser, and first-2 KiB binary save header parser
src/country_lookup.zig 200 Dynamic Paradox localization loader (country_names_l_english.yml + formable_countries_l_english.yml) with 54 built-in fallback tags
src/discord_ipc.zig 408 Local Discord IPC framing (OP_HANDSHAKE, OP_FRAME), Windows named pipes / Linux Unix sockets, and zero-allocation SET_ACTIVITY JSON builder
src/tray.zig 1,353 Dedicated background-thread persistent system tray: Win32 Shell_NotifyIconW on Windows and D-Bus StatusNotifierItem + DBusMenu on Linux
src/updater.zig 705 Pure-Zig GitHub Releases API client (std.http.Client), SemVer comparison, trusted host allowlist, legacy Ruby detector/cleaner, and atomic self-updater
src/installer_win.zig 465 Standalone pure-Zig Windows GUI installer/uninstaller with @embedFile payloads, COM IShellLinkW shortcuts, and HKCU Uninstall registry integration
src/packager.zig 137 Standalone pure-Zig Linux POSIX USTAR .tar.gz archive builder using std.compress.flate

Runtime Architecture & Data Flow

flowchart LR
    subgraph Sources["Read-Only Telemetry Sources"]
        P["process.zig (Process Scan)"]
        S["steam_rp.zig (Steam Client IPC)"]
        L["log_watcher.zig (EU5 Logs)"]
        SV["save_inspector.zig (continue_game.json & .eu5)"]
        CL["country_lookup.zig (EU5 Localization)"]
    end

    subgraph Core["Main Loop (main.zig)"]
        GS["game_state.zig (GameState & Formatter)"]
        CFG["config.zig + toml.zig (config.toml)"]
        LOG["logger.zig (logs/eu5-rpc.log)"]
    end

    subgraph Outputs["External & UI Interfaces"]
        IPC["discord_ipc.zig (Discord Local IPC)"]
        TRAY["tray.zig (Win32 / Linux SNI Tray)"]
        UPD["updater.zig (GitHub Releases Thread)"]
    end

    P --> GS
    S --> GS
    L --> GS
    SV --> L
    CL --> L
    CFG --> GS
    GS --> IPC
    GS --> TRAY
    TRAY --> Core
    UPD --> TRAY
    Core --> LOG
Loading

Main Loop Execution Cycle

Each iteration of the daemon loop in src/main.zig:

  1. Immediate Tray Action Dispatch: Calls tray.pollAction() to respond promptly to launch_game, check_update, open_config, or quit_all. Even during sleep, sleepMs() wakes every 100 ms (or immediately if any tray atomic flag is set).
  2. Process Probe: Checks eu5.process.eu5Running().
    • On Game Start Transition: Transitions GameState from .not_running to .loading, calls watcher.refreshUserDataDir() to handle switching between Native and Proton installs, and lazily loads CountryLookup if not yet populated.
    • While Running: Polls steam_rp.poll() first. If Steam Rich Presence returns a country name, steam_has_country = true prevents stale save metadata from overwriting live country state while still allowing LogWatcher to process live logs and continue_game.json version updates.
    • On Game Exit Transition: Disconnects the Steam IPC pipe, resets GameState, sends a null activity to clear Discord presence, and exits if exit_when_game_closes = true (and --keep-open was not passed).
  3. Tray Tooltip Sync: Updates the tray status string (tray.updateStatus) whenever the formatted details change or the game transitions between running and waiting.
  4. Discord Reconnect & Deduplicated Push:
    • Retries Discord IPC connection every 10 seconds when disconnected.
    • Pushes SET_ACTIVITY only when running, discord.connected, the rate-limit window (discord_update_interval_s) has elapsed (or this is the first push), and either phase, details, or state actually changed.

GamePhase State Machine

src/game_state.zig models EU5's lifecycle using five phases:

stateDiagram-v2
    [*] --> not_running
    not_running --> loading : eu5 process detected / Empty->SplashScreen
    loading --> main_menu : LoadingScreen->MainMenu / Steam RP Main Menu
    main_menu --> lobby : Steam RP In Lobby
    main_menu --> in_game : MainMenu->Game / New Country
    lobby --> in_game : MainMenu->Game / Steam RP Playing
    in_game --> main_menu : ->MainMenu (clears country, year, event)
    in_game --> lobby : Steam RP In Lobby
    loading --> not_running : ->Empty / process exit
    main_menu --> not_running : ->Empty / process exit
    lobby --> not_running : ->Empty / process exit
    in_game --> not_running : ->Empty / process exit
Loading

Entering .main_menu clears country, tag, year, date, and active_event, preventing stale campaign info from lingering when returning to the menu.


Memory Model & Cross-Platform Primitives

  • Stack-Allocated Fixed Buffers: Hot-path structs (GameState, RichPresenceUpdate, SaveMetadata, Config, DiscordIpc, Tray) use fixed-size byte arrays (FixedStr(N), [128]u8, [256]u8, etc.) so steady-state polling performs almost zero heap allocations.
  • Windows Full UTF-16 & Shared-Read I/O (src/eu5_files.zig):
    • Converts UTF-8 paths to UTF-16LE (utf8ToUtf16Z) for Win32 *W APIs (CreateFileW, GetFileAttributesW, GetFileAttributesExW, GetEnvironmentVariableW, RegOpenKeyExW, SHGetFolderPathW, CreateProcessW), ensuring non-ASCII usernames and localized Windows directories work cleanly.
    • Opens EU5 log and save files with FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE so actively written Paradox logs never fail with sharing violations.
  • Linux Syscalls & Standard C Library:
    • Uses Linux statx directly for fileMtime and fileSize, POSIX fcntl advisory file locks for single-instance enforcement, and fork/execvp double-forking for detached launchers without zombie processes.
    • Signal handlers register SIGINT and SIGTERM to set g_stop for graceful presence clearing, and ignore SIGPIPE so Discord disconnects never terminate the daemon.

Persistent System Tray Internals (src/tray.zig)

The tray controller communicates with the main thread via lock-free atomics (quit_requested, launch_requested, check_update_requested, open_config_requested, game_running, status_dirty, notify_pending) and a small SpinLock guarding the status/notification text buffers.

Windows Implementation

  • Creates a hidden message-only window (Eu5RpcTrayWindowClass) on the tray thread and loads embedded icon resource #1 (assets/icon.ico).
  • Registers the tray icon via Shell_NotifyIconW(NIM_ADD, ...) with NIF_MESSAGE | NIF_ICON | NIF_TIP.
  • Registers the "TaskbarCreated" window message (RegisterWindowMessageW) so if Windows Explorer restarts, winTrayWndProc automatically re-adds the icon.
  • Displays native popup menus (CreatePopupMenu / TrackPopupMenu) on left-click, right-click, or context-menu events, and delivers update notifications via NIF_INFO balloon toasts.

Linux Implementation

  • Dynamically loads libdbus-1.so.3 (falling back to libdbus-1.so) at runtime via dlopen / dlsym — keeping zero hard link-time GUI/D-Bus dependencies and gracefully no-oping on headless machines.
  • Writes the @embedFile("icon_png") PNG to $XDG_RUNTIME_DIR/eu5-rpc-icons/eu5-rpc.png (or /tmp/eu5-rpc-icons-<uid>/eu5-rpc.png) and exposes IconThemePath so panels render the exact icon even if --install was not run.
  • Claims org.kde.StatusNotifierItem-<pid>-1 on the session bus and registers two object paths:
    • /StatusNotifierItem implementing org.kde.StatusNotifierItem + org.freedesktop.DBus.Properties + Introspectable
    • /MenuBar implementing com.canonical.dbusmenu (GetLayout, GetGroupProperties, AboutToShow, Event, LayoutUpdated)
  • Calls org.kde.StatusNotifierWatcher.RegisterStatusNotifierItem("/StatusNotifierItem") and subscribes to NameOwnerChanged for org.kde.StatusNotifierWatcher so the icon re-registers automatically if plasmashell, GNOME Shell, or Waybar restarts.
  • Sends desktop notifications via org.freedesktop.Notifications.Notify (5,000 ms timeout).