17 kB 107 lines
b2461cb6
nanachi.org
⋯
docs/architecture.md
download raw history
at master Markdown

Architecture #

Crates and views #

The app is a Cargo workspace with two crates and a set of Slint views.

Part Role
crates/core (fmm_core) Data, planning and effects: discovery, local scanning, versions, mod-list writes, portal parsing and caches, download/install/backup, settings, durable metadata. No UI.
crates/app (fmm) Binds core to Slint: models, callbacks, background workers, native window integration, windowless capture harness.
src/view/*.slint Views and widgets (widgets/). Properties and callbacks only; compiled and embedded by crates/app/build.rs.

The release is a single Windows GUI executable or Linux/macOS binary. Fonts, game pieces and icons are embedded at build time, so no checkout, Bun or game install is needed at runtime. Debug builds keep a console.

App modules #

  • model.rs projects the local snapshot and pending choices; catalogue.rs projects portal, update and rich-view data; bindings.rs converts both to Slint models and formatted descriptions.
  • controller.rs owns local selection, search, toggles, version pins and changelog state.
  • description.rs projects bounded shared description frames and computes image-row positions; Slint drives playback with frame/delay models and a persistent playhead, without Rust per-frame updates. Width callbacks reflow without redecoding.
  • live.rs runs blocking portal work on worker threads and publishes results with slint::invoke_from_event_loop. Revision counters discard stale search, selection and changelog responses. Search and detail requests are debounced (300 ms and 250 ms); recent pages stay in memory; visible rows and the selected mod queue thumbnails with at most four requests in flight.
  • operations.rs runs confirmation, planning and download/apply work off the UI thread. Progress is kept per mod name and published about every 60 ms. Queued and running downloads appear as placeholder rows in Manage, each with its own cancel button. A batch downloads sequentially; closing the window and competing operations are blocked while one runs.
  • settings.rs binds the Settings and onboarding dialogs; chrome.rs the custom window frame (the title strip and the footer ribs both drag the window); capture.rs the headless screenshot harness.

Core modules #

paths, discovery (install and data folders), local_mods (zip, folder and builtin info.json), locale, mod_list, store (snapshot plus guarded writes), enable (dependency evaluation), version, net, portal, portal_search (HTML), portal_data (catalogue, /full, thumbnails, with an injected Fetch), catalogue (reads the local bulk response), explore (search and faceted counts over the local catalogue), updates, changelog, markdown, description_images (description-only URL/redirect policy, bounded decoding and inline flow), text, reltime, download, install, metadata, settings, cache.

Discovery, local choices and settings #

paths.rs and discovery.rs locate the Factorio install and write-data folders read-only: standard paths, Steam registry entries, library VDFs and Proton prefixes. Linux additionally probes native Steam aliases, XDG Steam, host-accessible Flatpak Steam and bounded standalone locations. It deduplicates canonical aliases with case-sensitive paths and parses structured VDF records. Linux config-path.cfg and config.ini resolve executable, system-write-data and system-read-data macros; unresolved or literal relative values require an explicit absolute data choice. Flatpak system-write-data resolves in its sandbox home. macOS probes ~/Library/Application Support/Steam libraries, /Applications and ~/Applications; the game root is factorio.app/Contents, and a chosen or FACTORIO_DIR folder holding the bundle, or the bundle itself, resolves to it. macOS user data defaults to ~/Library/Application Support/factorio. The data folder holds mods/mod-list.json; the install is optional and supplies the game version and builtin mods. FACTORIO_DIR overrides a saved install. Without a game version, local management works and downloads are disabled. First run, missing data or several detected data folders open onboarding; a chosen folder is validated and saved, and takes effect on restart.

local_mods.rs reads builtin, folder and zip info.json without extracting whole archives. store.rs holds a snapshot and the guarded writes. enable.rs evaluates missing or unsatisfied dependencies and marks both enabled sides of an incompatibility, without changing any state.

Toggles and installed-version pins are pending choices until Save and quit or the green save-only floppy button to its left (visible only with pending changes). "Latest" removes the saved version field. Both saves check that Factorio isn't running, the list hasn't changed and paths and pins are valid, then write mod-list.json through a sibling temp file and rename, keeping the first original as .bak. Downloads and removals keep unrelated pending choices through rescans; choices for removed mods are discarded. Unlisted installed mods display enabled, matching Factorio's default. They and unsaved toggle/pin choices show blue name/version text and a blue left accent in all Manage views. Disabled pending text is dimmed; selected pending rows retain orange selection and the blue accent. Pending unlisted rows also expose the save-only button. Saving records every installed mod with its displayed enabled state and clears both kinds of pending state; Undo only clears drafts.

Changelogs come from the selected local zip or folder version, then the portal's /full, then "No changelog".

Settings hold the data folder, the optional install folder, the SHA-1 verification switch and UI sound preferences. Missing settings use defaults without creating a file; a malformed file shows an error and is replaced only by an explicit Save. Obsolete fields in old files are ignored.

Portal and offline data #

Portal and archive HTTP goes through fmm_core::net: an HTTPS allow-list, no redirects, cookies or credentials, bounded timeouts, a 32 MiB cap on metadata responses (archives stream instead).

portal_search.rs builds and parses the site's search and browse routes: result markup, pagination and the returned filter state. Non-blank queries use /search; blank Relevance and Downloads use /browse/downloaded, Recently updated /browse/updated, Trending /browse/trending; 20 results per page. If the site normalises the requested filters or the markup changes, Explore falls back to the cached catalogue and shows a notice. Updates reads the full release arrays of installed mods (namelist), so a newer release for another game line never hides an update for the installed line. Formats are in docs/portal.md.

description_images.rs provides the separate description-only GET boundary: any validated HTTPS DNS host, at most three manual redirects, 15 s total and no download byte cap. It sniffs and decodes supported formats before atomically caching; injected transports and clocks keep tests/captures offline. External bytes use disposable description-images/, portal-host bytes keep portal-thumbs/. The decoder bounds dimensions and retained animation frames.

portal_data.rs caches the catalogue (six hours), per-mod /full (24 hours) and thumbnails. A cache or fetch failure keeps the last good data. Updates' Refresh checks full releases at most once a minute; Explore's Refresh refetches the current page. Built with the broken-portal feature, metadata is corrupted before parsing to exercise the fallbacks; images, archives, local data and stored records are untouched.

metadata.rs stores full portal responses by installed name and version, without expiry. A successful install or update records the applied version even if the portal advertises a newer one. At startup one background worker fills missing records for non-builtin mods, 500 ms apart; failures retry on the next launch. Retained thumbnails sit beside the records; gallery images load on demand. A metadata failure after an install is reported without undoing the install.

Install, update and remove #

install.rs plans before writing anything. Roots target the newest release for the installed game line; required dependencies satisfy all active constraints, including older compatible versions. Builtins can't be installed or removed. Cycles, missing builtins, unsafe identities, stale paths or lists and unsatisfiable constraints fail explicitly. Optional dependencies are listed, not installed; enabled incompatibilities warn. Actions run dependency first, and downloads and list writes for a mods folder are serialised.

download.rs creates its own mods/<name>_<version>.zip.fmm-part with create-new, streams in 64 KiB chunks while hashing and reporting progress, checks cancellation and the action-specific running-game guard, syncs, and returns a private checked temp. Network errors retry from byte zero up to twice; HTTP errors and SHA-1 mismatches don't retry. A 404 reports that the release isn't on the mirror yet. With verification off it still checks length, archive entries with CRCs and the info.json identity. Apply re-checks the temp's identity, digest and size before touching an installed version. Dropping a download removes only its own part file; startup removes leftover part files and refuses reparse points.

The live window watches mods/ (not its subfolders) for changes other programs make, such as Finder Put Back, manual copies or the game rewriting mod-list.json. After 400 ms of quiet it rescans on a worker and adopts the result like an operation's own rescan, keeping still-valid pending toggles, pins and selection. Changes during a planned or running operation wait until it's idle. Dotfiles, folder-mod contents, partial downloads and the list's temp/backup siblings are ignored.

Updating moves each replaced zip or folder intact into the sibling mod-backups/ under its original name; an occupied backup name is recycled first. Windows moves use MoveFileExW without replace or copy flags; Linux moves use renameat2(RENAME_NOREPLACE) and macOS moves renameatx_np(RENAME_EXCL). Races, cross-volume moves and unsupported filesystems fail safely. Removing a mod asks for confirmation, then sends every user version to the Recycle Bin (SHFileOperationW with FOF_ALLOWUNDO and a large-delete warning) and drops its list entries when the game is stopped. Reparse points and paths inside the install are rejected, and the running and staleness checks repeat before each effect and before the commit.

New installs never write mod-list.json or auto-enable a saved entry and may run while Factorio runs. Factorio treats unlisted installed mods as enabled; the app matches that default. Updates replacing existing versions retain the running-game guard, keep the enabled state and advance the version pin. One atomic list write commits successful updates and stopped-game removals. While Factorio runs, only listed, saved-enabled mods cannot be removed; unlisted and saved-disabled mods can be recycled without writing the list, retaining any disabled entries. Pending UI choices do not change the guard. New installs survive a separate update's list-commit failure. If promotion or the commit fails, moved backups are restored in reverse order, after demoting newly promoted zips back to their temp path; restores never overwrite. If Factorio starts during a protected update/removal, later writes and rollback refuse and report recovery paths. Recycle Bin removal can't be rolled back by the app. There is no crash journal: a crash or power loss may need a manual restore from the preserved backups. Linux removal uses freedesktop desktop Trash with original-path and deletion-time metadata. The desktop backend chooses home or per-volume Trash and accepts ordinary desktop permissions. A narrow vendored patch returns EXDEV instead of entering its copy/delete fallback. Failed removals leave the source in place; only completed Trash moves produce manual recovery instructions, and only failed attempted restores say ROLLBACK FAILED. No permanent-delete fallback exists. macOS removal uses NSFileManager trashItemAtURL, which moves to the item's volume Trash and never deletes. Other targets refuse effects.

Files the app reads and writes #

The Windows app root is %LOCALAPPDATA%\werry\factoriomodmanager. Linux settings use ${XDG_CONFIG_HOME:-$HOME/.config}/werry/factoriomodmanager, metadata uses ${XDG_DATA_HOME:-$HOME/.local/share}/werry/factoriomodmanager/metadata, and cache uses ${XDG_CACHE_HOME:-$HOME/.cache}/werry/factoriomodmanager. XDG values must be absolute; empty or relative values fall back to absolute HOME. Missing bases and relative FMM overrides return errors. macOS settings and metadata use ~/Library/Application Support/werry/factoriomodmanager (metadata in metadata/), and cache uses ~/Library/Caches/werry/factoriomodmanager; HOME and FMM overrides must be absolute.

Location Contents Lifetime Override
settings.json Folders, verification switch, UI sound enabled/volume Durable FMM_SETTINGS_DIR
metadata/<name>_<version>.json plus images Installed-mod portal data Durable, never expires FMM_METADATA_DIR
cache/catalogue.json, catalogue.fetched-at Bulk catalogue 6 hours FMM_CACHE_DIR
cache/full/<name-hash>.json Per-mod /full 24 hours FMM_CACHE_DIR
cache/thumbs/, cache/portal-thumbs/<url-hash>.* Extracted and portal thumbnails Disposable FMM_CACHE_DIR

Everything is written through a sibling temp file and a rename. Clearing the cache leaves settings and metadata alone.

Outside the app root, the app reads the Factorio install (read-only) and writes only mods/ zips, mods/mod-list.json (plus .bak), mod-backups/ and Recycle Bin/desktop Trash operations. It never reads player-data.json or touches mod-settings.dat.

On Linux the running guard reads /proc comm and argv0 (native factorio or Proton factorio.exe). Per-PID access and exit errors are skipped; a broken/unreadable table reports a warning and fails open, by owner decision. Cleanup repeats the guard before deleting each stale owned download part and refuses paths inside the install. HTTP(S) browser links launch xdg-open with one URL argument, reaped off the UI thread. On macOS the guard lists processes through libproc (proc_name and the proc_pidpath basename) and fails open the same way; cleanup is guarded identically, and links go to /usr/bin/open off the UI thread.

Rendering #

The Linux XDG application ID is factoriomodmanager, matching its desktop entry and icon. The live window uses Slint's FemtoVG renderer; --screenshot installs an in-process software renderer and never shows a window. Game atlas pieces, portal images and measured flat bands render in both. Table, row and grid views are virtualised, so a 24,000-entry catalogue has a bounded number of live widgets. Manage and Updates offer Table, Rows and Grid; Explore offers Rows and Grid. View choices last for the session; selection, checks, search and details are shared across views. Grid columns reflow with the width, and crossing a column-count boundary resets scrolling to the top.

TypeScript under Bun is only tooling (asset extraction, style and piece generation, captures, PNG scoring). It isn't part of the executable. See docs/development.md.

UI audio preferences and playback #

uiSoundsEnabled defaults to true and integer uiSoundVolume to 50 (0–100). Old/missing settings use these defaults without a write. Out-of-range integers clamp on load; wrong types use the existing malformed-settings error path. Settings previews immediately, disables the volume control while off without losing its value, applies Save without restart, and restores runtime preferences on Cancel/Escape. Failed Save keeps both the draft and the disk file intact. Only folder changes require restart.

audio.rs preloads embedded Vorbis on a detached worker and opens Rodio's default device, trying a 512-frame buffer then its default buffer. It never enumerates other devices. Rodio/Lewton decode once; PCM is prepared at output rate/channels, then shared by independent voices. Nonblocking submissions have capacity 32 and expire after 100 ms; preferences invalidate queued events. Three voices per cue, eight overall, oldest replacement, 250 ms cannot throttling and final mix clamping bound rapid clicks. Mute stops active voices. Output failure stays silent with one diagnostic; off→on permits one retry. No join can block UI close. Tests inject output and captures skip the service entirely. Actual routing, latency, mute fidelity and Windows playback require native owner checks.