82 Commits
Author SHA1 Message Date
objz 6dda8dc410 chore: updated readme and updated to 0.3.3 release 2026-07-11 17:49:35 +02:00
objz b4d03e7212 perf(content): use stable keys for icon caches 2026-07-11 17:16:30 +02:00
objz c792e1cc11 perf(tui): avoid redundant idle rendering 2026-07-11 17:13:02 +02:00
objz d10be1676e Merge pull request #25 from objz/feature/image-render-options
Feature/image render options
2026-07-11 16:04:25 +02:00
objz b94957a952 fix: formatting 2026-07-11 15:46:15 +02:00
objz 6f5722aa02 feat(tui): render streamed content icons 2026-07-11 15:41:51 +02:00
objz 4bf43a438b feat(content): add quadrant icon rasterization 2026-07-11 15:41:36 +02:00
objz b372571648 feat(config): add terminal image mode setting 2026-07-11 15:41:21 +02:00
objz b5d98e5e8a fix: polling noice on log and cache for scanning java version 2026-07-10 17:06:59 +02:00
objz 7e5ff7f75f fix(ci): choco validation file was remove and fixed icon paths 2026-07-10 16:56:11 +02:00
objz 099d96bcca Merge pull request #23 from objz/feature/delete-mods
feat(tui): add delete actions for instance content
2026-07-10 16:46:34 +02:00
objz 4ba9c65f73 fix(tui): route account deletes through shared confirmation 2026-07-10 16:39:43 +02:00
objz be01370ab2 feature(tui): added delete button to every content type 2026-07-10 16:35:55 +02:00
objz 4ddb8f49bb Merge pull request #24 from objz/feature/config-sync
feat(config-sync): add shared config profiles
2026-07-10 16:30:00 +02:00
objz 4576da4551 fix(config-sync): satisfy clippy warnings 2026-07-10 16:20:03 +02:00
objz 269814945d feat(tui): manage config profiles from settings 2026-07-10 16:12:48 +02:00
objz 69549b7152 feat(config-sync): add per-instance config profiles 2026-07-10 16:09:47 +02:00
objz 8f16931502 chore: v0.3.2 2026-06-16 15:17:55 +02:00
objz a95250cf9a Merge pull request #21 from objz/fix/adding-neoforge-instance-fails
Fix/adding neoforge instance fails
2026-06-16 15:13:30 +02:00
objz 2adfd0afbd Merge pull request #20 from objz/fix/sun-misc-unsafe-memory-accessallow
Fix/sun misc unsafe memory accessallow
2026-06-16 15:13:15 +02:00
objz 3ab6adf700 Merge pull request #22 from objz/fix/aur-failed-to-install
fix(pkg): isolate cargo target and config for AUR builds
2026-06-16 15:12:31 +02:00
objz 7c59758f5f fix(pkg): isolate cargo target and config for AUR builds 2026-06-16 15:08:14 +02:00
objz 63d7ef0fa1 fix: lib directory should point to the local libs preffered, only shared libs as backup to prevent corruption neoforge installation 2026-06-16 14:13:57 +02:00
objz 68d2f45236 fix: point -Duser to the right directory to prevent crashes 2026-06-16 14:13:57 +02:00
objz 3dd384c5c6 fixed clippy fail on windows caused by dead code that is only needed on unix 2026-06-16 14:01:32 +02:00
objz c5da2c7c99 fixed duplicate error messages on installer failure and added new error type 2026-06-16 13:25:28 +02:00
objz 1fd1b4e09d fix(launch): validate required Java version before launch 2026-06-16 12:32:37 +02:00
objz 0d9cd9c6b8 fixed duplicate logs 2026-06-16 12:26:18 +02:00
objz 09f403aa07 fixed noisy log 2026-06-16 12:07:31 +02:00
objz 3d7f233e27 fixed clippy issues 2026-06-16 10:35:34 +02:00
objz db23b86dca fix: flush downloaded files before returning 2026-06-16 10:27:21 +02:00
objz 09bc8f26fb chore: improve rmcl diagnostic logging 2026-06-16 10:22:51 +02:00
objz a58e6fb76d style: apply rustfmt 2026-06-16 09:58:34 +02:00
objz 7723716e18 Merge pull request #12 from objz/stout/sterr-parse-tui
added minecraft log parser
2026-06-13 16:53:21 +02:00
objz 29280e9f8d added minecraft log parser 2026-06-13 16:27:05 +02:00
objz e7e033715e fixed shocase gif 2026-06-12 11:36:19 +02:00
objz 4c22381675 added showcase.gif to the readme 2026-06-12 09:58:18 +02:00
objz e809fac364 fix generated wix 2026-06-11 21:00:55 +02:00
objz bf95404920 fix(test): peek_does_not_remove() was failing falsely 2026-06-11 20:47:22 +02:00
objz 4197beea3c chore(0.3.1 2026-06-11 20:08:30 +02:00
objz 10bfe8ad2f Merge branch 'master' of https://github.com/objz/rmcl 2026-06-11 20:06:24 +02:00
objz 58cbeb3ba0 removed println when launching from cli, so it does not open a seperate terminal window for a headless launch 2026-06-11 20:06:02 +02:00
objz 8b15dbcda5 removed println when launching from cli, so it does not open a seperate terminal window for a headless launch 2026-06-11 19:35:12 +02:00
objz 595af32e54 Merge pull request #9 from objz/test-overhaul
refactor: test suite overhaul (lib.rs split, snapshots, CI canaries)
2026-06-11 20:06:56 +03:00
objz c6c774b1e3 refactored: final review polish and detect_format + neoforge coverage
Addresses the six items the last review flagged. Four are polish for
existing tests; two add coverage for previously-untested public APIs.

Polish:

- instance/content/mods.rs: icon_path_from_value_map now asserts a
  single deterministic value. serde_json::Map is a BTreeMap so the
  "128" key sorts before "64" and the test no longer needs an
  order-tolerant disjunction.

- cli/log.rs: replace the hand-rolled unique_temp_dir with
  tempfile::tempdir() across both tests. Drop the trailing
  remove_dir_all cleanup since TempDir handles that on Drop. Last
  inline test file using the hand-rolled pattern.

- running.rs: remove drain_empty_returns_empty. Two consecutive calls
  to drain_last_played in the same test can race with the parallel
  push_and_drain_last_played test which pushes to the same global
  LAST_PLAYED state. drain semantics are covered by the existing
  push_and_drain test.

- tui/error_buffer.rs: peek_does_not_remove now actually verifies the
  invariant the name promises. Pushes a tagged event, captures the
  count before and after peek_error, asserts the count is unchanged
  and the tagged event is still in the queue. Previous version only
  asserted that something was returned.

New coverage:

- net/neoforge.rs: added fetch_neoforge_game_versions_from(client,
  api_url) mirroring the existing _from pattern. tests/net_loaders.rs
  gains neoforge_fetch_game_versions_reverse_engineers_mc_versions
  covering the maven-version-to-MC-version reverse mapping, which was
  only touched by the #[ignore] live API test before.

- instance/import/mod.rs: six new tests for detect_format covering
  mrpack detection, mmc-pack at root and nested, the priority case
  where both markers are present, unknown archives, and missing
  files. Helper make_pack_zip builds in-memory zips so the tests
  don't need fixture files on disk.
2026-05-27 18:55:19 +02:00
objz 5f43128a80 added: tests for patches helpers, forge installer detection, url_encode, profile fetchers
Closes the seven remaining tractable coverage gaps the final review
flagged. All tests-only or tiny *_from variants matching the existing
pattern. 18 new tests.

- src/instance/launch/patches.rs: seven inline tests for the lwjgl3ify
  patch helpers that were entirely untested before. strip_replaced_libs
  has happy + no-op cases. parse_add_opens covers the basic Add-Opens
  extraction, the MANIFEST.MF continuation-line case (the tricky one:
  jar manifests wrap lines with a trailing space + leading-space marker
  that gets stripped on join), missing manifest, and missing file.
  add_lwjgl3 verifies that only jars that actually exist in lib_dir
  end up on the classpath.

- src/net/forge.rs: three inline tests for has_legacy_install_profile.
  Builds synthetic forge installer zips in a tempdir with and without
  the versionInfo key in install_profile.json; covers the missing-jar
  branch with a path that doesn't exist.

- src/net/modrinth.rs: five-case rstest for url_encode covering the
  unreserved set, space, RFC 3986 reserved characters, multi-byte UTF-8
  (the encoder operates per-byte so emoji exercises the multi-byte
  path), and empty input.

- src/net/fabric.rs / src/net/quilt.rs: added fetch_*_profile_from and
  fetch_*_profile_with_raw_from variants mirroring the existing pattern.
  Existing fetch_*_profile and *_with_raw delegate to them with the
  upstream constants.

- tests/net_loaders.rs: two new wiremock tests (fabric_fetch_profile
  parses libraries, quilt_fetch_profile parses libraries) using the
  new _from variants.

- src/tui/widgets/popups/import_modpack/render.rs: extra snapshot for
  the Confirm step when loader_version is None (vanilla pack or old
  mmc pack). The previous Confirm snapshot covered Some(_) only.

Production touches stay minimal: the four new pub fn delegators in
fabric.rs and quilt.rs, all behaviour-preserving.
2026-05-27 18:19:26 +02:00
objz 0eb47fd7b4 added: *_from variants in net::{forge,fabric,quilt,neoforge} + assets
Same pattern as fetch_version_manifest_from from the earlier batch:
each fetcher gets a sibling that takes the URL as a parameter; the
existing function delegates to it with the upstream constant.
Production callers are unchanged.

- src/net/forge.rs: fetch_forge_versions_from(client, promotions_url,
  game_version) and fetch_forge_game_versions_from(client,
  promotions_url).
- src/net/fabric.rs: fetch_fabric_game_versions_from(client, base) and
  fetch_fabric_versions_from(client, base, game_version). The fabric
  API is hierarchical so the helpers take the meta base URL and append
  the rest internally, matching the existing layout.
- src/net/quilt.rs: same pair as fabric.
- src/net/neoforge.rs: fetch_neoforge_versions_from(client, api_url,
  game_version).
- src/net/mojang.rs: download_assets_from(client, meta, meta_dir,
  assets_base) so tests can route per-asset CDN downloads through a
  wiremock server. download_assets delegates to it with
  ASSETS_BASE_URL.

tests/net_loaders.rs adds eight wiremock tests covering each new
fetcher and a happy + error case for neoforge's invalid-game-version
branch. tests/net_mojang.rs gains download_assets_from_writes_index_and_assets
which now exercises the full per-asset download path against synthetic
hashes.

Production touches are minimal (one new pub fn delegating to the
existing one for each fetcher). Behaviour of existing callers is
unchanged.
2026-05-27 18:03:57 +02:00
objz 0d1b7984fc added: deferred tests-only items (extra wizard snapshots + library/asset downloads)
Closes the "zero production touches" subset of the deferred coverage
items the audit had flagged.

- src/tui/widgets/popups/new_instance/render.rs: three new snapshots
  for the Version, LoaderVersion, and Confirm steps. Each pre-populates
  WIZARD_STATE so ensure_versions_loaded and ensure_loader_versions_loaded
  short-circuit on LoadState::Loaded and never spawn a network task. The
  TEST_SERIAL mutex established in the earlier batch serialises against
  the existing Name/Loader snapshots.

- src/tui/widgets/popups/import_modpack/render.rs: two new snapshots
  for the Version step (synthetic VersionInfo entries) and the Confirm
  step (synthetic ImportSummary). Same serialisation pattern.

- tests/net_mojang.rs: three new wiremock tests.
  download_libraries_writes_artifact_to_meta_dir constructs a synthetic
  VersionMeta whose single library points at the wiremock server, then
  asserts the bytes land at meta_dir/libraries/<artifact.path>.
  download_libraries_skips_when_destination_exists verifies the cache
  hit path via wiremock's expect(0).
  download_assets_writes_index_when_objects_is_empty exercises the
  index fetch+write code path with an empty objects map so the per-asset
  download loop never fires.

  Zero production touches. download_libraries already takes a
  VersionMeta whose libraries carry their own URLs; download_assets'
  index fetch reads from meta.asset_index.url (also configurable
  per-call), so the empty-objects path doesn't need ASSETS_BASE_URL
  overridable. Full per-asset coverage lands in a separate commit.
2026-05-27 18:03:57 +02:00
objz d612f83446 refactored: address final review punch list
Final-review pass flagged three items. All addressed:

- src/instance/loader/mod.rs: rename and rewrite the two profile-shape
  tests so the test name matches what the body does.

  legacy_forge_version_info_round_trips_through_save_profile_json was
  misleading; the body never called save_installer_profile, it only
  wrote bytes to disk and read them back. Renamed to
  legacy_forge_version_info_deserialises_as_launch_profile and dropped
  the filesystem dance - the test was only ever verifying serde shape
  on the literal byte string.

  raw_fabric_profile_bytes_parse_as_launch_profile got the same
  treatment for consistency: dropped the TempDir + write + read round
  trip since the test only checks deserialisation.

- src/tui/error_buffer.rs: removed has_errors_after_push. The test
  read global state populated by other tests in the same module, so
  it would still pass if push_error were a no-op. The push semantics
  are properly covered by peek_all_returns_newest_first and
  overflow_drops_oldest, both of which use unique tagged messages to
  isolate from cross-test interference.
2026-05-27 17:42:14 +02:00
objz 8d7a0903fd refactored: DRY repetitive test fixtures with owning struct + rstest
Picks up the remaining test-only suggestions from the style audit. No
production code change.

- launch_profile/templates.rs: introduces a Fixture struct that owns
  the four PathBuf inputs (lib/nat/game/assets) and exposes a ctx()
  method. Eight tests that each rebuilt the same context inline now
  collapse into one rstest with eight cases plus two standalone
  tests for the recursive-substitution and Windows-backslash edge
  cases. Net code: ~120 lines saved.

- launch_profile/render.rs: same pattern. Fixture::new() owns the
  paths plus a FeatureSet; ctx() and rule_ctx() expose what every
  test needs. Six tests stop redeclaring four PathBufs + a five-line
  RuleContext literal apiece.

- instance/launch/mod.rs: three installer_version_dir_name tests
  (Forge / NeoForge / non-installer loaders) become one rstest with
  five cases (one per ModLoader variant). A regression that
  misorders the match arms would now fail a specific case, not just
  the catch-all "non-installer" test.

- instance/content/resource_packs.rs: ten extract_description_*
  tests become one rstest with ten cases. Each case still hits a
  distinct match arm (string, object{text}, object{no text}, array
  variants, null, number, bool); the rstest is cosmetic, not a
  consolidation that loses coverage.

Net effect: same coverage, ~250 lines less repetitive test setup,
clearer intent. Test count rises by 2 because rstest expands cases
into separate test functions.
2026-05-27 17:35:50 +02:00
objz 41d6da8008 added: ratatui snapshots for instance_list and wizard popups
Phase E added snapshots for the ErrorPopup; this extends the same
pattern to the three other high-value widgets the audit flagged.

- src/tui/widgets/instances.rs: two snapshots covering the instance
  list with three synthetic instances (verifies layout, "Never played"
  rendering, scrollbar gutter) and the empty list. State is passed in
  via the existing State::with_instances constructor; no global state
  involved.

- src/tui/widgets/popups/new_instance/render.rs: two snapshots covering
  the Name step (default) and Loader step (hardcoded loader list, no
  network). WIZARD_STATE is global, so the tests reset it under its
  mutex and serialise via a per-module TEST_SERIAL mutex to prevent
  cross-test races. The Version and LoaderVersion steps are skipped
  here because their render path calls ensure_versions_loaded which
  tokio::spawns a network task; covering them would need a fully
  pre-populated state and is deferred.

- src/tui/widgets/popups/import_modpack/render.rs: two snapshots
  covering the Input step (default) and the Fetching step (just a
  spinner + label, no network triggered by render). Same global-state
  serialisation pattern as new_instance.

Snapshots live next to each widget under snapshots/ as plain text and
are committed to git.
2026-05-27 17:22:33 +02:00
objz 6ac9f4e239 added: net::mojang wiremock tests via *_from URL variants
The existing fetch_version_manifest hard-codes the Mojang URL, so tests
either had to hit the live endpoint (the #[ignore] live-API test) or
not run at all. Adds fetch_version_manifest_from(client, url) that lets
callers pick the URL; fetch_version_manifest stays compatible by
delegating with the upstream constant. fetch_version_meta_with_raw
already takes the URL via VersionEntry, no change needed.

tests/net_mojang.rs adds three wiremock tests:

- fetch_version_manifest_parses_synthetic_response verifies the
  VersionManifest deserialiser against a synthetic upstream-shaped
  payload (latest + versions list).
- fetch_version_meta_returns_struct_and_raw_bytes verifies both the
  parsed VersionMeta and the raw byte capture path used by the install
  flow to write upstream JSON byte-for-byte.
- fetch_version_manifest_retries_5xx_and_succeeds confirms the retry
  envelope integrates correctly with VersionManifest deserialisation
  on top of the retry-only tests in tests/net_retry.rs.

These don't replace the #[ignore = "hits live Mojang API"] canary
which still runs on master push to detect upstream schema drift.
2026-05-27 17:22:32 +02:00
objz 1f1a0ebb3d refactored: test style cleanup + mmc archive extract test
Picks up the style audit's findings without touching production
behaviour (except for two em-dash characters in non-test code that
violated the no-em-dash rule).

- cli/import.rs, instance/import/mmc.rs: replace the two em-dashes
  that leaked into source (one in a user-facing format string, one
  in a code comment) with hyphen / colon.
- instance/manager.rs: rewrite test_manager to return TempDir instead
  of a hand-rolled tempdir path with manual cleanup. Drop the
  trailing std::fs::remove_dir_all from every test. Rename test_*
  functions to describe the scenario per CONTRIBUTING (delete_missing_
  instance_returns_not_found, save_then_load_all_round_trips_config,
  load_one_missing_returns_not_found, etc.).
- migrate.rs: replace unique_tmp + atomic counter with
  tempfile::tempdir() across all seven tests; ~10 lines of plumbing
  gone, automatic cleanup via Drop.
- auth/accounts.rs: drop the dummy_account wrapper that just forwarded
  to create_offline_account; inline the real call at the eight use
  sites.
- instance/models.rs: rename test_instance_config_roundtrip to
  instance_config_roundtrips_through_json.
- instance/content/mods.rs: drop the "what" comments above straight
  forward asserts; keep the one "why" comment that explains an
  empty-name + present-logo coverage gap. Trim the obvious "helper to
  create a jar (zip) file" comment above make_jar.
- tests/smoke.rs: //! to // for the file header; project convention is
  // for files (//! is for crate-level rustdoc, which doesn't render
  for integration test crates).

Adds one new test:

- instance/import/mmc.rs: extract_mmc_archive_copies_minecraft_subtree
  builds an in-memory zip with a Pack/ prefix, a Pack/mmc-pack.json
  sibling, and Pack/.minecraft/{options.txt, mods/test-mod.jar},
  then asserts only the .minecraft/ subtree lands in the destination
  with relative paths preserved. Closes the mmc extract coverage gap
  the audit flagged.
2026-05-27 17:09:09 +02:00
objz 623acd9e2c added: tests for retry envelope, manager rename, mod precedence, time buckets
Audit identified six high-priority coverage gaps. This commit closes
them with 30 net new passing tests.

- tests/net_retry.rs (new): 5 wiremock-based tests for the retry
  envelope in net/mod.rs. Covers get_json + download_file across:
  5xx retry-then-succeed, 4xx fail-fast (asserted via wiremock
  expect(1) so any retry attempt fails the test), and exhaust at
  MAX_RETRIES = 3 (asserted via expect(4)). The exhaust test takes
  ~3.5s of wall time because the production code sleeps 500 + 1000 +
  2000 ms between attempts; this is unavoidable without making the
  delays configurable.

- tests/launch_pipeline.rs: 3 new error-path tests against
  build_launch_invocation. merged_profile_missing_main_class_fails
  surfaces the LaunchError::Parse branch when meta.json deserialises
  cleanly but lacks mainClass. legacy_loader_profile_missing_loader_version_errors
  and legacy_loader_profile_missing_installer_json_errors exercise the
  two Parse branches inside migrate_legacy_loader_profile_if_needed.

- instance/manager.rs: 6 tests for rename (happy path, noop on same
  name, empty target rejected, missing source, target collision) and
  touch_last_played (sets the field to a stamp within 5 seconds of
  now). The InstanceManager rename surface had no coverage before;
  mutating the validation order or the std::fs::rename target would
  not have failed any existing test.

- instance/content/mods.rs: 4 new precedence-chain tests. The reader
  chain is fabric > quilt > forge-toml (which itself tries
  neoforge.mods.toml before mods.toml) > mcmod.info. Only the
  fabric-over-forge precedence had a test before. Adds quilt > forge,
  forge_toml > mcmod_info, neoforge.mods.toml > mods.toml, and a test
  that a mods.toml carrying only logoFile (no [[mods]] array) still
  resolves the icon.

- tui/widgets/instances.rs: 12 new tests for format_last_played. One
  case for the None input (returns "Never played"), then an rstest
  covering each bucket boundary in the match (0/59 just-now,
  60/3599 minutes, 3600/86399 hours, 86400/2591999 days,
  2592000/31535999 months, >=31536000 over-a-year). A mutation that
  bumps any boundary by one second, or swaps a unit suffix, fails at
  least one case.
2026-05-27 16:44:05 +02:00
objz 7a9dfa850d refactored: rework weak unit tests to catch real regressions
Audit found 9 confirmed-weak unit tests plus several newly-found ones that
asserted things equivalent to themselves, returned vacuous truth, or had
assertions guarded behind conditionals that silently swallowed failure.

Changes by file:

- auth/accounts.rs: create_offline_account_fields now pins the uuid to
  offline_uuid("TestPlayer") instead of !is_empty(); mutating the uuid
  derivation would fail this now.
- cli/mod.rs: parses_instance_list_subcommand drills into the list
  subcommand under instance rather than only verifying the instance
  group exists.
- config/theme.rs: border_style_roundtrip is now an rstest covering all
  four BorderStyle variants; mutating any non-Double arm is caught.
- instance/desktop.rs: removed desktop_path_returns_some (assertion was
  gated behind if let Some so could pass when the function returned
  None); build_content_linux* already covers the real behaviour.
- instance/launch/mod.rs: removed five predicate-only tests that
  asserted serde defaulting on LaunchProfile rather than invoking the
  migration predicate. Added two tests that actually call
  migrate_legacy_meta_if_needed (rstest over modern/legacy arg shapes)
  and migrate_legacy_loader_profile_if_needed (modern-with-inheritsFrom
  early-return). Renamed build_game_args_renders_upstream_arguments,
  dropping the misleading "and appends loader args" clause that the
  test never covered.
- instance/loader/mod.rs: removed test_vanilla_install_noop (no
  assertion at all) and test_vanilla_get_versions (asserted a hardcoded
  Ok(vec!["vanilla"]) return). Replaced test_vanilla_factory with an
  rstest covering all five ModLoader variants; a misordered match arm
  in get_installer is caught.
- migrate.rs: removed cleanup_instance_leftovers_handles_missing_dir
  (had no assertions and was redundant with
  cleanup_instance_leftovers_removes_shim_and_log4j).
- net/mod.rs: removed detect_java_falls_back_to_java which asserted
  !is_empty() against a function whose worst-case fallback is the
  literal string "java"; structurally uncatchable.
- tui/error_buffer.rs: peek_all_returns_newest_first and
  auto_assigned_ids_are_unique now tag their pushed events with a
  unique substring and filter peek_all_errors to just those, so the
  assertions actually fire instead of being silently skipped via
  if all.len() >= 2 when shared static state interfered.

Total: net zero change in test count (deletions and parameterised
replacements roughly balance), but mutation coverage of the surviving
suite is materially stronger.
2026-05-27 16:43:47 +02:00
objz d2e08d818b added: launch-pipeline integration tests via build_launch_invocation seam
Phase D of the test overhaul. Extracts a build_launch_invocation seam
from launch() so the full launch pipeline (profile loading, inheritsFrom
resolution, classpath assembly, template rendering) can be exercised
without spawning a real java process or hitting the auth servers.

The seam takes resolved auth credentials (LaunchAuth) and returns a
LaunchInvocation struct with the final java path, jvm args, classpath,
main class, extra args, game args, and working dir. launch() shrinks to
a thin wrapper that resolves auth from the account store, calls the
seam, and spawns the process.

tests/launch_pipeline.rs adds 14 integration tests covering: vanilla
modern args; vanilla legacy minecraftArguments; Forge with --add-opens;
Forge local-libs preference; Fabric implicit inheritsFrom resolution;
NeoForge inheritsFrom; auth credential substitution into game args;
version_type substitution; platform classpath separator; rule-disallowed
library exclusion; Xms/Xmx from config; default memory fallback; missing
meta.json error; missing loader profile error.
2026-05-26 21:38:17 +02:00
objz cc0dde106a refactored: move public-API filesystem tests to tests/
Per Phase C of the test overhaul: tests that touch the filesystem and
exercise the public API surface (scan_screenshots, scan_shaders,
scan_worlds, scan_resource_packs, log_files) move from inline mod tests
into tests/. They now consume rmcl as an external crate, mirroring how
real callers would.

AccountStore::store_save_and_reload stays inline because the helper it
needs (constructing AccountStore directly with a tempdir path) requires
reaching into a private field; exposing that just for tests would leak
implementation detail. The other accounts tests are in-memory and stay
inline regardless.

The extract_description_* tests in resource_packs stay inline since
they are pure logic on serde_json::Value (no filesystem).

image is added to dev-dependencies so integration tests can fabricate
1x1 PNG fixtures (already a regular dep of the lib).
2026-05-26 21:11:38 +02:00
objz c6fce8592a fixed: let CI network canaries actually red the build when they break 2026-05-26 21:00:06 +02:00
objz 2163fef175 added: INFO-level snapshot + popup_area unit tests; rename narrow_frame test 2026-05-26 21:00:06 +02:00
objz 05bea59ef1 refactored: narrow lib.rs visibility + drop speculative tests/common 2026-05-26 21:00:06 +02:00
objz 63fb96a0d2 added: run network canaries on master push only 2026-05-26 20:59:59 +02:00
objz c15cb9a378 added: ratatui snapshot tests for ErrorPopup (4 scenarios) 2026-05-26 20:59:59 +02:00
objz 961983d1fe removed: 6 useless tests (4 theatre + 2 wrapper redundancy) 2026-05-26 20:59:59 +02:00
objz aeeef26614 added: lib.rs split + tests/ scaffold for integration testing 2026-05-26 20:59:59 +02:00
objz efcef1cab4 Merge pull request #8 from objz/launch-args-rework
fix(launch): Forge 1.17+ on Java 17+ via launch-profile rework
2026-05-26 20:58:56 +02:00
objz f45351841c fixed: quick-play feature flags + missing version_type template
two related bugs surfaced by manual testing on 1.20.6 vanilla and fabric:

1. FeatureSet missing has_quick_plays_support / is_quick_play_singleplayer /
   is_quick_play_multiplayer / is_quick_play_realms. mojang's profiles gate
   the quick-play arguments behind these features. serde silently dropped
   the unknown fields during deserialization, leaving an empty FeatureSet
   that matched any context, so the conditional arguments emitted raw
   ${quickPlay*} placeholders to the JVM that template substitution then
   warned about. add the fields explicitly and extend features_match to
   reject any required feature the context doesn't set.

2. TemplateContext missing version_type. ${version_type} is an
   unconditional template in modern vanilla's arguments.game (renders the
   profile's "type" field, e.g. "release"). without it, the substitution
   emitted a literal ${version_type} to minecraft and warned. add the
   field, plumb the merged profile's type_ value through, default to
   "release" when absent.
2026-05-25 21:00:56 +02:00
objz d88ab085b5 fixed: forge/neoforge libraries from instance .minecraft/libraries not on classpath
modern forge's installer places some libraries (notably the bootstrap
library that defines ForgeBootstrap / BootstrapLauncher) into the
instance's .minecraft/libraries/ rather than the shared meta cache. the
unified classpath loop introduced in the rework checked downloads.artifact
first and pushed meta_dir/libraries/<path> without ever consulting the
local installer dir for libraries that had downloads.artifact set.

resolve a single relative path per library (downloads.artifact.path if
present, else maven_coord_to_path(name)), then for has_local_libs check
the local installer dir first regardless of which path source we used.
fixes ClassNotFoundException at launch on forge 1.20.6 and likely
similar versions.
2026-05-25 20:58:05 +02:00
objz 363ada8211 refactored: review findings - style and abstraction cleanup
- drop stale phase planning comments from launch_profile module headers.
 - simplify merge_libraries to HashSet<&str> (no string clones).
 - rewrite coord_key with match_indices (clearer intent).
 - read /proc/sys/kernel/osrelease on linux for mojang_os_version
   instead of shelling out to uname; return empty elsewhere.
 - add comment explaining why is_retryable excludes Parse.
 - shorten the launch_profile::... paths in launch/mod.rs with top-level
   use statements.
 - derive Default on LaunchProfile + nested types so test fixtures use
   ..Default::default() instead of listing every None field.
 - inline account_can_launch at its single call site, delete the helper
   and three tests that exercised trivially-correct one-line logic.
 - extract get_json_with_raw on HttpClient and save_profile_bytes in
   instance::loader; collapses three near-identical fetch_X_profile_with_raw
   helpers and three near-identical 'create dir + write bytes' blocks.
2026-05-25 19:05:48 +02:00
objz 412e6ff91a fixed: review findings - robustness, dead code, missing tests
several smaller fixes from the code review:
 - add os_version to RuleContext + OsCondition for mojang rules that
   constrain natives selection by host version (rare, but in the spec).
 - factor mojang_os_name/arch/version into a shared launch_profile::system
   module instead of duplicating between net/mojang.rs and launch/mod.rs.
 - get_json and get_bytes now retry transient failures (5xx, connect,
   body decode) via a shared get_with_retry envelope; previously only
   download_file had retry logic.
 - migrate_legacy_meta_if_needed falls back to the stale cached profile
   with a warn log on network failure instead of erroring out (offline
   launches now work).
 - tightened legacy-loader detection by requiring the unique-to-rmcl
   gameArguments field; clearer error when loader_version is absent.
 - forge legacy versionInfo write uses compact serialization (no
   pretty-print key reorder).
 - deleted dead fetch_version_meta and save_profile_json.
 - documented quick-play templates omission in templates::lookup.
 - added end-to-end test that loads a vanilla profile from disk, loads a
   loader profile with inheritsFrom, resolves, renders, and snapshots.
2026-05-25 18:24:06 +02:00
objz 19887643bc fixed: critical review findings - extra_args double emission and library dedup
extra_args from the patches module was being passed to build_game_args
(which appended it to game_args) AND emitted again via cmd.args before
game_args - a regression that doubled legacy Forge + lwjgl3ify shim
args. extra_args is now passed only once. also, merge_into now dedups
libraries by group:artifact, preferring the child's entry - without
this, Forge/NeoForge library overrides of vanilla (e.g. log4j) would
silently lose to vanilla because the JVM picks the first classpath
match.
2026-05-25 17:33:52 +02:00
objz a7b378b17d added: Fabric/Quilt raw-bytes profile storage + migration fix
stop re-serializing FabricProfile/QuiltProfile through narrow structs;
new fetch_X_profile_with_raw helpers return both the parsed shape (for
library downloads) and the upstream bytes (written byte-for-byte to the
loader-profiles cache). also fixes a latent issue surfaced by the
change: the legacy-loader migration predicate now skips Fabric and Quilt
explicitly since their upstream shape matches the predicate but they
have no installer JSON to recover from.
2026-05-25 16:56:13 +02:00
objz 8d2b5b9832 added: legacy Forge install_profile.json native pass-through
install_forge_from_profile now writes the upstream versionInfo as compact
JSON (no key reordering, no field stripping) instead of building a custom
{mainClass, libraries, gameArguments} shape. legacy 1.7.10-era Forge
profiles ride the same LaunchProfile + resolve + render pipeline as
modern Forge. drops the no-longer-needed extract_extra_game_args helper.
2026-05-25 16:22:41 +02:00
objz 0d00678a7c added: modern Forge and NeoForge native pass-through (user-facing fix)
stop stripping the installer's version JSON in save_installer_profile -
copy it byte-for-byte so the upstream arguments.jvm (with the
--add-opens flags forge 1.17+ needs on java 17+) reaches launch time.
launch loads the loader profile as LaunchProfile, sets an implicit
inheritsFrom = game_version when absent, resolves through vanilla, then
renders args. classpath assembly unifies into one loop handling both
vanilla-style and loader-style libraries. lazy migration of pre-rework
loader-profiles from the installer's version JSON when still on disk.

fixes the reported Forge 1.17+ on java 17+ IllegalAccessError.
2026-05-25 16:08:47 +02:00
objz 63014726e9 added: inheritsFrom resolution with merge_into and chain walker
new launch_profile::resolve module walks a profile's inheritsFrom chain,
loading parents from meta_dir/versions/<id>/meta.json and merging them
into a single flat LaunchProfile per mojang's documented semantics. pure
merge_into handles field-level merging; async resolve walks the chain
with HashSet-based cycle detection and an 8-level depth cap.
2026-05-25 15:23:09 +02:00
objz 2029005c78 added: vanilla launch flow uses LaunchProfile with render + raw-byte storage
vanilla launches now read upstream mojang JSON via the new LaunchProfile
path, render game/JVM args through launch_profile::render with template
substitution, and store the cached meta.json byte-for-byte instead of
re-serializing through a narrow struct. legacy stripped meta.json files
are re-fetched on first launch. adds HttpClient::get_bytes and
fetch_version_meta_with_raw; collapses the two library-rule evaluators
into one shared launch_profile::rules::evaluate.
2026-05-25 14:51:34 +02:00
objz 22e4481a2b added: launch_profile foundation primitives (rules, templates, model)
introduce the launch_profile module with the core types and pure functions
needed to parse, evaluate, and substitute against mojang-format version
JSON: Rule/OsCondition/FeatureSet with a single rule evaluator,
TemplateContext + substitute() for ${var} expansion, and the
LaunchProfile schema mirroring mojang's on-disk shape. no consumers yet.
2026-05-25 14:02:18 +02:00
objz 50e31f38bb fix(config) default config now uses the rmcl name instead the old mcl 2026-05-20 16:00:22 +02:00
objz 2cc0173873 Merge pull request #7 from objz/hardcoded-min/max-mem
fix(tui): memory_min/max now hardcoded values
2026-05-19 19:58:14 +02:00
objz 681f7974d6 ci: run check, clippy, test, and build on linux, macos, and windows
Expands the PR verification workflow into a cross-platform matrix so we
catch platform-specific breakage before merge. Adds concurrency to cancel
superseded PR runs.
2026-05-19 19:56:13 +02:00
objz a54e53038a fix(tui): memory_min/max now uses the real values from the config.toml instead of hardcoded values. same for java_path 2026-05-19 19:33:54 +02:00
objz 17bb771020 doc: fixed naming 2026-05-13 21:57:38 +02:00
objz c3ea0bc592 ci(winget): set GH_REPO so gh release upload finds the repo without a checkout 2026-05-13 21:26:54 +02:00
110 changed files with 10793 additions and 1751 deletions

No files matched your search

+31 -6
View File
@@ -1,4 +1,4 @@
name: build
name: ci
on:
push:
@@ -9,9 +9,22 @@ on:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
jobs:
check:
runs-on: ubuntu-latest
verify:
name: ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v6
@@ -28,9 +41,21 @@ jobs:
java-version: "21"
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.os }}
- name: check
run: cargo check --locked
- name: cargo check
run: cargo check --locked --all-targets
- name: clippy
- name: cargo clippy
run: cargo clippy --all-targets --locked -- -D warnings
- name: cargo test
run: cargo test --locked --all-targets
- name: cargo build
run: cargo build --locked
- name: cargo test --ignored (network canaries, master only)
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: cargo test --locked --all-targets -- --ignored
-1
View File
@@ -46,7 +46,6 @@ jobs:
checksum="$(awk '{print $1}' "$package_dir/$checksum_file")"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/chocolateyInstall.ps1"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/VERIFICATION.txt"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "package_dir=$package_dir" >> "$GITHUB_OUTPUT"
+1
View File
@@ -104,6 +104,7 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PLAN: ${{ inputs.plan }}
run: |
$plan = $env:PLAN | ConvertFrom-Json
Generated
+290 -1
View File
@@ -120,6 +120,16 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
[[package]]
name = "assert-json-diff"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "async-trait"
version = "0.1.89"
@@ -480,6 +490,17 @@ dependencies = [
"yaml-rust2",
]
[[package]]
name = "console"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
dependencies = [
"encode_unicode",
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "const-oid"
version = "0.10.2"
@@ -761,6 +782,24 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "deadpool"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"
dependencies = [
"deadpool-runtime",
"lazy_static",
"num_cpus",
"tokio",
]
[[package]]
name = "deadpool-runtime"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
[[package]]
name = "deflate64"
version = "0.1.12"
@@ -927,6 +966,12 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "encode_unicode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]]
name = "encoding_rs"
version = "0.8.35"
@@ -1008,6 +1053,15 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"
[[package]]
name = "fast-strip-ansi"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3086ffd0a7160f58f988c74173a002e255da505a114e2f5425acb1eaab2b8ac"
dependencies = [
"vt-push-parser",
]
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -1105,6 +1159,21 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futures"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
@@ -1112,6 +1181,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
@@ -1120,6 +1190,17 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-executor"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.32"
@@ -1149,12 +1230,19 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-timer"
version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
@@ -1165,6 +1253,16 @@ dependencies = [
"slab",
]
[[package]]
name = "gdb-command"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73b2762e2f2c0768e1137b33e9f7cf31599994e96496f4e020cc16e0d4e66319"
dependencies = [
"regex",
"wait-timeout",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -1235,6 +1333,31 @@ version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "h2"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"
dependencies = [
"atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
"http",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
@@ -1282,6 +1405,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
[[package]]
name = "hex"
version = "0.4.3"
@@ -1336,6 +1465,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.11"
@@ -1355,9 +1490,11 @@ dependencies = [
"bytes",
"futures-channel",
"futures-core",
"h2",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
@@ -1622,6 +1759,18 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "insta"
version = "1.47.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b4a6248eb93a4401ed2f37dfe8ea592d3cf05b7cf4f8efa867b6895af7e094e"
dependencies = [
"console",
"once_cell",
"similar",
"tempfile",
]
[[package]]
name = "instability"
version = "0.3.12"
@@ -1797,6 +1946,12 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "kodama"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f868feceed4703c842925c14232667c5f29c8059d0354154b2d06ec3bf9daf82"
[[package]]
name = "kqueue"
version = "1.1.1"
@@ -1847,6 +2002,19 @@ version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libcasr"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "159cff1fadbb464709c30306774c57171e98cc1ea41e7767df5c63819743a453"
dependencies = [
"chrono",
"gdb-command",
"kodama",
"regex",
"thiserror 2.0.18",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -2118,6 +2286,16 @@ dependencies = [
"libm",
]
[[package]]
name = "num_cpus"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "num_threads"
version = "0.1.7"
@@ -2498,6 +2676,15 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro-error-attr2"
version = "2.0.0"
@@ -2945,6 +3132,12 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "relative-path"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -3002,7 +3195,7 @@ dependencies = [
[[package]]
name = "rmcl"
version = "0.3.0"
version = "0.3.3"
dependencies = [
"async-trait",
"chrono",
@@ -3012,7 +3205,10 @@ dependencies = [
"crossterm 0.29.0",
"dirs",
"dirs-next",
"fast-strip-ansi",
"image",
"insta",
"libcasr",
"log",
"minecraft-msa-auth",
"notify",
@@ -3022,7 +3218,9 @@ dependencies = [
"ratatui-image",
"ratatui-textarea",
"ratatui-themekit",
"regex",
"reqwest",
"rstest",
"serde",
"serde_json",
"tachyonfx",
@@ -3040,6 +3238,7 @@ dependencies = [
"tui-scrollview",
"tui-widget-list",
"which",
"wiremock",
"zip",
]
@@ -3057,6 +3256,36 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "rstest"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035"
dependencies = [
"futures",
"futures-timer",
"rstest_macros",
"rustc_version",
]
[[package]]
name = "rstest_macros"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a"
dependencies = [
"cfg-if",
"glob",
"proc-macro-crate",
"proc-macro2",
"quote",
"regex",
"relative-path",
"rustc_version",
"syn 2.0.117",
"unicode-ident",
]
[[package]]
name = "rust-ini"
version = "0.21.3"
@@ -3352,6 +3581,12 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "similar"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
[[package]]
name = "siphasher"
version = "1.0.2"
@@ -3783,6 +4018,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.11+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.2+spec-1.1.0"
@@ -4125,6 +4372,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
[[package]]
name = "vt-push-parser"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdbf39d53c5a50cad8119d9cde929ecd208764e8d8d1626486b8929cbcd5f0e7"
dependencies = [
"hex",
"smallvec",
]
[[package]]
name = "vtparse"
version = "0.6.2"
@@ -4134,6 +4391,15 @@ dependencies = [
"utf8parse",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -4729,6 +4995,29 @@ dependencies = [
"memchr",
]
[[package]]
name = "wiremock"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"
dependencies = [
"assert-json-diff",
"base64",
"deadpool",
"futures",
"http",
"http-body-util",
"hyper",
"hyper-util",
"log",
"once_cell",
"regex",
"serde",
"serde_json",
"tokio",
"url",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
+9 -2
View File
@@ -1,9 +1,9 @@
[package]
name = "rmcl"
version = "0.3.0"
version = "0.3.3"
authors = ["objz"]
edition = "2024"
description = "A fully featured Minecraft launcher TUI"
description = "A fully featured Minecraft TUI launcher"
repository = "https://github.com/objz/rmcl"
homepage = "https://github.com/objz/rmcl"
license = "GPL-3.0-only"
@@ -58,6 +58,9 @@ open = "5"
which = "8.0.2"
dirs = "6.0.0"
notify = "8"
regex = "1"
fast-strip-ansi = "0.13"
libcasr = "2.13"
[profile.release]
@@ -73,3 +76,7 @@ lto = "thin"
[dev-dependencies]
tempfile = "3"
insta = "1"
wiremock = "0.6"
rstest = "0.23"
image = { version = "0.25", default-features = false, features = ["png"] }
+48 -37
View File
@@ -8,7 +8,7 @@
[![Issues][issues-shield]][issues-url]
[![GPL-3.0 License][license-shield]][license-url]
**R**ust **M**ine**C**raft **L**auncher. or **R**ust **M**ine**C**raft c**L**i. pick whichever sounds better to you.
**R**usty **M**ine**C**raft **L**auncher. or **R**ust **M**ine**C**raft c**L**i. pick whichever sounds better to you.
![screenshot](assets/screenshot.png)
@@ -20,23 +20,27 @@
## about
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust because if you're replacing something bloated you might as well go all the way.
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust.
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation.
it does everything you'd expect from a launcher.
![showcase](assets/showcase.gif)
## features
| Mod Loader | Supported |
|------------|-----------|
| Vanilla | ✅ |
| Fabric | ✅ |
| Forge | ✅ |
| NeoForge | ✅ |
| Quilt | ✅ |
| LiteLoader | ❌ |
| Rift | ❌ |
| | |
|---|---|
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later |
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
| **desktop shortcuts** | click it and Minecraft starts, no need to open rmcl or type anything |
| **CLI** | every feature the TUI has is also available as a subcommand |
| **theming** | 10 built-in themes, custom themes, color overrides |
### modpacks and accounts
`Modrinth`, `MultiMC`, and `GTNH` modpacks format is supported. Import it from a file, URL, or just the slug. Able to use multiple Microsoft accounts and offline accounts aswell.
---
@@ -48,10 +52,14 @@ Authentication is performed through Microsoft’s official services.
## installation
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
### macOS / Linux
prebuilt archives are attached to each GitHub release.
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
```sh
# Homebrew
brew install objz/tap/rmcl
@@ -62,6 +70,9 @@ brew install objz/tap/rmcl
release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey
packages are submitted from release CI and become available after review.
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
```powershell
# WinGet
winget install Objz.Rmcl
@@ -72,6 +83,10 @@ choco install rmcl
### Arch Linux
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
```sh
# from source (release tarball)
paru -S rmcl
@@ -85,29 +100,11 @@ paru -S rmcl-git
### Cargo
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
```sh
cargo install rmcl
```
### package status
release:
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
package managers:
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
aur:
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
### from source
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
@@ -132,7 +129,7 @@ settings, accounts, instances, and cached game metadata.
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
### logs
@@ -145,9 +142,23 @@ launcher logs are per-session and contain rmcl's own output. instance launch log
---
## configuration
## performance
everything is configured through TOML files. `config.toml` for paths, default memory allocation, and UI behavior. `theme.toml` for theme selection and border style. you can also override individual colors without making a full custom theme.
the following measurements were taken from a release build on a Linux development system. they are intended as a practical reference, since terminal, window size, content count, and hardware all affect the result.
### idle instance list
over a `60` second sample, the instance list used `497.81 ms` of CPU time. that is about `0.83%` of one CPU core. resident memory was `15.1 MiB`.
### idle mods list
with a populated mods list and its icons loaded, a `60` second sample used `664.77 ms` of CPU time. that is about `1.11%` of one CPU core. resident memory was `67.2 MiB`, with a peak of `69.9 MiB`.
### scrolling mods list
continuously scrolling through the populated mods list used `1000.02 ms` of CPU time over 30 seconds. that is about `3.33%` of one CPU core.
In comparison, the Modrinth AppImage used approximately `14-30%` of a CPU core and about `327 Mib` of memory while browsing the mod list.
---
@@ -163,7 +174,7 @@ you can create your own by dropping a TOML file in `~/.config/rmcl/theme/` and r
## contributing
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md) for code style and project structure.
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md)
---
+4 -2
View File
@@ -1,9 +1,9 @@
[paths]
# where instances are stored
instances_dir = "~/.local/share/mcl/instances"
instances_dir = "~/.local/share/rmcl/instances"
# metadata, cache, whatever else ends up there
meta_dir = "~/.local/share/mcl/meta"
meta_dir = "~/.local/share/rmcl/meta"
# optional java override (empty = uses JAVA_HOME)
java_path = ""
@@ -14,6 +14,8 @@ memory_min = "512M"
memory_max = "2G"
[ui]
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2
image_protocol = "kitty"
# error popup timing (in ms)
error_auto_dismiss_ms = 5000
error_slide_start_ms = 3500
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB

+2 -1
View File
@@ -5,7 +5,7 @@
<version>0.0.0</version>
<packageSourceUrl>https://github.com/objz/rmcl</packageSourceUrl>
<owners>objz</owners>
<title>rmcl</title>
<title>rmcl Minecraft Launcher</title>
<authors>objz</authors>
<projectUrl>https://github.com/objz/rmcl</projectUrl>
<licenseUrl>https://github.com/objz/rmcl/blob/master/LICENSE</licenseUrl>
@@ -13,6 +13,7 @@
<projectSourceUrl>https://github.com/objz/rmcl</projectSourceUrl>
<docsUrl>https://github.com/objz/rmcl#readme</docsUrl>
<bugTrackerUrl>https://github.com/objz/rmcl/issues</bugTrackerUrl>
<releaseNotes>https://github.com/objz/rmcl/releases</releaseNotes>
<tags>minecraft launcher cli tui rust</tags>
<summary>Minecraft launcher TUI</summary>
<description>A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.</description>
-12
View File
@@ -1,12 +0,0 @@
VERIFICATION
This package downloads the official MSI from the GitHub release:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi
The SHA256 checksum is generated by cargo-dist and published next to the release asset:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi.sha256
Expected SHA256:
__CHECKSUM64__
+5
View File
@@ -20,11 +20,16 @@ pkgver() {
}
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl"
cargo test --release --locked
}
+5
View File
@@ -15,11 +15,16 @@ source=("${url}/archive/v${pkgver}.tar.gz")
sha256sums=('SKIP')
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl-${pkgver}"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl-${pkgver}"
cargo test --release --locked
}
+75 -23
View File
@@ -39,9 +39,27 @@ impl AccountStore {
pub fn load() -> Self {
let path = account_store_path();
let accounts = match std::fs::read_to_string(&path) {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
Err(_) => Vec::new(),
Ok(content) => match serde_json::from_str(&content) {
Ok(accounts) => accounts,
Err(e) => {
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
Vec::new()
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("No accounts file at {}", path.display());
Vec::new()
}
Err(e) => {
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
Vec::new()
}
};
tracing::debug!(
"Loaded {} account(s) from {}",
accounts.len(),
path.display()
);
Self { accounts, path }
}
@@ -55,7 +73,17 @@ impl AccountStore {
match serde_json::to_string_pretty(&self.accounts) {
Ok(json) => {
if let Err(e) = std::fs::write(&self.path, json) {
tracing::error!("Failed to write accounts file: {}", e);
tracing::error!(
"Failed to write accounts file {}: {}",
self.path.display(),
e
);
} else {
tracing::debug!(
"Saved {} account(s) to {}",
self.accounts.len(),
self.path.display()
);
}
}
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
@@ -73,9 +101,18 @@ impl AccountStore {
}
pub fn set_active(&mut self, index: usize) {
let username = self
.accounts
.get(index)
.map(|account| account.username.clone());
for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index;
}
if let Some(username) = username {
tracing::info!("Selected account '{}'", username);
} else {
tracing::warn!("Tried to select missing account index {}", index);
}
self.save();
}
@@ -83,22 +120,38 @@ impl AccountStore {
// first account added auto-becomes active so there's always a selection.
pub fn add(&mut self, account: Account) {
let uuid = &account.uuid;
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
let account_type = account.account_type.clone();
let username = account.username.clone();
self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account;
if self.accounts.is_empty() {
account.active = true;
}
self.accounts.push(account);
tracing::info!(
"{} {:?} account '{}'",
if replaced { "Updated" } else { "Added" },
account_type,
username
);
self.save();
}
pub fn remove(&mut self, index: usize) {
if index >= self.accounts.len() {
tracing::warn!("Tried to remove missing account index {}", index);
return;
}
let account = self.accounts.remove(index);
tracing::info!(
"Removed {:?} account '{}'",
account.account_type,
account.username
);
if account.active && !self.accounts.is_empty() {
self.accounts[0].active = true;
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
}
self.save();
}
@@ -186,7 +239,10 @@ mod tests {
assert_eq!(acc.account_type, AccountType::Offline);
assert!(!acc.active);
assert!(acc.refresh_token.is_none());
assert!(!acc.uuid.is_empty());
// pin the uuid to the deterministic offline_uuid output so a regression
// in the uuid derivation (e.g. salt change) would fail this test, not
// just a non-empty-string check that any garbage would pass.
assert_eq!(acc.uuid, offline_uuid("TestPlayer"));
}
fn make_store(dir: &std::path::Path) -> AccountStore {
@@ -196,10 +252,6 @@ mod tests {
}
}
fn dummy_account(name: &str) -> Account {
create_offline_account(name)
}
fn microsoft_account(name: &str) -> Account {
Account {
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
@@ -216,7 +268,7 @@ mod tests {
fn store_add_first_becomes_active() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(create_offline_account("Alice"));
assert_eq!(store.accounts.len(), 1);
assert!(store.accounts[0].active);
}
@@ -225,8 +277,8 @@ mod tests {
fn store_add_second_stays_inactive() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(dummy_account("Bob"));
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
assert_eq!(store.accounts.len(), 2);
assert!(store.accounts[0].active);
assert!(!store.accounts[1].active);
@@ -236,8 +288,8 @@ mod tests {
fn store_add_duplicate_uuid_replaces() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
let mut dup = dummy_account("Alice");
store.add(create_offline_account("Alice"));
let mut dup = create_offline_account("Alice");
dup.username = "AliceRenamed".to_owned();
dup.uuid = store.accounts[0].uuid.clone();
store.add(dup);
@@ -256,7 +308,7 @@ mod tests {
fn store_has_microsoft_account_when_one_exists() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Offline"));
store.add(create_offline_account("Offline"));
assert!(!store.has_microsoft_account());
store.add(microsoft_account("Owner"));
@@ -267,8 +319,8 @@ mod tests {
fn store_active_account_returns_active() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(dummy_account("Bob"));
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
let active = store.active_account().unwrap();
assert_eq!(active.username, "Alice");
}
@@ -277,8 +329,8 @@ mod tests {
fn store_set_active_changes_active() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(dummy_account("Bob"));
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
store.set_active(1);
assert!(!store.accounts[0].active);
assert!(store.accounts[1].active);
@@ -288,8 +340,8 @@ mod tests {
fn store_remove_activates_first_remaining() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(dummy_account("Bob"));
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
store.remove(0);
assert_eq!(store.accounts.len(), 1);
assert_eq!(store.accounts[0].username, "Bob");
@@ -300,7 +352,7 @@ mod tests {
fn store_remove_out_of_bounds_noop() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(create_offline_account("Alice"));
store.remove(5);
assert_eq!(store.accounts.len(), 1);
}
@@ -309,8 +361,8 @@ mod tests {
fn store_save_and_reload() {
let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
store.add(dummy_account("Bob"));
store.add(create_offline_account("Alice"));
store.add(create_offline_account("Bob"));
store.save();
let reloaded = AccountStore {
+2
View File
@@ -61,6 +61,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
user_code: details.user_code().secret().to_owned(),
verification_uri: details.verification_uri().to_string(),
});
crate::tui::request_redraw();
}
let token = oauth_client
@@ -85,6 +86,7 @@ pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
let outcome = run_full_auth_flow().await;
if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome);
crate::tui::request_redraw();
}
});
+1 -1
View File
@@ -95,7 +95,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
}
println!(
"Importing '{}' — {} {} ({} mods, {} overrides)",
"Importing '{}' - {} {} ({} mods, {} overrides)",
summary.name,
summary.game_version,
summary.loader,
+78 -4
View File
@@ -11,6 +11,7 @@ use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState;
type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default";
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
match matches.subcommand() {
@@ -20,6 +21,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
Some(("rename", sub_matches)) => rename_instance(sub_matches),
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
Some(("config", sub_matches)) => config_instance(sub_matches),
Some(("profile", sub_matches)) => profile_instance(sub_matches),
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
_ => Ok(()),
}
@@ -134,7 +136,6 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let config = manager.load_one(name)?;
println!("Launching '{}'...", name);
crate::instance::launch::launch(&config, &instances_dir, &meta_dir)
.await
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
@@ -144,16 +145,15 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
loop {
match crate::running::get(name) {
Some(RunState::Crashed(Some(code))) => {
println!("Game exited with status {}.", code);
println!("Game exited with status {}", code);
break;
}
Some(RunState::Crashed(None)) => {
println!("Game was terminated.");
println!("Game was terminated");
break;
}
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
None => {
println!("Game exited with status 0.");
break;
}
}
@@ -235,12 +235,86 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
.map(|(width, height)| format!("{}x{}", width, height))
.unwrap_or_else(|| "-".to_string()),
],
vec![
"config-sync-profile".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
];
print_table(&["Field", "Value"], &rows);
Ok(())
}
fn profile_instance(matches: &ArgMatches) -> CliResult {
let name = required_arg(matches, "name")?;
let manager = manager();
let mut config = manager.load_one(name)?;
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
if config
.config_sync_profile
.as_ref()
.is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile))
{
config.config_sync_profile = None;
manager.save(&config)?;
}
let Some(profile) = matches.get_one::<String>("profile") else {
let rows = vec![
vec![
"current".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
vec![
"available".to_string(),
if profiles.is_empty() {
LOCAL_CONFIG_PROFILE.to_string()
} else {
format!("{}, {}", LOCAL_CONFIG_PROFILE, profiles.join(", "))
},
],
];
print_table(&["Field", "Value"], &rows);
return Ok(());
};
let target = if is_local_profile_alias(profile) {
None
} else {
Some(profile.as_str())
};
let instance_dir = manager.instances_dir.join(&config.name);
let selected = crate::instance::config_sync::switch_profile(
&config.name,
config.config_sync_profile.as_deref(),
target,
&manager.meta_dir,
&instance_dir,
)?;
config.config_sync_profile = selected;
manager.save(&config)?;
println!(
"Updated '{}' config profile to {}.",
name,
display_config_profile(config.config_sync_profile.as_deref())
);
Ok(())
}
fn display_config_profile(profile: Option<&str>) -> &str {
profile.unwrap_or(LOCAL_CONFIG_PROFILE)
}
fn is_local_profile_alias(profile: &str) -> bool {
let profile = profile.trim();
profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance-default")
|| profile.eq_ignore_ascii_case("instance default")
}
// maps --set key=value pairs to config fields. empty value = clear the field.
fn apply_config_update(
config: &mut crate::instance::InstanceConfig,
+7 -21
View File
@@ -91,47 +91,33 @@ use super::utils::{require_instance, required_arg};
mod tests {
use super::resolve_log_path;
fn unique_temp_dir() -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"rmcl_cli_log_test_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("time should work")
.as_nanos()
))
}
#[test]
fn resolves_latest_log_when_no_file_is_given() {
let root = unique_temp_dir();
let dir = root.join("demo/.minecraft/logs/launches");
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/.minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
let path = resolve_log_path(&root, "demo", None).expect("latest log should resolve");
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("2024-01-02_03-04-05.log")
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn resolves_named_log_file() {
let root = unique_temp_dir();
let dir = root.join("demo/.minecraft/logs/launches");
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/.minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
let path =
resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve");
let path = resolve_log_path(tmp.path(), "demo", Some("latest.log"))
.expect("named log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("latest.log")
);
let _ = std::fs::remove_dir_all(&root);
}
}
+15 -1
View File
@@ -104,6 +104,13 @@ fn build_command() -> Command {
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
)
.subcommand(
Command::new("profile")
.about("Show or set an instance config-sync profile")
.arg_required_else_help(true)
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("profile").action(ArgAction::Set)),
)
.subcommand(
Command::new("desktop")
.about("Toggle desktop shortcut for an instance")
@@ -247,6 +254,13 @@ mod tests {
let matches = build_command()
.try_get_matches_from(["rmcl", "instance", "list"])
.expect("command should parse");
assert!(matches.subcommand_matches("instance").is_some());
let instance = matches
.subcommand_matches("instance")
.expect("instance subcommand should be present");
assert_eq!(
instance.subcommand_name(),
Some("list"),
"instance list should resolve to the list subcommand"
);
}
}
+19 -3
View File
@@ -22,15 +22,31 @@ pub fn get_config_path() -> PathBuf {
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent) = config_path.parent() {
let _ = fs::create_dir_all(parent);
if let Some(parent) = config_path.parent()
&& let Err(e) = fs::create_dir_all(parent)
{
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
Err(e) => tracing::warn!(
"Failed to write default config to {}: {}",
config_path.display(),
e
),
}
} else {
tracing::trace!("Using existing config at {}", config_path.display());
}
config_path
}
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
tracing::debug!("Loading config from {}", config_path.display());
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()?
+13 -37
View File
@@ -5,6 +5,16 @@ use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageProtocol {
Halfblocks,
Quadrants,
#[default]
Kitty,
Iterm2,
}
#[derive(Debug, Deserialize, Default)]
pub struct General {}
@@ -102,6 +112,8 @@ impl Default for Defaults {
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui {
#[serde(default)]
pub image_protocol: ImageProtocol,
#[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64,
#[serde(default = "default_error_slide_start_ms")]
@@ -128,6 +140,7 @@ fn default_max_error_events() -> usize {
impl Default for Ui {
fn default() -> Self {
Self {
image_protocol: ImageProtocol::default(),
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(),
@@ -197,43 +210,6 @@ mod tests {
assert!(!resolved.to_string_lossy().starts_with('~'));
}
#[test]
fn resolve_instances_dir_absolute() {
let paths = Paths {
instances_dir: "/opt/rmcl/instances".to_owned(),
..Paths::default()
};
assert_eq!(
paths.resolve_instances_dir(),
PathBuf::from("/opt/rmcl/instances")
);
}
#[test]
fn resolve_meta_dir_absolute() {
let paths = Paths {
meta_dir: "/opt/rmcl/meta".to_owned(),
..Paths::default()
};
assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/rmcl/meta"));
}
#[test]
fn defaults_have_expected_values() {
let d = Defaults::default();
assert_eq!(d.memory_min, "512M");
assert_eq!(d.memory_max, "2G");
}
#[test]
fn ui_defaults_have_expected_values() {
let ui = Ui::default();
assert_eq!(ui.error_auto_dismiss_ms, 5000);
assert_eq!(ui.error_slide_start_ms, 3500);
assert_eq!(ui.error_fly_out_ms, 300);
assert_eq!(ui.max_error_events, 50);
}
#[test]
fn config_deserializes_from_empty_toml() {
let config: Config = toml::from_str("").unwrap();
+9 -12
View File
@@ -172,18 +172,15 @@ pub static BORDER_STYLE: LazyLock<BorderStyle> =
mod tests {
use super::*;
#[test]
fn default_theme_config() {
let config = ThemeConfig::default();
assert_eq!(config.theme, "catppuccin");
assert_eq!(config.border_style, BorderStyle::Rounded);
assert!(config.custom.is_none());
}
#[test]
fn border_style_roundtrip() {
let style = BorderStyle::Double;
assert_eq!(style.to_border_type(), BorderType::Double);
// cover every BorderStyle variant. a mutation that swaps two arms of the
// match (e.g. Rounded -> Plain) would slip past testing just one variant.
#[rstest::rstest]
#[case::plain(BorderStyle::Plain, BorderType::Plain)]
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
#[case::double(BorderStyle::Double, BorderType::Double)]
#[case::thick(BorderStyle::Thick, BorderType::Thick)]
fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) {
assert_eq!(style.to_border_type(), expected);
}
#[test]
+677
View File
@@ -0,0 +1,677 @@
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigSyncError {
#[error("Invalid config sync profile: {0}")]
InvalidProfile(String),
#[error("Config sync profile '{profile}' is already in use")]
AlreadyLocked { profile: String },
#[error("Cannot switch config profiles while '{instance}' is running")]
InstanceRunning { instance: String },
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Debug)]
pub struct ConfigSyncLock {
path: PathBuf,
}
impl Drop for ConfigSyncLock {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.path)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("Failed to release config sync lock: {}", e);
}
}
}
pub fn prepare(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(None);
};
validate_profile(profile)?;
let profile_dir = profile_dir(meta_dir, profile);
if !profile_dir.exists() {
return Ok(None);
}
let lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(minecraft_dir, &profile_dir)?;
} else {
sync_from_profile(&profile_dir, minecraft_dir)?;
}
Ok(Some(lock))
}
pub fn finish(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<(), ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(());
};
validate_profile(profile)?;
sync_to_profile(minecraft_dir, &profile_dir(meta_dir, profile))
}
pub fn list_profiles(meta_dir: &Path) -> Result<Vec<String>, ConfigSyncError> {
let root = profiles_dir(meta_dir);
let mut profiles = Vec::new();
if !root.exists() {
return Ok(profiles);
}
for entry in std::fs::read_dir(root)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
if validate_profile(&name).is_ok() {
profiles.push(name);
}
}
}
profiles.sort_unstable();
Ok(profiles)
}
pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSyncError> {
let Some(profile) = normalize_profile(profile) else {
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
};
validate_profile(profile)?;
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
Ok(profile.to_string())
}
pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncError> {
validate_profile(profile)?;
let dir = profile_dir(meta_dir, profile);
if dir.exists() {
remove_path(&dir)?;
}
Ok(())
}
pub fn switch_profile(
instance_name: &str,
current_profile: Option<&str>,
target_profile: Option<&str>,
meta_dir: &Path,
instance_dir: &Path,
) -> Result<Option<String>, ConfigSyncError> {
if crate::running::get(instance_name).is_some() {
return Err(ConfigSyncError::InstanceRunning {
instance: instance_name.to_string(),
});
}
let current_profile = current_profile.and_then(normalize_profile);
let target_profile = target_profile.and_then(normalize_profile);
if let Some(profile) = current_profile {
validate_profile(profile)?;
}
if let Some(profile) = target_profile {
validate_profile(profile)?;
}
if current_profile == target_profile {
return Ok(current_profile.map(str::to_string));
}
if let Some(profile) = current_profile {
let profile_dir = profile_dir(meta_dir, profile);
if profile_dir.exists() {
let _lock = acquire_lock(&profile_dir, profile)?;
finish(Some(profile), meta_dir, &minecraft_dir(instance_dir))?;
}
}
match (current_profile, target_profile) {
(None, Some(_)) => {
sync_to_profile(
&minecraft_dir(instance_dir),
&local_backup_dir(instance_dir),
)?;
}
(Some(_), None) => {
let backup = local_backup_dir(instance_dir);
if backup.exists() {
sync_from_profile(&backup, &minecraft_dir(instance_dir))?;
}
return Ok(None);
}
_ => {}
}
let Some(profile) = target_profile else {
return Ok(None);
};
let profile_dir = profile_dir(meta_dir, profile);
let _lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?;
}
sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?;
Ok(Some(profile.to_string()))
}
fn normalize_profile(profile: &str) -> Option<&str> {
let trimmed = profile.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
}
pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
if profile.is_empty()
|| profile.len() > 64
|| profile.starts_with('.')
|| profile.contains('/')
|| profile.contains('\\')
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance default")
|| profile.eq_ignore_ascii_case("local default")
|| profile
.chars()
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
{
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
}
Ok(())
}
fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
profiles_dir(meta_dir).join(profile)
}
fn profiles_dir(meta_dir: &Path) -> PathBuf {
meta_dir.join("config-sync").join("profiles")
}
fn minecraft_dir(instance_dir: &Path) -> PathBuf {
instance_dir.join(".minecraft")
}
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
instance_dir
.join(".rmcl")
.join("config-sync")
.join("local-config")
}
fn acquire_lock(profile_dir: &Path, profile: &str) -> Result<ConfigSyncLock, ConfigSyncError> {
std::fs::create_dir_all(profile_dir)?;
let path = profile_dir.join(".lock");
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_) => Ok(ConfigSyncLock { path }),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
Err(ConfigSyncError::AlreadyLocked {
profile: profile.to_string(),
})
}
Err(e) => Err(e.into()),
}
}
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
if dst.exists() {
remove_path(dst)?;
}
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
copy_dir_contents(src, dst)
}
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&minecraft_dir.join("config"), &profile_dir.join("config"))?;
mirror_options(minecraft_dir, profile_dir)
}
fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&profile_dir.join("config"), &minecraft_dir.join("config"))?;
mirror_options(profile_dir, minecraft_dir)
}
fn profile_payload_exists(profile_dir: &Path) -> Result<bool, ConfigSyncError> {
if profile_dir.join("config").exists() {
return Ok(true);
}
if !profile_dir.exists() {
return Ok(false);
}
for entry in std::fs::read_dir(profile_dir)? {
let entry = entry?;
if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) {
return Ok(true);
}
}
Ok(false)
}
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
remove_options(dst)?;
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let name = entry.file_name();
if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) {
std::fs::copy(entry.path(), dst.join(name))?;
}
}
Ok(())
}
fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> {
if !dir.exists() {
return Ok(());
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if is_options_file(&entry.file_name().to_string_lossy()) {
remove_path(&entry.path())?;
}
}
Ok(())
}
fn is_options_file(name: &str) -> bool {
name == "options.txt" || name.starts_with("options") && name.ends_with(".txt")
}
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
let meta = std::fs::symlink_metadata(path)?;
if meta.is_dir() {
std::fs::remove_dir_all(path)?;
} else {
std::fs::remove_file(path)?;
}
Ok(())
}
fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let source = entry.path();
let target = dst.join(entry.file_name());
let file_type = entry.file_type()?;
if file_type.is_dir() {
std::fs::create_dir_all(&target)?;
copy_dir_contents(&source, &target)?;
} else if file_type.is_file() {
std::fs::copy(&source, &target)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_prepare_seeds_shared_config() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap();
std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap();
std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/optionsshaders.txt"))
.unwrap(),
"shader-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/options.txt"))
.unwrap(),
"local-config"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/nested/mod.toml"))
.unwrap(),
"nested"
);
}
#[test]
fn prepare_mirrors_shared_config_into_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/options.txt"),
"shared-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/shared.toml"),
"shared",
)
.unwrap();
std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap();
std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(),
"shared"
);
assert!(!minecraft.join("config/local.toml").exists());
}
#[test]
fn finish_mirrors_instance_config_back_to_shared() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/old.toml"),
"old",
)
.unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
finish(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"new-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/new.toml"))
.unwrap(),
"new"
);
assert!(
!meta
.join("config-sync/profiles/main/config/old.toml")
.exists()
);
}
#[test]
fn lock_blocks_second_prepare() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
let err = prepare(Some("main"), &meta, &minecraft).unwrap_err();
assert!(matches!(err, ConfigSyncError::AlreadyLocked { .. }));
}
#[test]
fn profile_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
#[test]
fn profile_rejects_builtin_names() {
for profile in [
"none",
"default",
"local",
"instance default",
"local default",
] {
let err = validate_profile(profile).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
}
#[test]
fn prepare_ignores_deleted_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
assert!(lock.is_none());
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn create_profile_trims_and_lists_profiles() {
let tmp = tempfile::tempdir().unwrap();
let profile = create_profile(tmp.path(), " main ").unwrap();
let profiles = list_profiles(tmp.path()).unwrap();
assert_eq!(profile, "main");
assert_eq!(profiles, vec!["main"]);
}
#[test]
fn delete_profile_removes_profile_dir() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
delete_profile(tmp.path(), "main").unwrap();
assert!(list_profiles(tmp.path()).unwrap().is_empty());
}
#[test]
fn switch_to_profile_backs_up_local_config_and_restores_none() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("main"));
assert_eq!(
std::fs::read_to_string(instance.join(".rmcl/config-sync/local-config/options.txt"))
.unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(
instance.join(".rmcl/config-sync/local-config/config/local.txt")
)
.unwrap(),
"local"
);
std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap();
std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap();
let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/shared.txt"))
.unwrap(),
"shared"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!minecraft.join("config/shared.txt").exists());
}
#[test]
fn switch_from_deleted_profile_restores_local_without_recreating_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
"local-options",
)
.unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/config/local.txt"),
"local",
)
.unwrap();
let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn switch_between_profiles_saves_old_and_loads_new() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
create_profile(&meta, "a").unwrap();
std::fs::create_dir_all(meta.join("config-sync/profiles/b/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/options.txt"),
"profile-b-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/config/b.txt"),
"profile-b",
)
.unwrap();
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("b"));
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/options.txt")).unwrap(),
"changed-a-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/config/a.txt")).unwrap(),
"changed-a"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"profile-b-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(),
"profile-b"
);
assert!(!minecraft.join("config/a.txt").exists());
}
#[test]
fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let first = tmp.path().join("first/.minecraft");
let second_instance = tmp.path().join("second");
let second = second_instance.join(".minecraft");
std::fs::create_dir_all(first.join("config")).unwrap();
std::fs::create_dir_all(second.join("config")).unwrap();
std::fs::write(first.join("options.txt"), "first-default").unwrap();
std::fs::write(second.join("options.txt"), "second-local").unwrap();
create_profile(&meta, "main").unwrap();
let _lock = prepare(Some("main"), &meta, &first).unwrap();
std::fs::write(first.join("options.txt"), "changed-in-main").unwrap();
finish(Some("main"), &meta, &first).unwrap();
drop(_lock);
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
assert_eq!(
std::fs::read_to_string(second.join("options.txt")).unwrap(),
"changed-in-main"
);
assert_eq!(
std::fs::read_to_string(
second_instance.join(".rmcl/config-sync/local-config/options.txt")
)
.unwrap(),
"second-local"
);
}
}
+4 -4
View File
@@ -6,11 +6,11 @@ pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use mods::scan_one_mod;
pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
pub use shaders::{scan_shaders, scan_one_shader};
pub use worlds::{scan_worlds, scan_one_world};
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
pub use shaders::{scan_one_shader, scan_shaders};
pub use worlds::{scan_one_world, scan_worlds};
use std::io::Read;
+237 -10
View File
@@ -13,6 +13,7 @@ use serde::Deserialize;
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub symbol: char,
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
@@ -153,12 +154,22 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) {
Ok(file) => file,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e);
return (String::new(), String::new(), None);
}
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(archive) => archive,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!(
"Failed to read mod JAR as ZIP {}: {}",
jar_path.display(),
e
);
return (String::new(), String::new(), None);
}
};
// try each loader's metadata in order. if we get metadata but the
@@ -180,12 +191,23 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
read_zip_bytes(&mut archive, icon_path)
}
.or_else(|| try_fallback_icons(&mut archive));
tracing::trace!(
"Read mod metadata from {}: name='{}' icon_declared={}",
jar_path.display(),
name,
!icon_path.is_empty()
);
return (name, description, icon);
}
}
// no recognized metadata at all, try common icon paths
let icon_bytes = try_fallback_icons(&mut archive);
tracing::trace!(
"No recognized mod metadata in {}; fallback_icon={}",
jar_path.display(),
icon_bytes.is_some()
);
(String::new(), String::new(), icon_bytes)
}
@@ -354,6 +376,14 @@ pub(crate) fn make_icon_pixels(
height: u16,
) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&img, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img.resize_exact(
u32::from(width),
u32::from(height) * 2,
@@ -370,6 +400,7 @@ pub(crate) fn make_icon_pixels(
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push(IconCell {
symbol: '\u{2584}',
bg_r: br,
bg_g: bg,
bg_b: bb,
@@ -381,12 +412,110 @@ pub(crate) fn make_icon_pixels(
rows.push(cols);
}
Some(rows)
rows
}
pub(crate) fn make_icon_quadrants_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|col| {
let x = u32::from(col) * 2;
let y = u32::from(row) * 2;
let pixels = [
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
];
quadrant_cell(pixels)
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
}
// 6x3 fallback icon showing a "?" pattern for mods without icons.
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -395,6 +524,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -403,6 +533,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -420,6 +551,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
// 12x6 fallback icon showing a "?" pattern for worlds without icons.
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -428,6 +560,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -436,6 +569,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -476,6 +610,20 @@ pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("mods");
std::fs::create_dir_all(&dir).unwrap();
@@ -567,7 +715,6 @@ mod tests {
use std::io::Write as _;
// helper to create a jar (zip) file with the given entries
fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) {
let path = dir.join(name);
let file = std::fs::File::create(&path).unwrap();
@@ -700,18 +847,98 @@ description = "A neoforge mod"
assert_eq!(mods[0].name, "Fabric Name");
}
#[test]
fn scan_mods_prefers_quilt_over_forge() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let quilt = r#"{"quilt_loader":{"id":"x","version":"1","metadata":{"name":"Quilt Name","description":"quilt desc"}}}"#;
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"quilt-over-forge.jar",
&[
("quilt.mod.json", quilt.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Quilt Name");
}
#[test]
fn scan_mods_prefers_forge_toml_over_mcmod_info() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
let mcmod = r#"[{"modid":"legacy","name":"Legacy Name","description":"legacy desc"}]"#;
make_jar(
&dir,
"forge-over-legacy.jar",
&[
("META-INF/mods.toml", forge.as_bytes()),
("mcmod.info", mcmod.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Forge Name");
}
// when both neoforge.mods.toml and mods.toml exist in the same jar (the
// shape a dual-format mod might ship), the neoforge one wins because
// read_forge_toml_meta tries it first via .or_else.
#[test]
fn scan_mods_prefers_neoforge_toml_over_forge_toml() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let neoforge =
"[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"neoforge-over-forge.jar",
&[
("META-INF/neoforge.mods.toml", neoforge.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "NeoForge Name");
}
// a mods.toml with logoFile but no [[mods]] array (e.g. a dependency-only
// library jar) should still surface as a scanned mod with empty name +
// description but with the icon resolved.
#[test]
fn scan_mods_reads_mods_toml_without_mods_array() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let mods_toml = "logoFile = \"icon.png\"\n";
let png_bytes = b"\x89PNG fake icon";
make_jar(
&dir,
"lib-only.jar",
&[
("META-INF/mods.toml", mods_toml.as_bytes()),
("icon.png", png_bytes),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
// file-stem fallback when metadata name is empty - covered here
// because no other test exercises an empty-name + present-logo combo.
assert_eq!(mods[0].name, "lib-only");
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
}
#[test]
fn scan_mods_fallback_icon_paths() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
// jar with no metadata but has logo.png
let png_bytes = b"\x89PNG fake";
make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
// should use filename as name since no metadata
assert_eq!(mods[0].name, "no-meta");
// icon_bytes should contain the logo.png content
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
}
@@ -723,10 +950,10 @@ description = "A neoforge mod"
#[test]
fn icon_path_from_value_map() {
// serde_json::Map is a BTreeMap, so iteration is sorted by key.
// "128" sorts before "64" lexicographically, so the first value wins.
let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"});
let result = icon_path_from_value(&val);
// should return one of the values
assert!(result == "icon_64.png" || result == "icon_128.png");
assert_eq!(icon_path_from_value(&val), "icon_128.png");
}
#[test]
+18 -119
View File
@@ -141,125 +141,24 @@ fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>)
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn extract_description_from_string() {
let val = serde_json::json!("Simple pack");
assert_eq!(extract_description(&val), "Simple pack");
}
#[test]
fn extract_description_from_object_with_text() {
let val = serde_json::json!({"text": "Hello world"});
assert_eq!(extract_description(&val), "Hello world");
}
#[test]
fn extract_description_from_object_without_text() {
let val = serde_json::json!({"color": "red"});
assert_eq!(extract_description(&val), "");
}
#[test]
fn extract_description_from_array_of_strings() {
let val = serde_json::json!(["Hello", " ", "world"]);
assert_eq!(extract_description(&val), "Hello world");
}
#[test]
fn extract_description_from_array_of_objects() {
let val = serde_json::json!([{"text": "A"}, {"text": "B"}]);
assert_eq!(extract_description(&val), "AB");
}
#[test]
fn extract_description_from_mixed_array() {
let val = serde_json::json!(["Prefix ", {"text": "suffix"}]);
assert_eq!(extract_description(&val), "Prefix suffix");
}
#[test]
fn extract_description_from_empty_array() {
let val = serde_json::json!([]);
assert_eq!(extract_description(&val), "");
}
#[test]
fn extract_description_from_null() {
let val = serde_json::Value::Null;
assert_eq!(extract_description(&val), "");
}
#[test]
fn extract_description_from_number() {
let val = serde_json::json!(42);
assert_eq!(extract_description(&val), "");
}
#[test]
fn extract_description_from_bool() {
let val = serde_json::json!(true);
assert_eq!(extract_description(&val), "");
}
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("resourcepacks");
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn scan_resource_packs_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_packs_dir(tmp.path(), "inst");
let packs = scan_resource_packs(tmp.path(), "inst");
assert!(packs.is_empty());
}
#[test]
fn scan_resource_packs_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let packs = scan_resource_packs(tmp.path(), "ghost");
assert!(packs.is_empty());
}
#[test]
fn scan_resource_packs_finds_zips_and_dirs() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_packs_dir(tmp.path(), "inst");
std::fs::write(dir.join("pack-a.zip"), b"PK\x03\x04").unwrap();
std::fs::create_dir(dir.join("pack-b")).unwrap();
let packs = scan_resource_packs(tmp.path(), "inst");
assert_eq!(packs.len(), 2);
}
#[test]
fn scan_resource_packs_disabled_variants() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_packs_dir(tmp.path(), "inst");
std::fs::write(dir.join("on.zip"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
std::fs::create_dir(dir.join("diron")).unwrap();
std::fs::create_dir(dir.join("diroff.disabled")).unwrap();
let packs = scan_resource_packs(tmp.path(), "inst");
assert_eq!(packs.len(), 4);
let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap();
let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap();
let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap();
let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap();
assert!(on_zip.enabled);
assert!(!off_zip.enabled);
assert!(on_dir.enabled);
assert!(!off_dir.enabled);
}
#[test]
fn scan_resource_packs_ignores_non_pack_files() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_packs_dir(tmp.path(), "inst");
std::fs::write(dir.join("notes.txt"), "not a pack").unwrap();
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
let packs = scan_resource_packs(tmp.path(), "inst");
assert_eq!(packs.len(), 1);
// every case exercises a distinct match arm in extract_description.
// string + object{text} + object{no text} + array(string) +
// array(object) + array(mixed) + array(empty) + null + number + bool.
// mutating any arm to fall through to "" would fail at least one case.
#[rstest::rstest]
#[case::string(json!("Simple pack"), "Simple pack")]
#[case::object_with_text(json!({"text": "Hello world"}), "Hello world")]
#[case::object_without_text(json!({"color": "red"}), "")]
#[case::array_of_strings(json!(["Hello", " ", "world"]), "Hello world")]
#[case::array_of_objects(json!([{"text": "A"}, {"text": "B"}]), "AB")]
#[case::mixed_array(json!(["Prefix ", {"text": "suffix"}]), "Prefix suffix")]
#[case::empty_array(json!([]), "")]
#[case::null(serde_json::Value::Null, "")]
#[case::number(json!(42), "")]
#[case::bool(json!(true), "")]
fn extract_description_handles(#[case] input: serde_json::Value, #[case] expected: &str) {
assert_eq!(extract_description(&input), expected);
}
}
-62
View File
@@ -89,65 +89,3 @@ fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
(description, icon_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_shaders_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("shaderpacks");
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn scan_shaders_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_shaders_dir(tmp.path(), "inst");
let shaders = scan_shaders(tmp.path(), "inst");
assert!(shaders.is_empty());
}
#[test]
fn scan_shaders_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let shaders = scan_shaders(tmp.path(), "ghost");
assert!(shaders.is_empty());
}
#[test]
fn scan_shaders_finds_zip_and_dir() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_shaders_dir(tmp.path(), "inst");
std::fs::write(dir.join("shader-a.zip"), b"PK\x03\x04").unwrap();
std::fs::create_dir(dir.join("shader-b")).unwrap();
let shaders = scan_shaders(tmp.path(), "inst");
assert_eq!(shaders.len(), 2);
}
#[test]
fn scan_shaders_disabled_variants() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_shaders_dir(tmp.path(), "inst");
std::fs::write(dir.join("active.zip"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
std::fs::create_dir(dir.join("dirshader.disabled")).unwrap();
let shaders = scan_shaders(tmp.path(), "inst");
let active = shaders.iter().find(|s| s.file_stem == "active").unwrap();
let off = shaders.iter().find(|s| s.file_stem == "off").unwrap();
let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap();
assert!(active.enabled);
assert!(!off.enabled);
assert!(!diroff.enabled);
}
#[test]
fn scan_shaders_ignores_non_shader_files() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_shaders_dir(tmp.path(), "inst");
std::fs::write(dir.join("readme.txt"), "not a shader").unwrap();
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
let shaders = scan_shaders(tmp.path(), "inst");
assert_eq!(shaders.len(), 1);
}
}
-77
View File
@@ -134,80 +134,3 @@ fn format_size(bytes: u64) -> String {
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_saves_dir(tmp: &Path, instance: &str) -> std::path::PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("saves");
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn scan_worlds_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_saves_dir(tmp.path(), "inst");
let worlds = scan_worlds(tmp.path(), "inst");
assert!(worlds.is_empty());
}
#[test]
fn scan_worlds_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let worlds = scan_worlds(tmp.path(), "ghost");
assert!(worlds.is_empty());
}
#[test]
fn scan_worlds_finds_directories() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_saves_dir(tmp.path(), "inst");
std::fs::create_dir(dir.join("My World")).unwrap();
std::fs::create_dir(dir.join("Creative")).unwrap();
let worlds = scan_worlds(tmp.path(), "inst");
assert_eq!(worlds.len(), 2);
}
#[test]
fn scan_worlds_ignores_files() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_saves_dir(tmp.path(), "inst");
std::fs::create_dir(dir.join("World1")).unwrap();
std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap();
let worlds = scan_worlds(tmp.path(), "inst");
assert_eq!(worlds.len(), 1);
}
#[test]
fn scan_worlds_disabled_world() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_saves_dir(tmp.path(), "inst");
std::fs::create_dir(dir.join("ActiveWorld")).unwrap();
std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap();
let worlds = scan_worlds(tmp.path(), "inst");
let active = worlds
.iter()
.find(|w| w.file_stem == "ActiveWorld")
.unwrap();
let hidden = worlds
.iter()
.find(|w| w.file_stem == "HiddenWorld")
.unwrap();
assert!(active.enabled);
assert!(!hidden.enabled);
}
#[test]
fn scan_worlds_sorted_case_insensitive() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_saves_dir(tmp.path(), "inst");
std::fs::create_dir(dir.join("Zeta")).unwrap();
std::fs::create_dir(dir.join("alpha")).unwrap();
std::fs::create_dir(dir.join("Beta")).unwrap();
let worlds = scan_worlds(tmp.path(), "inst");
let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names, vec!["alpha", "Beta", "Zeta"]);
}
}
+11 -17
View File
@@ -20,7 +20,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
#[cfg(target_os = "windows")]
{
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.bat")))
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.vbs")))
}
#[cfg(target_os = "macos")]
@@ -141,7 +141,7 @@ fn build_content(name: &str, icon: Option<&Path>) -> String {
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
let mut out = String::new();
out.push_str("[Desktop Entry]\n");
out.push_str("Version=1.0\n");
out.push_str("Version=0.3.1\n");
out.push_str("Type=Application\n");
out.push_str(&format!("Name=Minecraft - {name}\n"));
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
@@ -149,18 +149,21 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
if let Some(icon) = icon {
out.push_str(&format!("Icon={}\n", icon.display()));
}
out.push_str("Terminal=true\n");
out.push_str("Terminal=false\n");
out.push_str("Categories=Game;\n");
out
}
#[cfg(target_os = "windows")]
fn build_windows_shortcut(name: &str) -> String {
let escaped_name = name.replace('"', "\"\"");
let mut out = String::new();
out.push_str("@echo off\r\n");
out.push_str(&format!("title Minecraft - {name}\r\n"));
out.push_str(&format!("rmcl instance launch \"{name}\"\r\n"));
out.push_str("pause\r\n");
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
out.push_str(&format!(
"shell.Run \"rmcl instance launch \"\"{}\"\"\", 0, False\r\n",
escaped_name
));
out
}
@@ -201,22 +204,13 @@ mod tests {
assert_eq!(sanitize("path/traversal"), "path_traversal");
}
#[test]
fn desktop_path_returns_some() {
let path = desktop_path("TestPack");
if let Some(p) = path {
let name = p.file_name().unwrap().to_str().unwrap();
assert!(name.contains("TestPack"));
}
}
#[test]
#[cfg(target_os = "linux")]
fn build_content_linux() {
let content = build_content("TestPack", None);
assert!(content.contains("Name=Minecraft - TestPack"));
assert!(content.contains("Exec=rmcl instance launch \"TestPack\""));
assert!(content.contains("Terminal=true"));
assert!(content.contains("Terminal=false"));
assert!(content.contains("Categories=Game;"));
}
+97 -1
View File
@@ -51,6 +51,11 @@ impl MmcPack {
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let pack = parse_mmc_pack(path)?;
tracing::debug!(
"Parsed MultiMC pack {} with {} component(s)",
path.display(),
pack.components.len()
);
let game_version = pack
.game_version()
@@ -62,6 +67,15 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
let (mod_count, override_count) = count_content_files(path)?;
tracing::trace!(
"MultiMC summary: name='{}' game_version={} loader={:?} loader_version={:?} mods={} overrides={}",
name,
game_version,
loader,
loader_version,
mod_count,
override_count
);
Ok(ImportSummary {
name,
@@ -81,6 +95,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing MultiMC/Prism pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -99,6 +118,11 @@ pub async fn execute_import(
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!(
"Imported MultiMC/Prism pack '{}' as '{}'",
summary.name,
name
);
Ok(config)
}
@@ -117,8 +141,16 @@ fn extract_mmc_archive(
let prefix = find_archive_prefix(&archive);
let minecraft_prefix = format!("{prefix}.minecraft/");
tracing::debug!(
"Extracting MultiMC archive {} with prefix '{}' into {}",
archive_path.display(),
prefix,
minecraft_dir.display()
);
let total = archive.len();
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..total {
let mut entry = archive.by_index(i)?;
let entry_name = entry.name().to_string();
@@ -129,6 +161,7 @@ fn extract_mmc_archive(
if relative.is_empty() || entry_name.ends_with('/') {
std::fs::create_dir_all(minecraft_dir.join(relative))?;
dirs += 1;
continue;
}
@@ -142,9 +175,22 @@ fn extract_mmc_archive(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting MultiMC entry {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} files and {} directories from MultiMC archive {}",
extracted,
dirs,
archive_path.display()
);
Ok(())
}
@@ -167,6 +213,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
let mut archive = zip::ZipArchive::new(file).ok()?;
let entry_name = find_entry(&archive, "instance.cfg")?;
tracing::trace!("Reading instance name from {}", entry_name);
let entry = archive.by_name(&entry_name).ok()?;
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
@@ -174,6 +221,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
if let Some(value) = line.strip_prefix("name=") {
let name = value.trim().to_string();
if !name.is_empty() {
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
return Some(name);
}
}
@@ -181,7 +229,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
None
}
// finds the prefix for the archive — empty for flat zips, "DirName/" for nested
// finds the prefix for the archive: empty for flat zips, "DirName/" for nested
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
for name in archive.file_names() {
if name.ends_with("mmc-pack.json") {
@@ -269,4 +317,52 @@ mod tests {
let pack: MmcPack = serde_json::from_str(json).unwrap();
assert!(pack.loader().0.is_none());
}
// builds an in-memory mmc-style pack zip and verifies that
// extract_mmc_archive copies only the .minecraft/ subtree into the
// destination, preserving relative paths and skipping siblings.
#[test]
fn extract_mmc_archive_copies_minecraft_subtree() {
use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
let archive_path = tmp.path().join("pack.zip");
let dest = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(&dest).unwrap();
// Pack/ is the prefix; only .minecraft/ entries should land in dest.
// mmc-style pack: a root dir "Pack/" wrapping the .minecraft tree
// plus a sibling mmc-pack.json that should NOT be extracted.
{
let file = std::fs::File::create(&archive_path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
zip.start_file("Pack/mmc-pack.json", opts).unwrap();
zip.write_all(b"{}").unwrap();
zip.start_file("Pack/.minecraft/options.txt", opts).unwrap();
zip.write_all(b"lang:en_us").unwrap();
zip.start_file("Pack/.minecraft/mods/test-mod.jar", opts)
.unwrap();
zip.write_all(b"jar-bytes").unwrap();
zip.finish().unwrap();
}
extract_mmc_archive(&archive_path, &dest).expect("extract");
// .minecraft/ entries must have been copied with their relative paths
let options = std::fs::read(dest.join("options.txt")).expect("options.txt");
assert_eq!(options, b"lang:en_us");
let modjar = std::fs::read(dest.join("mods/test-mod.jar")).expect("mods/test-mod.jar");
assert_eq!(modjar, b"jar-bytes");
// and the sibling outside .minecraft/ must not have been copied
assert!(
!dest.join("mmc-pack.json").exists(),
"mmc-pack.json should not land in the instance dir"
);
}
}
+109 -3
View File
@@ -33,6 +33,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|| input.starts_with('/')
|| input.starts_with("~/")
{
tracing::debug!("Import input resolved as local file: {}", input);
return ImportInput::LocalFile(input.to_string());
}
@@ -41,7 +42,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
{
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
return match parts.as_slice() {
let parsed = match parts.as_slice() {
[slug, "version", version_id, ..] => ImportInput::VersionId {
slug: slug.to_string(),
version_id: version_id.to_string(),
@@ -49,8 +50,11 @@ pub fn parse_import_input(input: &str) -> ImportInput {
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
[] => ImportInput::ProjectSlug(String::new()),
};
tracing::debug!("Import input resolved as Modrinth URL: {:?}", parsed);
return parsed;
}
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
ImportInput::ProjectSlug(input.to_string())
}
@@ -70,12 +74,14 @@ pub struct ImportSummary {
// peeks inside a zip to figure out what format it is.
// checks for modrinth.index.json first, then mmc-pack.json.
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
tracing::debug!("Detecting modpack format for {}", path.display());
let file =
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
let archive =
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
if archive.file_names().any(|n| n == "modrinth.index.json") {
tracing::debug!("Detected Modrinth .mrpack archive: {}", path.display());
return Ok(PackFormat::Mrpack);
}
@@ -84,21 +90,36 @@ pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
.file_names()
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
{
tracing::debug!("Detected MultiMC/Prism archive: {}", path.display());
return Ok(PackFormat::Mmc);
}
tracing::warn!("Unknown modpack archive format: {}", path.display());
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
if !path.exists() {
tracing::warn!("Cannot import missing file {}", path.display());
return Err(format!("File not found: {}", path.display()));
}
let format = detect_format(path)?;
match format {
let summary = match format {
PackFormat::Mrpack => mrpack::build_summary(path),
PackFormat::Mmc => mmc::build_summary(path),
}
}?;
tracing::debug!(
"Built import summary for {}: name='{}' format={:?} mc={} loader={} loader_version={:?} mods={} overrides={}",
path.display(),
summary.name,
summary.format,
summary.game_version,
summary.loader,
summary.loader_version,
summary.mod_count,
summary.override_count
);
Ok(summary)
}
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
@@ -108,6 +129,7 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::trace!("Import instance name '{}' is available", candidate);
return candidate;
}
for n in 2..100 {
@@ -117,9 +139,18 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::debug!(
"Import instance name '{}' collided; using '{}'",
base,
candidate
);
return candidate;
}
}
tracing::warn!(
"Import instance name '{}' had many collisions; using fallback suffix",
base
);
format!("{base} (import)")
}
@@ -127,6 +158,12 @@ pub async fn execute_import(
summary: &ImportSummary,
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
tracing::info!(
"Executing {:?} import '{}' from {}",
summary.format,
summary.name,
summary.archive_path.display()
);
match summary.format {
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
@@ -136,6 +173,75 @@ pub async fn execute_import(
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf {
let path = tmp.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
for (filename, bytes) in entries {
zip.start_file(*filename, opts).unwrap();
zip.write_all(bytes).unwrap();
}
zip.finish().unwrap();
path
}
#[test]
fn detect_format_recognises_mrpack() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
#[test]
fn detect_format_recognises_mmc_flat() {
// mmc-pack.json at the zip root - the flat layout that some mmc
// archives use.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
#[test]
fn detect_format_recognises_mmc_nested() {
// mmc-pack.json one directory deep - the more common layout where
// the archive wraps everything in a named directory.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
#[test]
fn detect_format_prefers_mrpack_when_both_markers_present() {
// a zip with both markers should resolve to Mrpack since the
// detector checks modrinth.index.json first.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"weird.zip",
&[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")],
);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
#[test]
fn detect_format_errors_on_unknown_archive() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "random.zip", &[("readme.txt", b"hello")]);
let err = detect_format(&path).unwrap_err();
assert!(
err.contains("Unknown pack format"),
"expected unknown format error, got: {err}"
);
}
#[test]
fn detect_format_errors_on_missing_file() {
let err = detect_format(Path::new("/nonexistent/pack.zip")).unwrap_err();
assert!(err.contains("Cannot open"), "got: {err}");
}
#[test]
fn unique_name_no_collision() {
+66 -4
View File
@@ -12,6 +12,13 @@ use super::{ImportSummary, PackFormat};
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let index = crate::net::modrinth::parse_mrpack(path)?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
@@ -21,6 +28,13 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(path).unwrap_or(0);
tracing::trace!(
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
game_version,
loader,
loader_version,
override_count
);
Ok(ImportSummary {
name: index.name.clone(),
@@ -54,6 +68,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing Modrinth pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -78,6 +97,7 @@ pub async fn execute_import(
extract_overrides(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!("Imported Modrinth pack '{}' as '{}'", summary.name, name);
Ok(config)
}
@@ -93,6 +113,12 @@ async fn download_mod_files(
let client = crate::net::HttpClient::new();
let total = index.files.len();
let completed = Arc::new(AtomicUsize::new(0));
tracing::debug!(
"Downloading {} file(s) from .mrpack '{}' into {}",
total,
index.name,
minecraft_dir.display()
);
progress::set_action(format!("Downloading mods... 0/{total}"));
@@ -107,6 +133,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -115,10 +144,17 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -136,6 +172,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -144,10 +183,17 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -175,6 +221,8 @@ fn extract_overrides(
let file = std::fs::File::open(mrpack_path)?;
let mut archive = zip::ZipArchive::new(file)?;
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
@@ -191,6 +239,7 @@ fn extract_overrides(
if relative.is_empty() || entry_name.ends_with('/') {
let dir = minecraft_dir.join(relative);
std::fs::create_dir_all(dir)?;
dirs += 1;
continue;
}
@@ -201,8 +250,21 @@ fn extract_overrides(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting .mrpack override {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} override files and {} directories from {}",
extracted,
dirs,
mrpack_path.display()
);
Ok(())
}
+860 -318
View File
File diff suppressed because it is too large. Load diff
+425
View File
@@ -0,0 +1,425 @@
// live minecraft process log parser.
//
// disk launch logs stay raw, but the tui needs enough structure to color and
// group output sanely. this parser keeps stdout/stderr as a hint, frames
// multiline java/jvm/native bursts into events, then assigns a semantic level.
use libcasr::exception::Exception;
use libcasr::java::{JavaException, JavaStacktrace};
use libcasr::stacktrace::ParseStacktrace;
use regex::Regex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogStream {
Stdout,
Stderr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JavaParse {
pub has_exception: bool,
pub has_stacktrace: bool,
pub stacktrace_frames: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedLogEvent {
pub level: LogLevel,
pub primary_stream: LogStream,
pub lines: Vec<String>,
pub java: Option<JavaParse>,
}
#[derive(Debug, Clone)]
struct PendingEvent {
level: LogLevel,
primary_stream: LogStream,
lines: Vec<String>,
normalized_lines: Vec<String>,
kind: EventKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EventKind {
Header,
Java,
JvmBurst,
Native,
Plain,
}
#[derive(Debug)]
pub struct MinecraftLogParser {
current: Option<PendingEvent>,
minecraft_header_re: Regex,
plain_level_re: Regex,
java_exception_re: Regex,
java_continuation_re: Regex,
jvm_burst_re: Regex,
native_header_re: Regex,
}
impl Default for MinecraftLogParser {
fn default() -> Self {
Self::new()
}
}
impl MinecraftLogParser {
pub fn new() -> Self {
Self {
// header matching stays local because this parser is in the live
// path; pulling in heavier pattern machinery would not help with
// the multiline framing problem.
minecraft_header_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*\[[^/\]]+/(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s*:",
)
.expect("valid minecraft header regex"),
plain_level_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b\s*(?:[:\]\-])?",
)
.expect("valid plain level regex"),
java_exception_re: Regex::new(
r"(?i)^\s*(?:Exception in thread .+|Caused by: |Suppressed: )?(?:[a-z_$][\w$]*\.)+(?:[A-Z][\w$]*(?:Exception|Error)|Throwable)(?::|\b)",
)
.expect("valid java exception regex"),
java_continuation_re: Regex::new(
r"^(?:\s+at\s+.+|\s*\.\.\.\s+\d+\s+more|Caused by:\s+.+|Suppressed:\s+.+)$",
)
.expect("valid java continuation regex"),
jvm_burst_re: Regex::new(
r"(?i)^\s*(?:Error:\s+.+|Unrecognized option:\s+.+|Could not create the Java Virtual Machine\.|A fatal exception has occurred\. Program will exit\.|Invalid maximum heap size:.+)$",
)
.expect("valid jvm burst regex"),
native_header_re: Regex::new(r"^\[[A-Z]\]\s+\[[0-9:.]+\]\s+[^:]+:")
.expect("valid native header regex"),
current: None,
}
}
pub fn push_line(&mut self, stream: LogStream, line: impl Into<String>) -> Vec<ParsedLogEvent> {
let line = line.into();
// classify against ansi-stripped text, but keep the original line for
// display so the live log remains faithful to the child process.
let normalized = fast_strip_ansi::strip_ansi_string(&line).into_owned();
let analysis = self.analyze_line(stream, &normalized);
let Some(current) = &mut self.current else {
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
return Vec::new();
};
// only hard starts split events. this keeps stacktraces and native
// loader bursts together even when they arrive one line at a time.
if should_split(current.kind, analysis.kind) {
let finished = self.current.take().map(finish_event);
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
finished.into_iter().collect()
} else {
if analysis.level_priority() > current.level_priority() {
current.level = analysis.level;
}
if matches!(current.kind, EventKind::Plain)
&& !matches!(analysis.kind, EventKind::Plain)
{
current.kind = analysis.kind;
}
current.lines.push(line);
current.normalized_lines.push(normalized);
Vec::new()
}
}
pub fn flush(&mut self) -> Option<ParsedLogEvent> {
self.current.take().map(finish_event)
}
pub fn has_pending(&self) -> bool {
self.current.is_some()
}
fn analyze_line(&self, stream: LogStream, normalized: &str) -> LineAnalysis {
if let Some(level) = self.header_level(normalized) {
return LineAnalysis {
level,
kind: EventKind::Header,
};
}
if self.java_exception_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.java_continuation_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.jvm_burst_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::JvmBurst,
};
}
if self.native_header_re.is_match(normalized) {
return LineAnalysis {
level: native_level(normalized).unwrap_or(LogLevel::Warn),
kind: EventKind::Native,
};
}
LineAnalysis {
level: match stream {
LogStream::Stdout => LogLevel::Info,
LogStream::Stderr => LogLevel::Error,
},
kind: EventKind::Plain,
}
}
fn header_level(&self, normalized: &str) -> Option<LogLevel> {
self.minecraft_header_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
.or_else(|| {
self.plain_level_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
})
.and_then(|m| parse_level(m.as_str()))
}
}
#[derive(Debug, Clone, Copy)]
struct LineAnalysis {
level: LogLevel,
kind: EventKind,
}
impl LineAnalysis {
fn level_priority(self) -> u8 {
level_priority(self.level)
}
}
impl PendingEvent {
fn new(stream: LogStream, line: String, normalized: String, analysis: LineAnalysis) -> Self {
Self {
level: analysis.level,
primary_stream: stream,
lines: vec![line],
normalized_lines: vec![normalized],
kind: analysis.kind,
}
}
fn level_priority(&self) -> u8 {
level_priority(self.level)
}
}
fn should_split(current: EventKind, next: EventKind) -> bool {
match next {
EventKind::Header => true,
EventKind::Native => !matches!(current, EventKind::Native),
EventKind::JvmBurst => !matches!(current, EventKind::JvmBurst),
EventKind::Java => !matches!(current, EventKind::Java | EventKind::Header),
EventKind::Plain => false,
}
}
fn finish_event(mut event: PendingEvent) -> ParsedLogEvent {
let normalized_body = event.normalized_lines.join("\n");
// libcasr is intentionally second-stage here: first frame the multiline
// event ourselves, then ask libcasr whether the block is a java failure.
let java = parse_java(&normalized_body);
if java
.as_ref()
.is_some_and(|java| java.has_exception || java.has_stacktrace)
{
event.level = LogLevel::Error;
}
ParsedLogEvent {
level: event.level,
primary_stream: event.primary_stream,
lines: event.lines,
java,
}
}
fn parse_java(body: &str) -> Option<JavaParse> {
let stacktrace_entries = JavaStacktrace::extract_stacktrace(body).unwrap_or_default();
let parsed_stacktrace = if stacktrace_entries.is_empty() {
None
} else {
JavaStacktrace::parse_stacktrace(&stacktrace_entries).ok()
};
let has_exception = JavaException::parse_exception(body).is_some();
let has_stacktrace = parsed_stacktrace
.as_ref()
.is_some_and(|stacktrace| !stacktrace.is_empty());
if has_exception || has_stacktrace {
Some(JavaParse {
has_exception,
has_stacktrace,
stacktrace_frames: parsed_stacktrace.map_or(0, |stacktrace| stacktrace.len()),
})
} else {
None
}
}
fn parse_level(level: &str) -> Option<LogLevel> {
match level.to_ascii_uppercase().as_str() {
"TRACE" => Some(LogLevel::Trace),
"DEBUG" => Some(LogLevel::Debug),
"INFO" => Some(LogLevel::Info),
"WARN" => Some(LogLevel::Warn),
"ERROR" | "FATAL" => Some(LogLevel::Error),
_ => None,
}
}
fn native_level(line: &str) -> Option<LogLevel> {
match line.chars().nth(1)? {
'E' | 'F' => Some(LogLevel::Error),
'W' => Some(LogLevel::Warn),
'I' => Some(LogLevel::Info),
'D' => Some(LogLevel::Debug),
_ => None,
}
}
fn level_priority(level: LogLevel) -> u8 {
match level {
LogLevel::Trace => 0,
LogLevel::Debug => 1,
LogLevel::Info => 2,
LogLevel::Warn => 3,
LogLevel::Error => 4,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
let mut parser = MinecraftLogParser::new();
let mut events = Vec::new();
for (stream, line) in lines {
events.extend(parser.push_line(*stream, *line));
}
events.extend(parser.flush());
events
}
#[test]
fn classifies_minecraft_headers() {
let events = parse_all(&[
(LogStream::Stdout, "[Render thread/INFO]: hello"),
(LogStream::Stdout, "[Render thread/WARN]: careful"),
(LogStream::Stdout, "[Render thread/ERROR]: broken"),
(LogStream::Stdout, "[Render thread/DEBUG]: noisy"),
(LogStream::Stdout, "[Render thread/TRACE]: tiny"),
]);
assert_eq!(events.len(), 5);
assert_eq!(events[0].level, LogLevel::Info);
assert_eq!(events[1].level, LogLevel::Warn);
assert_eq!(events[2].level, LogLevel::Error);
assert_eq!(events[3].level, LogLevel::Debug);
assert_eq!(events[4].level, LogLevel::Trace);
}
#[test]
fn explicit_stderr_info_stays_info() {
let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]);
assert_eq!(events[0].level, LogLevel::Info);
}
#[test]
fn unstructured_stderr_falls_back_to_error() {
let events = parse_all(&[(LogStream::Stderr, "native library failed")]);
assert_eq!(events[0].level, LogLevel::Error);
}
#[test]
fn groups_java_stacktrace() {
let events = parse_all(&[
(
LogStream::Stderr,
"Exception in thread \"main\" java.lang.RuntimeException: boom",
),
(
LogStream::Stderr,
"\tat net.minecraft.client.Main.main(Main.java:42)",
),
(
LogStream::Stderr,
"Caused by: java.lang.IllegalStateException: bad",
),
(LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"),
(LogStream::Stdout, "[Render thread/INFO]: after"),
]);
assert_eq!(events.len(), 2);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 4);
assert!(
events[0]
.java
.as_ref()
.is_some_and(|java| java.has_stacktrace)
);
assert_eq!(events[1].level, LogLevel::Info);
}
#[test]
fn groups_jvm_startup_failure_burst() {
let events = parse_all(&[
(LogStream::Stderr, "Unrecognized option: --bad"),
(
LogStream::Stderr,
"Could not create the Java Virtual Machine.",
),
(
LogStream::Stderr,
"A fatal exception has occurred. Program will exit.",
),
]);
assert_eq!(events.len(), 1);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 3);
}
#[test]
fn colored_header_classifies_but_keeps_original_text() {
let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m";
let events = parse_all(&[(LogStream::Stdout, line)]);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines[0], line);
}
}
+139
View File
@@ -324,3 +324,142 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
// builds an in-memory zip with the given entries, writes it to tmp, and
// returns the path. shared by parse_add_opens tests.
fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
let path = tmp.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
for (filename, bytes) in entries {
zip.start_file(*filename, opts).unwrap();
zip.write_all(bytes).unwrap();
}
zip.finish().unwrap();
path
}
#[test]
fn strip_replaced_libs_removes_dominated_prefixes() {
let mut classpath = vec![
PathBuf::from("/libs/launchwrapper-1.12.jar"),
PathBuf::from("/libs/asm-all-5.0.3.jar"),
PathBuf::from("/libs/lwjgl-2.9.4.jar"),
PathBuf::from("/libs/lwjgl_util-2.9.4.jar"),
PathBuf::from("/libs/commons-compress-1.4.1.jar"),
PathBuf::from("/libs/commons-io-2.4.jar"),
PathBuf::from("/libs/guava-15.0.jar"),
// these stay
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/guava-21.0.jar"),
];
strip_replaced_libs(&mut classpath);
assert_eq!(
classpath,
vec![
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/guava-21.0.jar"),
]
);
}
#[test]
fn strip_replaced_libs_keeps_unrelated_entries() {
let mut classpath = vec![
PathBuf::from("/libs/log4j-core-2.0.jar"),
PathBuf::from("/libs/mixin-0.8.5.jar"),
];
let original = classpath.clone();
strip_replaced_libs(&mut classpath);
assert_eq!(classpath, original);
}
#[test]
fn parse_add_opens_extracts_module_args() {
let tmp = tempfile::tempdir().unwrap();
let manifest =
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(
tmp.path(),
"patches.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
vec![
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"--add-opens",
"java.base/java.util=ALL-UNNAMED",
]
);
}
#[test]
fn parse_add_opens_handles_continuation_lines() {
// jar manifests wrap long lines: the line ends with a trailing space,
// then the next physical line starts with a leading space marker.
// when joined per the MANIFEST.MF spec, the trailing space remains
// and the leading space marker is consumed, so the two values stay
// separated by exactly one space when split_whitespace runs.
let tmp = tempfile::tempdir().unwrap();
let manifest =
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n";
let zip_path = make_zip(
tmp.path(),
"patches-continuation.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
vec![
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"--add-opens",
"java.base/sun.security.util=ALL-UNNAMED",
]
);
}
#[test]
fn parse_add_opens_returns_none_when_manifest_missing() {
let tmp = tempfile::tempdir().unwrap();
let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]);
assert!(parse_add_opens(&zip_path).is_none());
}
#[test]
fn parse_add_opens_returns_none_for_missing_file() {
assert!(parse_add_opens(Path::new("/nonexistent/x.zip")).is_none());
}
#[test]
fn add_lwjgl3_inserts_only_jars_that_exist() {
let tmp = tempfile::tempdir().unwrap();
let lib_dir = tmp.path();
// pre-create only the lwjgl core jar; everything else absent so the
// function should skip them silently. proves we don't insert paths
// for jars that aren't there.
let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar");
std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap();
std::fs::write(&core_jar, b"jar").unwrap();
let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")];
add_lwjgl3(lib_dir, &mut classpath);
// forge-patches stays at index 0; lwjgl core is inserted at index 1.
// none of the other modules existed so nothing else was added.
assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar"));
assert_eq!(classpath[1], core_jar);
assert_eq!(classpath.len(), 2);
}
}
+32 -9
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, fabric as fabric_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for FabricInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Fabric loader versions for Minecraft {}",
game_version
);
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,17 +49,31 @@ impl ModLoaderInstaller for FabricInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile =
fabric_api::fetch_fabric_profile(client, game_version, loader_version).await?;
) -> Result<(), InstallError> {
tracing::info!(
"Installing Fabric {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Fabric profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
super::save_profile_json(
super::save_profile_bytes(
meta_dir,
&format!("fabric-{game_version}-{loader_version}.json"),
&profile,
)?;
&raw_bytes,
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+27 -6
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, forge as forge_api};
@@ -27,7 +27,14 @@ impl ModLoaderInstaller for ForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
forge_api::fetch_forge_versions(client, game_version).await
tracing::debug!("Fetching Forge versions for Minecraft {}", game_version);
let versions = forge_api::fetch_forge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Forge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -37,8 +44,14 @@ impl ModLoaderInstaller for ForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
tracing::info!(
"Installing Forge {} for Minecraft {}",
loader_version,
game_version
);
tracing::debug!("Forge installer path: {}", installer_jar.display());
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await?;
@@ -47,6 +60,7 @@ impl ModLoaderInstaller for ForgeInstaller {
if forge_api::has_legacy_install_profile(&installer_jar) {
// old forge: no --installClient support, extract directly from jar
tracing::debug!("Forge installer uses legacy install_profile.json path");
if let Err(e) = forge_api::install_forge_from_profile(
client,
&installer_jar,
@@ -65,21 +79,28 @@ impl ModLoaderInstaller for ForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running Forge installer with Java {}", java_path);
if let Err(e) =
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
return Err(InstallError::Installer(e));
}
// extract the profile from what the installer just wrote to disk
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)
.map_err(InstallError::Installer)?;
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
tracing::debug!(
"Installed Forge {} for Minecraft {}",
loader_version,
game_version
);
Ok(())
}
}
@@ -89,7 +110,7 @@ fn save_forge_profile(
meta_dir: &Path,
game_version: &str,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
let version_dir_name = format!("{game_version}-forge-{loader_version}");
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
+195 -67
View File
@@ -12,10 +12,29 @@ mod vanilla;
use std::path::Path;
use async_trait::async_trait;
use thiserror::Error;
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError};
#[derive(Debug, Error)]
pub enum InstallerError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Process failed: {0}")]
ProcessFailed(String),
#[error("Profile error: {0}")]
Profile(String),
}
#[derive(Debug, Error)]
pub enum InstallError {
#[error("Download error: {0}")]
Download(#[from] NetError),
#[error("Installer error: {0}")]
Installer(#[from] InstallerError),
}
pub use vanilla::VanillaInstaller;
#[derive(Debug, Clone)]
@@ -43,32 +62,35 @@ pub trait ModLoaderInstaller: Send + Sync {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError>;
) -> Result<(), InstallError>;
}
pub(crate) fn save_profile_json(
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
// callers that already have the upstream bytes (fabric/quilt http fetch,
// legacy forge versionInfo extract) use this directly to keep the on-disk
// file byte-for-byte identical to the source.
pub(crate) fn save_profile_bytes(
meta_dir: &Path,
filename: &str,
profile: &impl serde::Serialize,
) -> Result<(), NetError> {
bytes: &[u8],
) -> std::io::Result<()> {
let profiles_dir = meta_dir.join("loader-profiles");
std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(filename);
let json = serde_json::to_string_pretty(profile)
.map_err(|e| NetError::Parse(format!("Failed to serialize profile {filename}: {e}")))?;
std::fs::write(&profile_path, &json)?;
Ok(())
std::fs::write(profiles_dir.join(filename), bytes)
}
// used by forge/neoforge. their java installer drops a version json into
// .minecraft/versions/. parses that to extract the main class and library
// list, then saves a stripped-down profile for use at launch time.
// .minecraft/versions/. we copy that file byte-for-byte to our loader
// profile cache so launch-time code sees the full upstream JSON -
// inheritsFrom, arguments.jvm, library rules, all of it - instead of a
// stripped-down version that would silently drop modern features (e.g.
// the --add-opens flags forge 1.17+ ships for java 17+ support).
pub(crate) fn save_installer_profile(
instance_dir: &Path,
meta_dir: &Path,
version_dir_name: &str,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
let ver_json_path = instance_dir
.join(".minecraft")
.join("versions")
@@ -76,43 +98,33 @@ pub(crate) fn save_installer_profile(
.join(format!("{version_dir_name}.json"));
if !ver_json_path.exists() {
return Err(NetError::Parse(format!(
tracing::debug!(
"Installer profile JSON missing: {}",
ver_json_path.display()
);
return Err(InstallerError::Profile(format!(
"Version JSON not found at {}",
ver_json_path.display()
)));
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct InstallerVersionJson {
main_class: String,
#[serde(default)]
libraries: Vec<InstallerLib>,
}
#[derive(serde::Deserialize)]
struct InstallerLib {
name: String,
}
tracing::debug!(
"Saving installer profile {} from {}",
profile_filename,
ver_json_path.display()
);
let raw = std::fs::read(&ver_json_path)?;
let ver: InstallerVersionJson = serde_json::from_slice(&raw).map_err(|e| {
NetError::Parse(format!(
"Invalid version JSON at {}: {e}",
ver_json_path.display()
))
})?;
let libs: Vec<serde_json::Value> = ver
.libraries
.iter()
.map(|l| serde_json::json!({"name": l.name}))
.collect();
let json_val = serde_json::json!({
"mainClass": ver.main_class,
"libraries": libs
});
save_profile_json(meta_dir, profile_filename, &json_val)
let profiles_dir = meta_dir.join("loader-profiles");
std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(profile_filename);
std::fs::write(&profile_path, &raw)?;
tracing::debug!(
"Saved installer profile to {} ({} bytes)",
profile_path.display(),
raw.len()
);
Ok(())
}
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
@@ -129,31 +141,18 @@ pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + S
mod tests {
use super::*;
#[test]
fn test_vanilla_factory() {
let installer = get_installer(ModLoader::Vanilla);
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
}
#[tokio::test]
async fn test_vanilla_get_versions() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let versions = installer.get_versions(&client, "1.20.1").await.unwrap();
assert!(!versions.is_empty());
assert_eq!(versions[0], "vanilla");
}
#[tokio::test]
async fn test_vanilla_install_noop() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let tmp = std::env::temp_dir().join("rmcl_test_vanilla_install");
let meta = std::env::temp_dir().join("rmcl_test_meta");
installer
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
.await
.unwrap();
// the factory maps every ModLoader variant to its concrete installer.
// covering all five arms catches a misordered match or a copy-paste typo
// that would route, say, NeoForge to the Forge installer.
#[rstest::rstest]
#[case::vanilla(ModLoader::Vanilla)]
#[case::forge(ModLoader::Forge)]
#[case::neoforge(ModLoader::NeoForge)]
#[case::fabric(ModLoader::Fabric)]
#[case::quilt(ModLoader::Quilt)]
fn get_installer_returns_matching_loader_type(#[case] loader: ModLoader) {
let installer = get_installer(loader);
assert_eq!(installer.loader_type(), loader);
}
#[tokio::test]
@@ -165,4 +164,133 @@ mod tests {
assert!(!versions.is_empty());
assert!(versions.iter().any(|v| v.id == "1.20.1"));
}
#[test]
fn save_installer_profile_copies_raw_bytes_verbatim() {
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let instance_dir = tmp.path().join("instance");
let meta_dir = tmp.path().join("meta");
// a synthetic installer version JSON with the modern arguments
// object - exactly the shape we used to strip.
let installer_json = br#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [{ "name": "net.minecraftforge:forge:47.2.0" }],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": ["--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"]
}
}"#;
let ver_dir = instance_dir
.join(".minecraft")
.join("versions")
.join("1.20.1-forge-47.2.0");
std::fs::create_dir_all(&ver_dir).unwrap();
let ver_json_path = ver_dir.join("1.20.1-forge-47.2.0.json");
std::fs::write(&ver_json_path, installer_json).unwrap();
save_installer_profile(
&instance_dir,
&meta_dir,
"1.20.1-forge-47.2.0",
"forge-1.20.1-47.2.0.json",
)
.unwrap();
let saved = std::fs::read(
meta_dir
.join("loader-profiles")
.join("forge-1.20.1-47.2.0.json"),
)
.unwrap();
assert_eq!(
saved,
installer_json.to_vec(),
"saved profile should be byte-for-byte identical to installer output"
);
}
// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge
// install_profile.json must deserialise as a LaunchProfile so the
// launch flow's render_args + resolve pipeline can consume it. no
// filesystem round-trip; serde_json directly on the literal bytes.
#[test]
fn legacy_forge_version_info_deserialises_as_launch_profile() {
let bytes = br#"{
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
"mainClass": "net.minecraft.launchwrapper.Launch",
"minecraftArguments": "--username ${auth_player_name} --tweakClass cpw.mods.fml.common.launcher.FMLTweaker",
"libraries": [
{ "name": "net.minecraftforge:forge:10.13.4.1614", "url": "http://files.minecraftforge.net/maven/" },
{ "name": "net.minecraft:launchwrapper:1.9" }
]
}"#;
let profile: crate::launch_profile::model::LaunchProfile =
serde_json::from_slice(bytes).unwrap();
assert_eq!(profile.id, "1.7.10-Forge10.13.4.1614-1.7.10");
assert_eq!(
profile.main_class.as_deref(),
Some("net.minecraft.launchwrapper.Launch")
);
// legacy forge profiles omit inheritsFrom; the launch flow's
// implicit fallback adds it before resolve.
assert!(profile.inherits_from.is_none());
assert!(
profile
.minecraft_arguments
.as_deref()
.unwrap()
.contains("--tweakClass")
);
assert_eq!(profile.libraries.len(), 2);
assert_eq!(
profile.libraries[0].name,
"net.minecraftforge:forge:10.13.4.1614"
);
assert_eq!(
profile.libraries[0].url.as_deref(),
Some("http://files.minecraftforge.net/maven/")
);
// legacy libs typically have no downloads.artifact; they resolve
// at launch time via maven_coord_to_path(name).
assert!(profile.libraries[0].downloads.is_none());
}
// shape-pinning test: a synthetic upstream fabric profile (no
// inheritsFrom, no arguments, libraries with name+url) must
// deserialise as a LaunchProfile so the install path can write it
// through to disk and the launch flow can read it back.
#[test]
fn raw_fabric_profile_bytes_parse_as_launch_profile() {
let bytes = br#"{
"id": "fabric-loader-0.14.21-1.20.1",
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
"libraries": [
{ "name": "net.fabricmc:fabric-loader:0.14.21", "url": "https://maven.fabricmc.net/" },
{ "name": "net.fabricmc:intermediary:1.20.1", "url": "https://maven.fabricmc.net/" }
]
}"#;
let parsed: crate::launch_profile::model::LaunchProfile =
serde_json::from_slice(bytes).unwrap();
assert_eq!(parsed.id, "fabric-loader-0.14.21-1.20.1");
assert_eq!(
parsed.main_class.as_deref(),
Some("net.fabricmc.loader.impl.launch.knot.KnotClient")
);
// upstream Fabric profiles omit inheritsFrom; the launch flow's
// implicit fallback handles it before resolve.
assert!(parsed.inherits_from.is_none());
assert!(parsed.arguments.is_none());
assert_eq!(parsed.libraries.len(), 2);
assert_eq!(
parsed.libraries[0].url.as_deref(),
Some("https://maven.fabricmc.net/")
);
}
}
+18 -6
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
@@ -26,7 +26,14 @@ impl ModLoaderInstaller for NeoForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
neoforge_api::fetch_neoforge_versions(client, game_version).await
tracing::debug!("Fetching NeoForge versions for Minecraft {}", game_version);
let versions = neoforge_api::fetch_neoforge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} NeoForge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -36,10 +43,12 @@ impl ModLoaderInstaller for NeoForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir
.join(".minecraft")
.join("neoforge-installer.jar");
tracing::info!("Installing NeoForge {}", loader_version);
tracing::debug!("NeoForge installer path: {}", installer_jar.display());
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
@@ -48,19 +57,22 @@ impl ModLoaderInstaller for NeoForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running NeoForge installer with Java {}", java_path);
if let Err(e) =
neoforge_api::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
return Err(InstallError::Installer(e));
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
}
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
save_neoforge_profile(instance_dir, meta_dir, loader_version)
.map_err(InstallError::Installer)?;
tracing::debug!("Installed NeoForge {}", loader_version);
Ok(())
}
}
@@ -69,7 +81,7 @@ fn save_neoforge_profile(
instance_dir: &Path,
meta_dir: &Path,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
let version_dir_name = format!("neoforge-{loader_version}");
let profile_filename = format!("neoforge-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
+32 -8
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, quilt as quilt_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for QuiltInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Quilt loader versions for Minecraft {}",
game_version
);
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,16 +49,31 @@ impl ModLoaderInstaller for QuiltInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile = quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
) -> Result<(), InstallError> {
tracing::info!(
"Installing Quilt {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Quilt profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
super::save_profile_json(
super::save_profile_bytes(
meta_dir,
&format!("quilt-{game_version}-{loader_version}.json"),
&profile,
)?;
&raw_bytes,
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, mojang};
@@ -45,7 +45,7 @@ impl ModLoaderInstaller for VanillaInstaller {
_loader_version: &str,
_instance_dir: &Path,
_meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
Ok(())
}
}
-69
View File
@@ -61,12 +61,6 @@ pub fn read_log_file(path: &Path) -> Vec<String> {
mod tests {
use super::*;
fn setup_log_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = log_dir(tmp, instance);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn log_dir_builds_correct_path() {
let p = log_dir(Path::new("/instances"), "my-world");
@@ -75,67 +69,4 @@ mod tests {
PathBuf::from("/instances/my-world/.minecraft/logs/launches")
);
}
#[test]
fn scan_log_files_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_log_dir(tmp.path(), "inst");
let entries = scan_log_files(tmp.path(), "inst");
assert!(entries.is_empty());
}
#[test]
fn scan_log_files_finds_logs() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_log_dir(tmp.path(), "inst");
std::fs::write(dir.join("2024-01-01_12-00-00.log"), "line1\nline2").unwrap();
std::fs::write(dir.join("2024-01-02_12-00-00.log"), "line3").unwrap();
let entries = scan_log_files(tmp.path(), "inst");
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].name, "2024-01-02_12-00-00.log");
assert_eq!(entries[1].name, "2024-01-01_12-00-00.log");
}
#[test]
fn scan_log_files_ignores_non_log() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_log_dir(tmp.path(), "inst");
std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
std::fs::write(dir.join("real.log"), "log line").unwrap();
let entries = scan_log_files(tmp.path(), "inst");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].name, "real.log");
}
#[test]
fn scan_log_files_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let entries = scan_log_files(tmp.path(), "ghost");
assert!(entries.is_empty());
}
#[test]
fn read_log_file_returns_lines() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("test.log");
std::fs::write(&path, "alpha\nbeta\ngamma").unwrap();
let lines = read_log_file(&path);
assert_eq!(lines, vec!["alpha", "beta", "gamma"]);
}
#[test]
fn read_log_file_missing_returns_empty() {
let lines = read_log_file(Path::new("/nonexistent/test.log"));
assert!(lines.is_empty());
}
#[test]
fn create_log_file_creates_path() {
let tmp = tempfile::tempdir().unwrap();
let path = create_log_file(tmp.path(), "inst");
assert!(path.is_some());
let path = path.unwrap();
assert!(path.to_string_lossy().ends_with(".log"));
assert!(path.parent().unwrap().exists());
}
}
+321 -82
View File
@@ -6,6 +6,8 @@ use std::path::PathBuf;
use chrono::Utc;
use thiserror::Error;
use crate::instance::loader::InstallError;
use crate::instance::loader::InstallerError;
use crate::instance::models::{InstanceConfig, ModLoader};
#[derive(Debug, Error)]
@@ -20,6 +22,8 @@ pub enum InstanceError {
Json(#[from] serde_json::Error),
#[error("Download error: {0}")]
Download(#[from] crate::net::NetError),
#[error("Installer error: {0}")]
InstallerError(#[from] InstallerError),
#[error("Invalid instance name: {0}")]
InvalidName(String),
}
@@ -33,11 +37,17 @@ pub struct InstanceManager {
impl InstanceManager {
pub fn new(instances_dir: impl Into<PathBuf>, meta_dir: impl Into<PathBuf>) -> Self {
InstanceManager {
let manager = InstanceManager {
instances_dir: instances_dir.into(),
meta_dir: meta_dir.into(),
client: crate::net::HttpClient::new(),
}
};
tracing::trace!(
"Created InstanceManager with instances_dir={} meta_dir={}",
manager.instances_dir.display(),
manager.meta_dir.display()
);
manager
}
pub async fn create(
@@ -51,13 +61,31 @@ impl InstanceManager {
let instance_dir = self.instances_dir.join(name);
let instance_json = instance_dir.join("instance.json");
tracing::info!(
"Creating instance '{}' (Minecraft {}, loader {}, loader_version={})",
name,
game_version,
loader,
loader_version.unwrap_or("<none>")
);
tracing::debug!("Instance directory: {}", instance_dir.display());
if instance_json.exists() {
tracing::warn!(
"Cannot create instance '{}': {} already exists",
name,
instance_json.display()
);
return Err(InstanceError::AlreadyExists(name.to_string()));
}
// leftover directory without config = botched previous creation, nuke it
if instance_dir.exists() && !instance_json.exists() {
tracing::warn!(
"Removing incomplete instance directory before recreating '{}': {}",
name,
instance_dir.display()
);
std::fs::remove_dir_all(&instance_dir)?;
}
@@ -69,7 +97,22 @@ impl InstanceManager {
// clean up on failure so there's no half-baked instance left around
if result.is_err() {
let _ = std::fs::remove_dir_all(&instance_dir);
tracing::debug!(
"Cleaning up incomplete instance '{}' after creation failed",
name
);
if let Err(cleanup_error) = std::fs::remove_dir_all(&instance_dir) {
tracing::warn!(
"Failed to clean up incomplete instance directory {}: {}",
instance_dir.display(),
cleanup_error
);
} else {
tracing::debug!(
"Cleaned up incomplete instance directory {}",
instance_dir.display()
);
}
}
result
@@ -84,14 +127,26 @@ impl InstanceManager {
instance_dir: &std::path::Path,
) -> Result<InstanceConfig, InstanceError> {
let minecraft_dir = instance_dir.join(".minecraft");
tracing::debug!(
"Preparing Minecraft directory for '{}': {}",
name,
minecraft_dir.display()
);
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
let path = minecraft_dir.join(subdir);
std::fs::create_dir_all(&path)?;
tracing::trace!("Ensured instance subdirectory {}", path.display());
}
// forge insists on this file existing, even if it's empty json. thanks forge.
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
if !launcher_profiles_path.exists() {
std::fs::write(&launcher_profiles_path, "{}")?;
tracing::debug!(
"Created launcher_profiles.json for '{}': {}",
name,
launcher_profiles_path.display()
);
}
for meta_subdir in &[
@@ -101,22 +156,44 @@ impl InstanceManager {
self.meta_dir.join("assets").join("indexes"),
] {
std::fs::create_dir_all(meta_subdir)?;
tracing::trace!("Ensured metadata directory {}", meta_subdir.display());
}
tracing::debug!("Fetching Mojang version manifest for '{}'", name);
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
tracing::debug!(
"Loaded Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
Some(v) => v,
Some(v) => {
tracing::debug!(
"Resolved Minecraft version '{}' as {} entry",
game_version,
v.version_type
);
v
}
None => {
return Err(InstanceError::InvalidName(format!(
"Minecraft version '{}' not found in manifest",
game_version
"Minecraft version '{}' not found in manifest with {} entries",
game_version,
manifest.versions.len()
)));
}
};
let version_meta =
crate::net::mojang::fetch_version_meta(&self.client, version_entry).await?;
let (version_meta, raw_meta_bytes) =
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
tracing::debug!(
"Fetched version meta '{}' with {} libraries and asset index {}",
version_meta.id,
version_meta.libraries.len(),
version_meta.asset_index.id
);
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?;
@@ -126,15 +203,23 @@ impl InstanceManager {
.join("versions")
.join(game_version)
.join("meta.json");
match serde_json::to_string_pretty(&version_meta) {
Ok(json) => {
if let Err(e) = std::fs::write(&meta_json_path, &json) {
tracing::warn!("Failed to save version meta: {}", e);
}
}
Err(e) => {
tracing::warn!("Failed to serialize version meta: {}", e);
}
if let Some(parent) = meta_json_path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
tracing::warn!(
"Failed to ensure meta dir {} exists: {}",
parent.display(),
e
);
}
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
tracing::warn!(
"Failed to save version meta {}: {}",
meta_json_path.display(),
e
);
} else {
tracing::debug!("Saved version meta to {}", meta_json_path.display());
}
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
@@ -152,6 +237,12 @@ impl InstanceManager {
)));
}
};
tracing::debug!(
"Installing loader {} {} for instance '{}'",
loader,
effective_loader_version,
name
);
installer
.install(
&self.client,
@@ -160,7 +251,13 @@ impl InstanceManager {
instance_dir,
&self.meta_dir,
)
.await?;
.await
.map_err(|e| match e {
InstallError::Download(net_error) => InstanceError::Download(net_error),
InstallError::Installer(installer_error) => {
InstanceError::InstallerError(installer_error)
}
})?;
let config = InstanceConfig {
name: name.to_string(),
@@ -174,9 +271,11 @@ impl InstanceManager {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
};
self.save(&config)?;
tracing::info!("Created instance '{}'", name);
crate::tui::progress::clear();
Ok(config)
@@ -185,9 +284,22 @@ impl InstanceManager {
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() {
tracing::warn!(
"Cannot delete missing instance '{}': {}",
name,
instance_dir.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
std::fs::remove_dir_all(&instance_dir)?;
tracing::info!("Deleting instance '{}' at {}", name, instance_dir.display());
if let Err(e) = std::fs::remove_dir_all(&instance_dir) {
tracing::error!(
"Failed to delete instance directory {}: {}",
instance_dir.display(),
e
);
return Err(e.into());
}
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
}
@@ -197,22 +309,44 @@ impl InstanceManager {
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
let new_name = new_name.trim();
if new_name.is_empty() {
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
return Err(InstanceError::InvalidName(
"Name cannot be empty".to_string(),
));
}
if old_name == new_name {
tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
return Ok(());
}
let old_dir = self.instances_dir.join(old_name);
let new_dir = self.instances_dir.join(new_name);
if !old_dir.exists() {
tracing::warn!(
"Cannot rename missing instance '{}': {}",
old_name,
old_dir.display()
);
return Err(InstanceError::NotFound(old_name.to_string()));
}
if new_dir.exists() {
tracing::warn!(
"Cannot rename instance '{}' to '{}': destination exists at {}",
old_name,
new_name,
new_dir.display()
);
return Err(InstanceError::AlreadyExists(new_name.to_string()));
}
std::fs::rename(&old_dir, &new_dir)?;
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
tracing::error!(
"Failed to rename instance directory {} to {}: {}",
old_dir.display(),
new_dir.display(),
e
);
return Err(e.into());
}
let config_path = new_dir.join("instance.json");
if let Ok(data) = std::fs::read_to_string(&config_path)
@@ -225,6 +359,11 @@ impl InstanceManager {
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
tracing::warn!("Failed to rename desktop shortcut: {}", e);
}
} else {
tracing::warn!(
"Renamed instance directory but could not update config at {}",
config_path.display()
);
}
Ok(())
@@ -232,10 +371,15 @@ impl InstanceManager {
pub fn load_all(&self) -> Vec<InstanceConfig> {
let mut instances = vec![];
tracing::debug!("Loading instances from {}", self.instances_dir.display());
let read_dir = match std::fs::read_dir(&self.instances_dir) {
Ok(rd) => rd,
Err(e) => {
tracing::error!("Failed to read instances directory: {}", e);
tracing::error!(
"Failed to read instances directory {}: {}",
self.instances_dir.display(),
e
);
return instances;
}
};
@@ -249,6 +393,7 @@ impl InstanceManager {
};
let config_path = entry.path().join("instance.json");
if !config_path.exists() {
tracing::trace!("Skipping non-instance directory {}", entry.path().display());
continue;
}
let contents = match std::fs::read_to_string(&config_path) {
@@ -265,6 +410,7 @@ impl InstanceManager {
}
}
}
tracing::debug!("Loaded {} instance(s)", instances.len());
instances
}
@@ -273,11 +419,39 @@ impl InstanceManager {
let config_path = self.instances_dir.join(name).join("instance.json");
if !config_path.exists() {
tracing::warn!(
"Instance '{}' config is missing at {}",
name,
config_path.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
let contents = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
tracing::debug!("Loading instance '{}' from {}", name, config_path.display());
let contents = match std::fs::read_to_string(&config_path) {
Ok(contents) => contents,
Err(e) => {
tracing::error!(
"Failed to read instance '{}' config {}: {}",
name,
config_path.display(),
e
);
return Err(e.into());
}
};
match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to parse instance '{}' config {}: {}",
name,
config_path.display(),
e
);
Err(e.into())
}
}
}
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
@@ -285,12 +459,18 @@ impl InstanceManager {
let config_path = instance_dir.join("instance.json");
let json = serde_json::to_string_pretty(instance)?;
std::fs::write(&config_path, &json)?;
tracing::debug!(
"Saved instance '{}' config to {}",
instance.name,
config_path.display()
);
Ok(())
}
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
let mut config = self.load_one(name)?;
config.last_played = Some(chrono::Utc::now());
tracing::debug!("Updating last_played for '{}'", name);
self.save(&config)
}
}
@@ -316,55 +496,21 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
mod tests {
use super::*;
use crate::instance::models::ModLoader;
use std::path::PathBuf;
use tempfile::TempDir;
fn test_manager() -> (InstanceManager, PathBuf) {
let tmp = std::env::temp_dir().join(format!("rmcl_test_{}", uuid_like()));
let meta = std::env::temp_dir().join(format!("rmcl_meta_test_{}", uuid_like()));
std::fs::create_dir_all(&tmp).ok();
std::fs::create_dir_all(&meta).ok();
(InstanceManager::new(tmp.clone(), meta), tmp)
// tmp owns the temp directory; its Drop impl cleans up everything when
// the test ends. the returned InstanceManager points at tmp.path() so
// tests can join("name") off of either to refer to the same locations.
fn test_manager() -> (InstanceManager, TempDir) {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
std::fs::create_dir_all(&meta).unwrap();
(InstanceManager::new(tmp.path().to_path_buf(), meta), tmp)
}
fn uuid_like() -> String {
format!(
"{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
)
}
#[test]
fn test_validate_name_valid() {
assert!(validate_name("my-instance").is_ok());
assert!(validate_name("test_world").is_ok());
}
#[test]
fn test_validate_name_invalid() {
assert!(validate_name("").is_err());
assert!(validate_name("path/traversal").is_err());
assert!(validate_name(".hidden").is_err());
}
#[test]
fn test_delete_nonexistent() {
let (manager, tmp) = test_manager();
let result = manager.delete("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn test_save_and_load_all() {
let (manager, tmp) = test_manager();
let instance_dir = tmp.join("test-save");
std::fs::create_dir_all(&instance_dir).ok();
let config = InstanceConfig {
name: "test-save".to_string(),
fn dummy_config(name: &str) -> InstanceConfig {
InstanceConfig {
name: name.to_string(),
game_version: "1.20.1".to_string(),
loader: ModLoader::Vanilla,
loader_version: None,
@@ -375,23 +521,47 @@ mod tests {
memory_min: None,
jvm_args: vec![],
resolution: None,
};
config_sync_profile: None,
}
}
manager.save(&config).expect("save failed");
#[test]
fn validate_name_accepts_safe_names() {
assert!(validate_name("my-instance").is_ok());
assert!(validate_name("test_world").is_ok());
}
#[test]
fn validate_name_rejects_empty_traversal_and_hidden() {
assert!(validate_name("").is_err());
assert!(validate_name("path/traversal").is_err());
assert!(validate_name(".hidden").is_err());
}
#[test]
fn delete_missing_instance_returns_not_found() {
let (manager, _tmp) = test_manager();
let result = manager.delete("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
}
#[test]
fn save_then_load_all_round_trips_config() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("test-save")).unwrap();
manager.save(&dummy_config("test-save")).expect("save");
let all = manager.load_all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].name, "test-save");
assert_eq!(all[0].game_version, "1.20.1");
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn test_load_all_accepts_numeric_memory() {
fn load_all_accepts_numeric_memory() {
let (manager, tmp) = test_manager();
let instance_dir = tmp.join("test-memory");
std::fs::create_dir_all(&instance_dir).ok();
let instance_dir = tmp.path().join("test-memory");
std::fs::create_dir_all(&instance_dir).unwrap();
std::fs::write(
instance_dir.join("instance.json"),
r#"{
@@ -410,15 +580,84 @@ mod tests {
assert_eq!(all.len(), 1);
assert_eq!(all[0].memory_max.as_deref(), Some("8G"));
assert_eq!(all[0].memory_min.as_deref(), Some("512M"));
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn test_load_one_not_found() {
let (manager, tmp) = test_manager();
fn load_one_missing_returns_not_found() {
let (manager, _tmp) = test_manager();
let result = manager.load_one("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn rename_moves_dir_and_updates_config_name() {
let (manager, tmp) = test_manager();
let old_dir = tmp.path().join("old-name");
std::fs::create_dir_all(&old_dir).unwrap();
manager.save(&dummy_config("old-name")).expect("save");
manager.rename("old-name", "new-name").expect("rename");
assert!(!old_dir.exists(), "old dir should be gone");
let new_dir = tmp.path().join("new-name");
assert!(new_dir.exists(), "new dir should exist");
let reloaded = manager.load_one("new-name").expect("load_one new-name");
assert_eq!(reloaded.name, "new-name");
}
#[test]
fn rename_to_same_name_is_noop() {
let (manager, tmp) = test_manager();
let dir = tmp.path().join("same");
std::fs::create_dir_all(&dir).unwrap();
manager.save(&dummy_config("same")).expect("save");
manager.rename("same", "same").expect("noop rename");
assert!(dir.exists());
}
#[test]
fn rename_empty_target_rejects() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("orig")).unwrap();
manager.save(&dummy_config("orig")).expect("save");
let err = manager.rename("orig", " ").unwrap_err();
assert!(matches!(err, InstanceError::InvalidName(_)));
}
#[test]
fn rename_missing_source_errors() {
let (manager, _tmp) = test_manager();
let err = manager.rename("ghost", "anything").unwrap_err();
assert!(matches!(err, InstanceError::NotFound(_)));
}
#[test]
fn rename_target_exists_errors() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("source")).unwrap();
std::fs::create_dir_all(tmp.path().join("collision")).unwrap();
manager.save(&dummy_config("source")).expect("save src");
manager.save(&dummy_config("collision")).expect("save dst");
let err = manager.rename("source", "collision").unwrap_err();
assert!(matches!(err, InstanceError::AlreadyExists(_)));
}
#[test]
fn touch_last_played_updates_field() {
let (manager, tmp) = test_manager();
std::fs::create_dir_all(tmp.path().join("ticker")).unwrap();
manager.save(&dummy_config("ticker")).expect("save");
assert!(manager.load_one("ticker").unwrap().last_played.is_none());
manager.touch_last_played("ticker").expect("touch");
let reloaded = manager.load_one("ticker").unwrap();
let stamp = reloaded
.last_played
.expect("last_played should be Some now");
let age = chrono::Utc::now() - stamp;
assert!(
age.num_seconds().abs() < 5,
"last_played should be roughly now, got age {age:?}"
);
}
}
+4 -5
View File
@@ -1,5 +1,7 @@
// instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher
pub mod config_sync;
pub mod content;
pub mod desktop;
pub mod import;
@@ -11,11 +13,8 @@ pub mod models;
pub mod screenshots;
pub use content::{
ContentEntry, toggle_entry,
scan_mods, scan_one_mod,
scan_resource_packs, scan_one_resource_pack,
scan_shaders, scan_one_shader,
scan_worlds, scan_one_world,
ContentEntry, scan_mods, scan_one_mod, scan_one_resource_pack, scan_one_shader, scan_one_world,
scan_resource_packs, scan_shaders, scan_worlds, toggle_entry,
};
pub use launch::LaunchError;
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
+4 -1
View File
@@ -47,6 +47,8 @@ pub struct InstanceConfig {
pub jvm_args: Vec<String>,
#[serde(default)]
pub resolution: Option<(u32, u32)>,
#[serde(default)]
pub config_sync_profile: Option<String>,
}
pub fn normalize_memory_value(raw: &str) -> Option<String> {
@@ -124,7 +126,7 @@ mod tests {
use super::*;
#[test]
fn test_instance_config_roundtrip() {
fn instance_config_roundtrips_through_json() {
let config = InstanceConfig {
name: "test".to_string(),
game_version: "1.20.1".to_string(),
@@ -137,6 +139,7 @@ mod tests {
memory_min: Some("512M".to_string()),
jvm_args: vec![],
resolution: Some((1920, 1080)),
config_sync_profile: None,
};
let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
-85
View File
@@ -45,88 +45,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
entries.sort_by(|a, b| b.name.cmp(&a.name));
entries
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_screenshots_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("screenshots");
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn tiny_png() -> Vec<u8> {
let img = image::RgbImage::from_pixel(1, 1, image::Rgb([255, 255, 255]));
let mut buf = std::io::Cursor::new(Vec::new());
img.write_to(&mut buf, image::ImageFormat::Png).unwrap();
buf.into_inner()
}
#[test]
fn scan_screenshots_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
setup_screenshots_dir(tmp.path(), "inst");
let screenshots = scan_screenshots(tmp.path(), "inst");
assert!(screenshots.is_empty());
}
#[test]
fn scan_screenshots_missing_dir_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let screenshots = scan_screenshots(tmp.path(), "ghost");
assert!(screenshots.is_empty());
}
#[test]
fn scan_screenshots_finds_images() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_screenshots_dir(tmp.path(), "inst");
std::fs::write(dir.join("2024-01-01.png"), tiny_png()).unwrap();
std::fs::write(dir.join("2024-01-02.png"), tiny_png()).unwrap();
let screenshots = scan_screenshots(tmp.path(), "inst");
assert_eq!(screenshots.len(), 2);
}
#[test]
fn scan_screenshots_ignores_non_images() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_screenshots_dir(tmp.path(), "inst");
std::fs::write(dir.join("pic.png"), tiny_png()).unwrap();
std::fs::write(dir.join("notes.txt"), "not an image").unwrap();
let screenshots = scan_screenshots(tmp.path(), "inst");
assert_eq!(screenshots.len(), 1);
}
#[test]
fn scan_screenshots_sorted_newest_first() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_screenshots_dir(tmp.path(), "inst");
std::fs::write(dir.join("aaa.png"), tiny_png()).unwrap();
std::fs::write(dir.join("zzz.png"), tiny_png()).unwrap();
let screenshots = scan_screenshots(tmp.path(), "inst");
assert_eq!(screenshots[0].name, "zzz.png");
assert_eq!(screenshots[1].name, "aaa.png");
}
#[test]
fn scan_screenshots_reads_dimensions() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_screenshots_dir(tmp.path(), "inst");
std::fs::write(dir.join("shot.png"), tiny_png()).unwrap();
let screenshots = scan_screenshots(tmp.path(), "inst");
assert_eq!(screenshots[0].width, 1);
assert_eq!(screenshots[0].height, 1);
}
#[test]
fn scan_screenshots_bad_image_uses_default_dimensions() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_screenshots_dir(tmp.path(), "inst");
std::fs::write(dir.join("corrupt.png"), b"not a real png").unwrap();
let screenshots = scan_screenshots(tmp.path(), "inst");
assert_eq!(screenshots.len(), 1);
assert_eq!(screenshots[0].width, 1920);
assert_eq!(screenshots[0].height, 1080);
}
}
+36 -3
View File
@@ -6,28 +6,61 @@ use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use crate::instance::launch::parser::{LogLevel, LogStream, ParsedLogEvent};
const MAX_LINES: usize = 2000;
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<String>>>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveLogLine {
pub level: LogLevel,
pub stream: LogStream,
pub text: String,
}
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<LiveLogLine>>>>;
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
pub fn push(name: &str, line: impl Into<String>) {
push_line(name, LogLevel::Info, LogStream::Stdout, line);
}
pub fn push_event(name: &str, event: ParsedLogEvent) {
for line in event.lines {
push_line(name, event.level, event.primary_stream, line);
}
}
pub fn push_line(name: &str, level: LogLevel, stream: LogStream, line: impl Into<String>) {
if let Ok(mut logs) = LOGS.lock() {
let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new);
buf.push_back(line.into());
buf.push_back(LiveLogLine {
level,
stream,
text: line.into(),
});
while buf.len() > MAX_LINES {
buf.pop_front();
}
}
}
pub fn get_all(name: &str) -> Vec<String> {
pub fn get_entries(name: &str) -> Vec<LiveLogLine> {
LOGS.lock()
.ok()
.and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect()))
.unwrap_or_default()
}
pub fn get_all(name: &str) -> Vec<String> {
LOGS.lock()
.ok()
.and_then(|logs| {
logs.get(name)
.map(|buf| buf.iter().map(|line| line.text.clone()).collect())
})
.unwrap_or_default()
}
pub fn clear(name: &str) {
if let Ok(mut logs) = LOGS.lock() {
logs.remove(name);
+11
View File
@@ -0,0 +1,11 @@
// primitives for parsing, merging, and rendering mojang-format launch
// profiles. consumed by the vanilla launcher and the loader install paths
// (forge/neoforge/fabric/quilt) - anything that reads a mojang-style
// version JSON.
pub mod model;
pub mod render;
pub mod resolve;
pub mod rules;
pub mod system;
pub mod templates;
+281
View File
@@ -0,0 +1,281 @@
// mojang-format launch profile types. mirrors the on-disk JSON schema
// used by vanilla versions, forge installer output, neoforge installer
// output, fabric profiles, and quilt profiles. parsing is lossless for
// the fields we care about; unknown fields are silently dropped (serde
// default behavior) - which is fine because we write upstream JSON
// byte-for-byte on the install side.
use serde::{Deserialize, Serialize};
use super::rules::Rule;
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LaunchProfile {
pub id: String,
pub inherits_from: Option<String>,
pub main_class: Option<String>,
#[serde(default)]
pub libraries: Vec<Library>,
pub arguments: Option<Arguments>,
pub minecraft_arguments: Option<String>,
pub asset_index: Option<AssetIndex>,
pub assets: Option<String>,
pub java_version: Option<JavaVersion>,
pub downloads: Option<VersionDownloads>,
pub release_time: Option<String>,
pub time: Option<String>,
#[serde(rename = "type")]
pub type_: Option<String>,
// present only in rmcl <= 0.3.0's stripped loader-profile shape.
// we deserialize it so the launch-time legacy-detection predicate
// can confirm "this really is our old format, not an upstream
// profile that happens to omit arguments". skipped on serialize so
// we never propagate this field outward.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub game_arguments: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
pub struct Arguments {
#[serde(default)]
pub game: Vec<Argument>,
#[serde(default)]
pub jvm: Vec<Argument>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Argument {
Literal(String),
Conditional {
rules: Vec<Rule>,
value: ArgumentValue,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ArgumentValue {
Single(String),
Multiple(Vec<String>),
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Library {
pub name: String,
pub downloads: Option<LibraryDownloads>,
pub rules: Option<Vec<Rule>>,
pub url: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct LibraryDownloads {
pub artifact: Option<Artifact>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Artifact {
pub url: String,
pub path: String,
pub sha1: String,
pub size: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct AssetIndex {
pub id: String,
pub url: String,
pub sha1: String,
pub size: Option<u64>,
pub total_size: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JavaVersion {
pub component: Option<String>,
pub major_version: u32,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct VersionDownloads {
pub client: Download,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Download {
pub url: String,
pub sha1: String,
pub size: u64,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::launch_profile::rules::RuleAction;
const MODERN_FIXTURE: &str = r#"{
"id": "1.20.1",
"type": "release",
"mainClass": "net.minecraft.client.main.Main",
"assetIndex": {
"id": "5",
"url": "https://example.invalid/5.json",
"sha1": "0000000000000000000000000000000000000000"
},
"javaVersion": {
"component": "java-runtime-gamma",
"majorVersion": 17
},
"libraries": [
{
"name": "org.lwjgl:lwjgl:3.3.1",
"downloads": {
"artifact": {
"url": "https://example.invalid/lwjgl.jar",
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
"sha1": "1111111111111111111111111111111111111111",
"size": 100
}
},
"rules": [
{ "action": "allow", "os": { "name": "linux" } }
]
}
],
"arguments": {
"game": [
"--username", "${auth_player_name}",
{
"rules": [{ "action": "allow", "features": { "is_demo_user": true } }],
"value": "--demo"
}
],
"jvm": [
"-Djava.library.path=${natives_directory}",
{
"rules": [{ "action": "allow", "os": { "name": "osx" } }],
"value": ["-XstartOnFirstThread"]
}
]
}
}"#;
const LEGACY_FIXTURE: &str = r#"{
"id": "1.7.10",
"type": "release",
"mainClass": "net.minecraft.client.main.Main",
"minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}",
"assetIndex": {
"id": "1.7.10",
"url": "https://example.invalid/1.7.10.json",
"sha1": "0000000000000000000000000000000000000000"
},
"libraries": []
}"#;
const LOADER_FIXTURE: &str = r#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [
{ "name": "net.minecraftforge:forge:47.2.0" }
],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": [
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler",
"-DlibraryDirectory=${library_directory}"
]
}
}"#;
#[test]
fn parses_modern_arguments_object() {
let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
assert_eq!(profile.id, "1.20.1");
assert_eq!(
profile.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
assert!(profile.inherits_from.is_none());
assert!(profile.minecraft_arguments.is_none());
let args = profile.arguments.as_ref().expect("arguments present");
assert_eq!(args.game.len(), 3);
assert_eq!(args.jvm.len(), 2);
// first game arg should be a literal "--username"
match &args.game[0] {
Argument::Literal(s) => assert_eq!(s, "--username"),
_ => panic!("expected literal"),
}
// third game arg should be a conditional with a single-string value
match &args.game[2] {
Argument::Conditional { rules, value } => {
assert_eq!(rules.len(), 1);
assert_eq!(rules[0].action, RuleAction::Allow);
assert!(matches!(value, ArgumentValue::Single(_)));
}
_ => panic!("expected conditional"),
}
// second jvm arg should be a conditional with a multi-string value
match &args.jvm[1] {
Argument::Conditional { value, .. } => {
assert!(matches!(value, ArgumentValue::Multiple(_)));
}
_ => panic!("expected conditional"),
}
}
#[test]
fn parses_legacy_minecraft_arguments_string() {
let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
assert_eq!(profile.id, "1.7.10");
assert!(profile.arguments.is_none());
assert!(
profile
.minecraft_arguments
.as_deref()
.unwrap()
.contains("${version_name}")
);
assert!(profile.libraries.is_empty());
}
#[test]
fn parses_loader_profile_with_inherits_from() {
let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
assert_eq!(profile.id, "1.20.1-forge-47.2.0");
assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1"));
assert!(profile.asset_index.is_none()); // inherited from parent
let args = profile.arguments.as_ref().unwrap();
assert_eq!(args.game.len(), 2);
assert_eq!(args.jvm.len(), 3);
}
#[test]
fn modern_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
#[test]
fn loader_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
#[test]
fn legacy_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
}
+357
View File
@@ -0,0 +1,357 @@
// renders a parsed launch profile into final argv-style lists for the JVM
// and the game. resolves conditional argument shapes (`{rules, value}`),
// filters them through the rule evaluator, and substitutes mojang template
// variables. legacy `minecraftArguments` strings are tokenised on whitespace
// and treated as a list of game args. pure function; no I/O.
use super::model::{Argument, ArgumentValue, LaunchProfile};
use super::rules::{RuleContext, evaluate};
use super::templates::{TemplateContext, substitute};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedArgs {
pub jvm: Vec<String>,
pub main_class: String,
pub game: Vec<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum RenderError {
#[error("launch profile is missing a main class")]
MissingMainClass,
}
pub fn render_args(
profile: &LaunchProfile,
rule_ctx: &RuleContext,
template_ctx: &TemplateContext,
) -> Result<RenderedArgs, RenderError> {
let main_class = profile
.main_class
.clone()
.ok_or(RenderError::MissingMainClass)?;
let mut jvm = Vec::new();
let mut game = Vec::new();
if let Some(args) = &profile.arguments {
for arg in &args.jvm {
push_argument(arg, rule_ctx, template_ctx, &mut jvm);
}
for arg in &args.game {
push_argument(arg, rule_ctx, template_ctx, &mut game);
}
} else if let Some(legacy) = &profile.minecraft_arguments {
for token in legacy.split_whitespace() {
game.push(substitute(token, template_ctx));
}
}
Ok(RenderedArgs {
jvm,
main_class,
game,
})
}
fn push_argument(
arg: &Argument,
rule_ctx: &RuleContext,
template_ctx: &TemplateContext,
out: &mut Vec<String>,
) {
match arg {
Argument::Literal(s) => out.push(substitute(s, template_ctx)),
Argument::Conditional { rules, value } => {
if !evaluate(rules, rule_ctx) {
return;
}
match value {
ArgumentValue::Single(s) => out.push(substitute(s, template_ctx)),
ArgumentValue::Multiple(items) => {
for s in items {
out.push(substitute(s, template_ctx));
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::launch_profile::model::Arguments;
use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction};
use std::path::PathBuf;
// owns the path buffers + FeatureSet so each test just calls
// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs
// and a RuleContext inline. all tests use linux/x86_64; if a test needs
// a different OS it sets it explicitly.
struct Fixture {
lib: PathBuf,
nat: PathBuf,
game: PathBuf,
assets: PathBuf,
features: FeatureSet,
}
impl Fixture {
fn new() -> Self {
Self {
lib: PathBuf::from("/m/libraries"),
nat: PathBuf::from("/m/natives"),
game: PathBuf::from("/i/.minecraft"),
assets: PathBuf::from("/m/assets"),
features: FeatureSet::default(),
}
}
fn template_ctx(&self) -> TemplateContext<'_> {
TemplateContext {
library_directory: &self.lib,
classpath_separator: ":",
version_name: "1.20.1",
version_type: "release",
natives_directory: &self.nat,
classpath: "a.jar:b.jar",
game_directory: &self.game,
assets_root: &self.assets,
assets_index_name: "5",
auth_player_name: "Player",
auth_uuid: "00000000-0000-0000-0000-000000000000",
auth_access_token: "token",
auth_xuid: "0",
user_type: "msa",
user_properties: "{}",
launcher_name: "rmcl",
launcher_version: "0.3.0",
clientid: "0",
}
}
fn rule_ctx(&self) -> RuleContext<'_> {
RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features: &self.features,
}
}
}
fn minimal_profile() -> LaunchProfile {
LaunchProfile {
id: "test".into(),
main_class: Some("net.test.Main".into()),
..Default::default()
}
}
#[test]
fn legacy_minecraft_arguments_render_into_game() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.minecraft_arguments =
Some("--username ${auth_player_name} --version ${version_name}".into());
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.main_class, "net.test.Main");
assert!(rendered.jvm.is_empty());
assert_eq!(
rendered.game,
vec!["--username", "Player", "--version", "1.20.1"]
);
}
#[test]
fn modern_arguments_render_with_literals_and_substitutions() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: vec![
Argument::Literal("--username".into()),
Argument::Literal("${auth_player_name}".into()),
],
jvm: vec![Argument::Literal(
"-Djava.library.path=${natives_directory}".into(),
)],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.game, vec!["--username", "Player"]);
assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]);
}
#[test]
fn conditional_argument_with_single_value_is_filtered_by_os_rule() {
let fx = Fixture::new();
let osx_only = Argument::Conditional {
rules: vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
..Default::default()
}),
features: None,
}],
value: ArgumentValue::Single("-XstartOnFirstThread".into()),
};
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![osx_only],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert!(
rendered.jvm.is_empty(),
"osx-only arg should be skipped on linux"
);
}
#[test]
fn conditional_argument_with_multiple_value_pushes_all() {
let fx = Fixture::new();
let linux_arg = Argument::Conditional {
rules: vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}],
value: ArgumentValue::Multiple(vec![
"--add-opens".into(),
"java.base/sun.security.util=ALL-UNNAMED".into(),
]),
};
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![linux_arg],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(
rendered.jvm,
vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"]
);
}
#[test]
fn missing_main_class_returns_error() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.main_class = None;
let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx());
assert!(matches!(result, Err(RenderError::MissingMainClass)));
}
#[tokio::test]
async fn end_to_end_resolve_then_render_modern_forge_shape() {
// exercises the full pipeline: load a synthetic vanilla profile
// from disk, load a synthetic loader profile with inheritsFrom,
// resolve the chain, then render args. catches integration bugs
// that unit tests of each layer would miss.
use crate::launch_profile::resolve;
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let vanilla_path = tmp.path().join("versions").join("1.20.1").join("meta.json");
std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap();
let vanilla_json = br#"{
"id": "1.20.1",
"mainClass": "net.minecraft.client.main.Main",
"libraries": [
{
"name": "org.lwjgl:lwjgl:3.3.1",
"downloads": {
"artifact": {
"url": "https://example.invalid/lwjgl.jar",
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
"sha1": "1111111111111111111111111111111111111111",
"size": 100
}
}
}
],
"arguments": {
"game": ["--username", "${auth_player_name}", "--version", "${version_name}"],
"jvm": ["-Djava.library.path=${natives_directory}"]
}
}"#;
std::fs::write(&vanilla_path, vanilla_json).unwrap();
let loader_json = r#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [
{ "name": "net.minecraftforge:forge:47.2.0" }
],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": [
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"
]
}
}"#;
let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap();
let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap();
let fx = Fixture::new();
let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
// child main_class wins after merge
assert_eq!(
rendered.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
// game args: parent first then child
assert_eq!(
rendered.game,
vec![
"--username",
"Player",
"--version",
"1.20.1",
"--launchTarget",
"forge_client"
]
);
// jvm args: parent first then child
assert_eq!(
rendered.jvm,
vec![
"-Djava.library.path=/m/natives",
"--add-opens",
"java.base/sun.security.util=cpw.mods.securejarhandler"
]
);
}
#[test]
fn modern_arguments_takes_precedence_over_legacy_field() {
// a profile that somehow has both arguments and minecraft_arguments
// should use arguments only (legacy is fallback).
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-arguments".into())],
jvm: Vec::new(),
});
profile.minecraft_arguments = Some("--from-legacy".into());
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.game, vec!["--from-arguments"]);
}
}
+565
View File
@@ -0,0 +1,565 @@
// resolves the `inheritsFrom` chain of a parsed `LaunchProfile`. mojang's
// version JSON allows a profile to inherit from another profile by id; the
// loaders (forge / neoforge / fabric / quilt) use this to layer their
// additions on top of a vanilla base. this module walks the chain and
// returns a single flat profile.
//
// merge semantics (per the mojang launcher and the major third-party
// launchers that interoperate with it):
// - scalar fields: child wins if Some, else parent.
// - libraries and arguments: parent ++ child (parent first). child
// entries are appended after parent's.
// - merge_into preserves parent's inherits_from so resolve() can keep
// walking; resolve() clears the final result's inherits_from after
// the loop exits.
//
// pure function `merge_into` handles the field-by-field merge math.
// async `resolve` does the chain walking with cycle detection and a depth
// cap. tests cover both layers independently.
use std::path::Path;
use super::model::{Arguments, LaunchProfile};
const MAX_INHERITANCE_DEPTH: usize = 8;
#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
#[error("parent profile not found at {0}")]
ParentNotFound(String),
#[error("failed to parse parent profile {0}: {1}")]
ParseError(String, String),
#[error("circular inheritance detected: {0} appears more than once in the chain")]
CircularInheritance(String),
#[error("inheritance chain exceeded {0} levels")]
DepthExceeded(usize),
#[error("I/O error reading parent profile: {0}")]
Io(#[from] std::io::Error),
}
// merges `child` on top of `parent`. child takes precedence for scalar
// fields. for libraries and arguments, child entries are appended after
// parent's. `id` is taken from child. `inherits_from` is taken from
// parent (so resolve() can keep walking the chain - resolve() clears it
// to None after the final iteration).
pub fn merge_into(child: LaunchProfile, parent: LaunchProfile) -> LaunchProfile {
LaunchProfile {
id: child.id,
inherits_from: parent.inherits_from,
main_class: child.main_class.or(parent.main_class),
libraries: merge_libraries(child.libraries, parent.libraries),
arguments: merge_arguments(child.arguments, parent.arguments),
minecraft_arguments: child.minecraft_arguments.or(parent.minecraft_arguments),
asset_index: child.asset_index.or(parent.asset_index),
assets: child.assets.or(parent.assets),
java_version: child.java_version.or(parent.java_version),
downloads: child.downloads.or(parent.downloads),
release_time: child.release_time.or(parent.release_time),
time: child.time.or(parent.time),
game_arguments: None,
type_: child.type_.or(parent.type_),
}
}
// extracts the `group:artifact` portion of a maven coordinate, dropping
// version and any classifier. used as the dedup key when merging library
// lists from a child profile on top of its parent.
fn coord_key(name: &str) -> &str {
// mojang maven coords are `group:artifact:version[:classifier]`. take
// everything up to the second colon.
let mut it = name.match_indices(':').map(|(i, _)| i);
it.next();
it.next().map_or(name, |i| &name[..i])
}
// child entries take precedence over parent entries with the same
// group:artifact. mojang and the major third-party launchers (prism,
// multimc) all dedup this way - without it, loader overrides of vanilla
// libraries (e.g. forge bumping log4j) would lose to vanilla because the
// JVM picks the first classpath match.
fn merge_libraries(
child: Vec<crate::launch_profile::model::Library>,
parent: Vec<crate::launch_profile::model::Library>,
) -> Vec<crate::launch_profile::model::Library> {
use std::collections::HashSet;
let child_keys: HashSet<&str> = child.iter().map(|l| coord_key(&l.name)).collect();
let mut out: Vec<crate::launch_profile::model::Library> = parent
.into_iter()
.filter(|l| !child_keys.contains(coord_key(&l.name)))
.collect();
out.extend(child);
out
}
fn merge_arguments(child: Option<Arguments>, parent: Option<Arguments>) -> Option<Arguments> {
match (child, parent) {
(None, None) => None,
(Some(c), None) => Some(c),
(None, Some(p)) => Some(p),
(Some(c), Some(p)) => {
let mut game = p.game;
game.extend(c.game);
let mut jvm = p.jvm;
jvm.extend(c.jvm);
Some(Arguments { game, jvm })
}
}
}
pub async fn resolve(
profile: LaunchProfile,
meta_dir: &Path,
) -> Result<LaunchProfile, ResolveError> {
use std::collections::HashSet;
let mut visited: HashSet<String> = HashSet::new();
visited.insert(profile.id.clone());
let mut current = profile;
let mut depth = 0;
while let Some(parent_id) = current.inherits_from.clone() {
depth += 1;
if depth > MAX_INHERITANCE_DEPTH {
return Err(ResolveError::DepthExceeded(MAX_INHERITANCE_DEPTH));
}
if !visited.insert(parent_id.clone()) {
return Err(ResolveError::CircularInheritance(parent_id));
}
let parent_path = meta_dir.join("versions").join(&parent_id).join("meta.json");
if !parent_path.exists() {
return Err(ResolveError::ParentNotFound(
parent_path.display().to_string(),
));
}
let parent_bytes = tokio::fs::read(&parent_path).await?;
let parent: LaunchProfile = serde_json::from_slice(&parent_bytes)
.map_err(|e| ResolveError::ParseError(parent_id.clone(), e.to_string()))?;
current = merge_into(current, parent);
}
current.inherits_from = None;
Ok(current)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::launch_profile::model::{Argument, ArgumentValue, AssetIndex, JavaVersion, Library};
use crate::launch_profile::rules::{Rule, RuleAction};
fn empty_profile(id: &str) -> LaunchProfile {
LaunchProfile {
id: id.into(),
..Default::default()
}
}
fn lib(name: &str) -> Library {
Library {
name: name.into(),
..Default::default()
}
}
fn allow_linux_rule() -> Rule {
Rule {
action: RuleAction::Allow,
os: Some(crate::launch_profile::rules::OsCondition {
name: Some("linux".into()),
..Default::default()
}),
features: None,
}
}
#[test]
fn child_id_wins() {
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.main_class = None;
let merged = merge_into(child, parent);
assert_eq!(merged.id, "child");
}
#[test]
fn merge_carries_parent_inherits_from() {
// merge_into preserves parent's inherits_from so resolve() can keep
// walking. resolve() itself clears the final result's inherits_from
// after the loop exits.
let mut child = empty_profile("child");
child.inherits_from = Some("parent".into());
let mut parent = empty_profile("parent");
parent.inherits_from = Some("grandparent".into());
let merged = merge_into(child, parent);
assert_eq!(merged.inherits_from.as_deref(), Some("grandparent"));
}
#[test]
fn merge_with_root_parent_clears_inherits_from() {
// parent with no inherits_from means the chain ends.
let mut child = empty_profile("child");
child.inherits_from = Some("parent".into());
let parent = empty_profile("parent");
let merged = merge_into(child, parent);
assert!(merged.inherits_from.is_none());
}
#[test]
fn child_main_class_overrides_parent() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
child.main_class = Some("child.Main".into());
parent.main_class = Some("parent.Main".into());
let merged = merge_into(child, parent);
assert_eq!(merged.main_class.as_deref(), Some("child.Main"));
}
#[test]
fn parent_main_class_used_when_child_missing() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.main_class = Some("parent.Main".into());
let merged = merge_into(child, parent);
assert_eq!(merged.main_class.as_deref(), Some("parent.Main"));
}
#[test]
fn libraries_are_concatenated_parent_first() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.libraries = vec![lib("p1"), lib("p2")];
child.libraries = vec![lib("c1")];
let merged = merge_into(child, parent);
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["p1", "p2", "c1"]);
}
#[test]
fn child_library_supersedes_parent_with_same_group_artifact() {
// forge declares log4j 2.17.0; vanilla declared 2.0-beta9. without
// dedup, both end up on the classpath and the JVM picks the first
// (vanilla) match - defeating forge's override. dedup keeps child's.
let mut child = empty_profile("forge");
let mut parent = empty_profile("vanilla");
parent.libraries = vec![
lib("org.apache.logging.log4j:log4j-core:2.0-beta9"),
lib("org.lwjgl:lwjgl:3.3.1"),
];
child.libraries = vec![
lib("org.apache.logging.log4j:log4j-core:2.17.0"),
lib("net.minecraftforge:forge:47.2.0"),
];
let merged = merge_into(child, parent);
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
// parent's log4j-core is filtered (superseded by child); parent's
// lwjgl stays (no conflict); child's log4j and forge come last.
assert_eq!(
names,
vec![
"org.lwjgl:lwjgl:3.3.1",
"org.apache.logging.log4j:log4j-core:2.17.0",
"net.minecraftforge:forge:47.2.0",
]
);
}
#[test]
fn coord_key_extracts_group_artifact() {
assert_eq!(coord_key("org.lwjgl:lwjgl:3.3.1"), "org.lwjgl:lwjgl");
assert_eq!(
coord_key("org.apache.logging.log4j:log4j-core:2.17.0"),
"org.apache.logging.log4j:log4j-core"
);
// with classifier
assert_eq!(
coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"),
"org.lwjgl:lwjgl"
);
// malformed (no colons) - return as-is
assert_eq!(coord_key("malformed"), "malformed");
}
#[test]
fn arguments_are_concatenated_parent_first() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-parent-game".into())],
jvm: vec![Argument::Literal("--from-parent-jvm".into())],
});
child.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-child-game".into())],
jvm: vec![Argument::Literal("--from-child-jvm".into())],
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert_eq!(
args.game,
vec![
Argument::Literal("--from-parent-game".into()),
Argument::Literal("--from-child-game".into()),
]
);
assert_eq!(
args.jvm,
vec![
Argument::Literal("--from-parent-jvm".into()),
Argument::Literal("--from-child-jvm".into()),
]
);
}
#[test]
fn arguments_from_child_only_carry_through() {
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.arguments = Some(Arguments {
game: vec![Argument::Literal("--child".into())],
jvm: Vec::new(),
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert_eq!(args.game.len(), 1);
assert!(args.jvm.is_empty());
}
#[test]
fn arguments_from_parent_only_carry_through() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![Argument::Literal("--parent-jvm".into())],
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert!(args.game.is_empty());
assert_eq!(args.jvm.len(), 1);
}
#[test]
fn conditional_arguments_with_rules_survive_merge() {
// make sure the Argument::Conditional shape isn't accidentally
// flattened or filtered during merging - rule eval happens later
// at render time, not during merge.
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.arguments = Some(Arguments {
game: vec![Argument::Conditional {
rules: vec![allow_linux_rule()],
value: ArgumentValue::Single("--linux-only".into()),
}],
jvm: Vec::new(),
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
match &args.game[0] {
Argument::Conditional { rules, .. } => {
assert_eq!(rules.len(), 1);
assert_eq!(rules[0].action, RuleAction::Allow);
}
_ => panic!("expected conditional argument to survive merge"),
}
}
#[test]
fn legacy_minecraft_arguments_child_overrides_parent() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
child.minecraft_arguments = Some("--child".into());
parent.minecraft_arguments = Some("--parent".into());
let merged = merge_into(child, parent);
assert_eq!(merged.minecraft_arguments.as_deref(), Some("--child"));
}
#[test]
fn asset_index_inherits_from_parent_when_child_absent() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.asset_index = Some(AssetIndex {
id: "5".into(),
url: "https://example.invalid/5.json".into(),
sha1: "0".repeat(40),
size: None,
total_size: None,
});
let merged = merge_into(child, parent);
assert!(merged.asset_index.is_some());
assert_eq!(merged.asset_index.unwrap().id, "5");
}
#[test]
fn java_version_inherits_from_parent_when_child_absent() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.java_version = Some(JavaVersion {
component: Some("java-runtime-gamma".into()),
major_version: 17,
});
let merged = merge_into(child, parent);
assert_eq!(
merged.java_version.as_ref().map(|j| j.major_version),
Some(17)
);
}
use tempfile::TempDir;
fn write_profile(meta_dir: &Path, profile: &LaunchProfile) {
let path = meta_dir
.join("versions")
.join(&profile.id)
.join("meta.json");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let json = serde_json::to_string_pretty(profile).unwrap();
std::fs::write(&path, json).unwrap();
}
#[tokio::test]
async fn resolve_returns_unchanged_when_no_inherits_from() {
let tmp = TempDir::new().unwrap();
let profile = empty_profile("standalone");
let resolved = resolve(profile, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "standalone");
assert!(resolved.inherits_from.is_none());
}
#[tokio::test]
async fn resolve_single_level_inheritance_merges_parent() {
let tmp = TempDir::new().unwrap();
let mut parent = empty_profile("1.20.1");
parent.main_class = Some("net.minecraft.client.main.Main".into());
parent.libraries = vec![lib("vanilla-lib")];
write_profile(tmp.path(), &parent);
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
child.libraries = vec![lib("forge-lib")];
let resolved = resolve(child, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "1.20.1-forge-47.2.0");
assert!(resolved.inherits_from.is_none());
assert_eq!(
resolved.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["vanilla-lib", "forge-lib"]);
}
#[tokio::test]
async fn resolve_errors_when_parent_missing() {
let tmp = TempDir::new().unwrap();
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
let err = resolve(child, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::ParentNotFound(_)),
"expected ParentNotFound, got {err:?}"
);
}
#[tokio::test]
async fn resolve_errors_when_parent_is_invalid_json() {
let tmp = TempDir::new().unwrap();
let parent_path = tmp.path().join("versions").join("1.20.1").join("meta.json");
std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap();
std::fs::write(&parent_path, "{ not valid json").unwrap();
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
let err = resolve(child, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::ParseError(_, _)),
"expected ParseError, got {err:?}"
);
}
#[tokio::test]
async fn resolve_multi_level_chain_merges_all_parents() {
let tmp = TempDir::new().unwrap();
// chain: grandchild -> child -> root (vanilla).
let mut root = empty_profile("1.20.1");
root.main_class = Some("net.minecraft.client.main.Main".into());
root.libraries = vec![lib("vanilla-lib")];
write_profile(tmp.path(), &root);
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
child.libraries = vec![lib("forge-lib")];
write_profile(tmp.path(), &child);
let mut grandchild = empty_profile("1.20.1-forge-47.2.0-modpack");
grandchild.inherits_from = Some("1.20.1-forge-47.2.0".into());
grandchild.libraries = vec![lib("modpack-lib")];
let resolved = resolve(grandchild, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "1.20.1-forge-47.2.0-modpack");
assert!(resolved.inherits_from.is_none());
assert_eq!(
resolved.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
// libs: root ++ child ++ grandchild (each parent prepended)
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]);
}
#[tokio::test]
async fn resolve_detects_circular_chain() {
let tmp = TempDir::new().unwrap();
// a -> b -> a (cycle)
let mut a = empty_profile("a");
a.inherits_from = Some("b".into());
write_profile(tmp.path(), &a);
let mut b = empty_profile("b");
b.inherits_from = Some("a".into());
write_profile(tmp.path(), &b);
// start from a fresh "a" profile that asks to inherit from b
let mut entry = empty_profile("a");
entry.inherits_from = Some("b".into());
let err = resolve(entry, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::CircularInheritance(ref s) if s == "a"),
"expected CircularInheritance(a), got {err:?}"
);
}
#[tokio::test]
async fn resolve_caps_depth() {
let tmp = TempDir::new().unwrap();
// build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10
// should fail with DepthExceeded.
for i in 0..=10 {
let mut p = empty_profile(&format!("v{i}"));
if i < 10 {
p.inherits_from = Some(format!("v{}", i + 1));
}
write_profile(tmp.path(), &p);
}
let mut entry = empty_profile("entry");
entry.inherits_from = Some("v0".into());
let err = resolve(entry, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::DepthExceeded(_)),
"expected DepthExceeded, got {err:?}"
);
}
}
+411
View File
@@ -0,0 +1,411 @@
// mojang rule evaluation. profiles, libraries, and argument entries can
// carry conditional rules that filter them by OS, architecture, or feature
// flags. this module is the single source of truth for that semantics -
// see `evaluate` below for the exact rules.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleAction {
Allow,
Disallow,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
pub struct OsCondition {
pub name: Option<String>,
pub arch: Option<String>,
// mojang occasionally constrains natives selection on os.version with a
// regex. rare in practice - when present, it's a substring/anchor match
// against the host OS version reported by `system::mojang_os_version`.
pub version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct FeatureSet {
pub is_demo_user: Option<bool>,
pub has_custom_resolution: Option<bool>,
// quick-play feature flags (1.20+). rmcl never sets these, so any rule
// gated on them is filtered out by features_match. listing them
// explicitly is what makes that filter work: without the fields,
// serde would silently drop them during deserialization, leaving a
// FeatureSet::default that matches everything.
pub has_quick_plays_support: Option<bool>,
pub is_quick_play_singleplayer: Option<bool>,
pub is_quick_play_multiplayer: Option<bool>,
pub is_quick_play_realms: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Rule {
pub action: RuleAction,
pub os: Option<OsCondition>,
pub features: Option<FeatureSet>,
}
pub struct RuleContext<'a> {
pub os_name: &'a str,
pub os_version: &'a str,
pub arch: &'a str,
pub features: &'a FeatureSet,
}
pub fn evaluate(rules: &[Rule], ctx: &RuleContext) -> bool {
if rules.is_empty() {
return true;
}
let mut allowed = false;
for rule in rules {
if rule_matches(rule, ctx) {
allowed = matches!(rule.action, RuleAction::Allow);
}
}
allowed
}
fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool {
if let Some(os) = &rule.os {
if let Some(name) = &os.name
&& name != ctx.os_name
{
return false;
}
if let Some(arch) = &os.arch
&& arch != ctx.arch
{
return false;
}
if let Some(pattern) = &os.version
&& !os_version_matches(pattern, ctx.os_version)
{
return false;
}
}
if let Some(required) = &rule.features
&& !features_match(required, ctx.features)
{
return false;
}
true
}
// mojang's os.version constraints are typically anchored regex patterns
// (e.g. `^10\\.`). we do a substring containment check as a defensive
// approximation that doesn't pull in the `regex` crate. when the host
// os_version is empty (Windows fallback path returns ""), version-gated
// rules don't match - which is the conservative default.
fn os_version_matches(pattern: &str, host_version: &str) -> bool {
if host_version.is_empty() {
return false;
}
// strip common regex anchors and metacharacters for substring lookup.
// good enough for the rare profile that uses os.version.
let needle = pattern
.trim_start_matches('^')
.trim_end_matches('$')
.trim_end_matches('.')
.trim_end_matches('\\');
host_version.contains(needle)
}
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
let pairs = [
(required.is_demo_user, current.is_demo_user),
(
required.has_custom_resolution,
current.has_custom_resolution,
),
(
required.has_quick_plays_support,
current.has_quick_plays_support,
),
(
required.is_quick_play_singleplayer,
current.is_quick_play_singleplayer,
),
(
required.is_quick_play_multiplayer,
current.is_quick_play_multiplayer,
),
(required.is_quick_play_realms, current.is_quick_play_realms),
];
pairs.iter().all(|(req, cur)| match req {
Some(want) => cur.unwrap_or(false) == *want,
None => true,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> {
RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features,
}
}
#[test]
fn empty_rules_allow() {
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&[], &ctx));
}
#[test]
fn single_allow_matching_os_allows() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn single_disallow_matching_os_disallows() {
let rules = vec![Rule {
action: RuleAction::Disallow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn allow_without_os_match_disallows_by_default() {
// explicit allow for windows; we are on linux; nothing matches;
// default state remains disallow.
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("windows".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn last_matching_rule_wins_when_allow_then_disallow() {
let rules = vec![
Rule {
action: RuleAction::Allow,
os: None,
features: None,
},
Rule {
action: RuleAction::Disallow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
..Default::default()
}),
features: None,
},
];
let features = FeatureSet::default();
let osx_ctx = RuleContext {
os_name: "osx",
os_version: "6.0",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &osx_ctx));
// and on linux: only the first rule matches → still allow.
let lin = linux_ctx(&features);
assert!(evaluate(&rules, &lin));
}
#[test]
fn last_matching_rule_wins_when_disallow_then_allow() {
let rules = vec![
Rule {
action: RuleAction::Disallow,
os: None,
features: None,
},
Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
},
];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn arch_mismatch_blocks_rule() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: Some("arm64".into()),
version: None,
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
// we are on linux but x86_64, not arm64 → rule does not match.
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn feature_required_true_matches_when_ctx_true() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: Some(FeatureSet {
is_demo_user: Some(true),
..Default::default()
}),
}];
let demo_features = FeatureSet {
is_demo_user: Some(true),
..Default::default()
};
let ctx = RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features: &demo_features,
};
assert!(evaluate(&rules, &ctx));
}
#[test]
fn feature_required_true_blocks_when_ctx_false() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: Some(FeatureSet {
is_demo_user: Some(true),
..Default::default()
}),
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn no_os_no_features_rule_always_matches() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn os_version_pattern_matches_against_host() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
version: Some("^10\\.".into()),
}),
features: None,
}];
let features = FeatureSet::default();
let ctx_match = RuleContext {
os_name: "osx",
os_version: "10.15.7",
arch: "x86_64",
features: &features,
};
assert!(evaluate(&rules, &ctx_match));
let ctx_mismatch = RuleContext {
os_name: "osx",
os_version: "13.2.1",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &ctx_mismatch));
}
#[test]
fn os_version_pattern_does_not_match_when_host_unknown() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("windows".into()),
arch: None,
version: Some("^10\\.".into()),
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = RuleContext {
os_name: "windows",
os_version: "",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn rule_deserializes_from_mojang_json() {
// shape lifted from real mojang library rules.
let json = r#"{
"action": "allow",
"os": { "name": "osx" }
}"#;
let rule: Rule = serde_json::from_str(json).unwrap();
assert_eq!(rule.action, RuleAction::Allow);
assert_eq!(
rule.os.as_ref().and_then(|o| o.name.as_deref()),
Some("osx")
);
assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none());
assert!(rule.features.is_none());
}
#[test]
fn rule_deserializes_with_features() {
let json = r#"{
"action": "allow",
"features": { "is_demo_user": true }
}"#;
let rule: Rule = serde_json::from_str(json).unwrap();
assert_eq!(rule.action, RuleAction::Allow);
assert!(rule.os.is_none());
assert_eq!(
rule.features.as_ref().and_then(|f| f.is_demo_user),
Some(true)
);
}
}
+37
View File
@@ -0,0 +1,37 @@
// system-detection helpers shared by launch and install paths. mojang
// names some things differently from rust's std::env::consts (e.g. macOS
// is "osx" in mojang profile rules), so this module is the single source
// of truth for translating.
pub fn mojang_os_name() -> &'static str {
match std::env::consts::OS {
"macos" => "osx",
other => other,
}
}
pub fn mojang_arch_name() -> &'static str {
match std::env::consts::ARCH {
"x86" => "x86",
"x86_64" => "x86_64",
"aarch64" => "arm64",
other => other,
}
}
// the host OS version string. mojang rules occasionally constrain natives
// selection on os.version with a regex (e.g. macOS 10.x-only natives).
// rust's stdlib doesn't expose this, so we read it where it's cheap and
// reliable: linux via /proc/sys/kernel/osrelease, other platforms return
// empty. when the host string is empty, version-gated rules don't match
// (conservative default in the rule evaluator) - which is fine because
// real-world profiles using os.version are vanishingly rare.
pub fn mojang_os_version() -> String {
#[cfg(target_os = "linux")]
{
if let Ok(s) = std::fs::read_to_string("/proc/sys/kernel/osrelease") {
return s.trim().to_string();
}
}
String::new()
}
+203
View File
@@ -0,0 +1,203 @@
// template substitution for mojang-style launch arguments. profiles use
// `${variable_name}` placeholders that the launcher fills in at launch
// time from the active session: paths, the user's account info, the
// classpath, the resolved natives directory, and so on.
//
// the full set of variables is documented in `TemplateContext`. unknown
// placeholders are left as-is and logged at `warn` level - that way if
// mojang adds a new variable in the future, the launcher fails open
// rather than silently swallowing it.
use std::path::Path;
pub struct TemplateContext<'a> {
pub library_directory: &'a Path,
pub classpath_separator: &'a str,
pub version_name: &'a str,
pub version_type: &'a str,
pub natives_directory: &'a Path,
pub classpath: &'a str,
pub game_directory: &'a Path,
pub assets_root: &'a Path,
pub assets_index_name: &'a str,
pub auth_player_name: &'a str,
pub auth_uuid: &'a str,
pub auth_access_token: &'a str,
pub auth_xuid: &'a str,
pub user_type: &'a str,
pub user_properties: &'a str,
pub launcher_name: &'a str,
pub launcher_version: &'a str,
pub clientid: &'a str,
}
pub fn substitute(input: &str, ctx: &TemplateContext) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(open) = rest.find("${") {
out.push_str(&rest[..open]);
let after_open = &rest[open + 2..];
match after_open.find('}') {
Some(close_rel) => {
let name = &after_open[..close_rel];
match lookup(name, ctx) {
Some(value) => out.push_str(&value),
None => {
tracing::warn!("unknown launch template variable: ${{{}}}", name);
out.push_str("${");
out.push_str(name);
out.push('}');
}
}
rest = &after_open[close_rel + 1..];
}
None => {
// unclosed `${...` - emit the rest literally and stop.
out.push_str("${");
out.push_str(after_open);
return out;
}
}
}
out.push_str(rest);
out
}
// quick-play templates (`${quickPlayPath}`, `${quickPlaySingleplayer}`,
// `${quickPlayMultiplayer}`, `${quickPlayRealms}`) are intentionally not
// listed here. they only appear in `arguments.game` entries gated on
// `is_quick_play_*` feature flags; since rmcl never sets those flags
// (FeatureSet defaults to None across the board), the surrounding
// conditional argument is filtered out by the rule evaluator before
// template substitution even runs. if we ever expose quick-play to users,
// add the variables here AND set the corresponding feature flags in
// RuleContext at launch.
fn lookup(name: &str, ctx: &TemplateContext) -> Option<String> {
Some(match name {
"library_directory" => ctx.library_directory.display().to_string(),
"classpath_separator" => ctx.classpath_separator.to_string(),
"version_name" => ctx.version_name.to_string(),
"version_type" => ctx.version_type.to_string(),
"natives_directory" => ctx.natives_directory.display().to_string(),
"classpath" => ctx.classpath.to_string(),
"game_directory" => ctx.game_directory.display().to_string(),
"assets_root" => ctx.assets_root.display().to_string(),
"assets_index_name" => ctx.assets_index_name.to_string(),
"auth_player_name" => ctx.auth_player_name.to_string(),
"auth_uuid" => ctx.auth_uuid.to_string(),
"auth_access_token" => ctx.auth_access_token.to_string(),
"auth_xuid" => ctx.auth_xuid.to_string(),
"user_type" => ctx.user_type.to_string(),
"user_properties" => ctx.user_properties.to_string(),
"launcher_name" => ctx.launcher_name.to_string(),
"launcher_version" => ctx.launcher_version.to_string(),
"clientid" => ctx.clientid.to_string(),
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
// owns the path buffers so tests don't have to declare them inline; the
// ctx() method borrows from self to build a TemplateContext with the
// standard set of values. windows() returns a fixture with backslash
// paths so the OS-independence test stays self-contained.
struct Fixture {
lib: PathBuf,
nat: PathBuf,
game: PathBuf,
assets: PathBuf,
user_properties: String,
}
impl Fixture {
fn unix() -> Self {
Self {
lib: PathBuf::from("/m/libraries"),
nat: PathBuf::from("/m/natives"),
game: PathBuf::from("/i/.minecraft"),
assets: PathBuf::from("/m/assets"),
user_properties: "{}".to_string(),
}
}
fn windows() -> Self {
Self {
lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"),
nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"),
game: PathBuf::from(r"C:\Users\test\.minecraft"),
assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"),
user_properties: "{}".to_string(),
}
}
fn ctx(&self) -> TemplateContext<'_> {
TemplateContext {
library_directory: &self.lib,
classpath_separator: ":",
version_name: "1.20.1",
version_type: "release",
natives_directory: &self.nat,
classpath: "a.jar:b.jar",
game_directory: &self.game,
assets_root: &self.assets,
assets_index_name: "5",
auth_player_name: "Player",
auth_uuid: "00000000-0000-0000-0000-000000000000",
auth_access_token: "token",
auth_xuid: "0",
user_type: "msa",
user_properties: &self.user_properties,
launcher_name: "rmcl",
launcher_version: "0.3.0",
clientid: "0",
}
}
}
#[rstest::rstest]
#[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")]
#[case::single_known("v=${version_name}", "v=1.20.1")]
#[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")]
#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")]
#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")]
#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")]
#[case::path(
"-DlibraryDirectory=${library_directory}",
"-DlibraryDirectory=/m/libraries"
)]
#[case::empty_input("", "")]
fn substitute_handles(#[case] input: &str, #[case] expected: &str) {
let fx = Fixture::unix();
assert_eq!(substitute(input, &fx.ctx()), expected);
}
#[test]
fn substituted_value_is_not_recursively_substituted() {
// simulate a user_properties value that happens to contain a ${...}
// pattern. it should NOT trigger another substitution pass.
let mut fx = Fixture::unix();
fx.user_properties = "${version_name}".to_string();
assert_eq!(
substitute("${user_properties}", &fx.ctx()),
"${version_name}"
);
}
#[test]
fn windows_style_backslashes_in_value_pass_through() {
// simulate a Windows install where library_directory is a path with
// backslashes. the substitution must not interpret backslashes as
// escape sequences or do anything else clever - it just copies the
// value into the output.
let fx = Fixture::windows();
let result = substitute("-Dpath=${library_directory}", &fx.ctx());
assert!(
result.contains(r"C:\Users\test\.minecraft\libraries"),
"expected backslashes preserved, got: {result}"
);
}
}
+19
View File
@@ -0,0 +1,19 @@
// crate root. main.rs is a thin wrapper that imports the two entry points
// re-exported below; everything else stays crate-private. integration tests
// in tests/ that need to reach in deeper can use `rmcl::auth`, `rmcl::net`,
// etc. directly; cli + migrate stay private because they have nothing
// general to expose.
pub mod auth;
mod cli;
pub mod config;
pub mod instance;
pub mod instance_logs;
pub mod launch_profile;
mod migrate;
pub mod net;
pub mod running;
pub mod tui;
pub use cli::init as cli_init;
pub use migrate::run_legacy_rename as migrate_legacy_rename;
+5 -15
View File
@@ -1,24 +1,14 @@
pub mod auth;
mod cli;
pub mod config;
pub mod instance;
pub mod instance_logs;
mod migrate;
pub mod net;
pub mod running;
pub mod tui;
#[tokio::main]
async fn main() {
// Run before logging::init() so the cache rename isn't blocked by a
// freshly-created ~/.cache/rmcl/ directory.
migrate::run_legacy_rename();
rmcl::migrate_legacy_rename();
// Guard must stay in scope to keep the log file writer alive
let _guard = tui::logging::init();
let _guard = rmcl::tui::logging::init();
tracing::info!("Starting rmcl {}", env!("CARGO_PKG_VERSION"));
if let Err(e) = color_eyre::install() {
eprintln!("Failed to install color-eyre: {}", e);
tracing::warn!("Failed to install color-eyre handler: {}", e);
}
cli::init().await
rmcl::cli_init().await
}
+25 -41
View File
@@ -39,7 +39,11 @@ fn rename_top_level(old: &Path, new: &Path) {
return;
}
match fs::rename(old, new) {
Ok(_) => eprintln!("rmcl migration: moved {} -> {}", old.display(), new.display()),
Ok(_) => eprintln!(
"rmcl migration: moved {} -> {}",
old.display(),
new.display()
),
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
if let Err(e2) = copy_dir_recursive(old, new) {
eprintln!(
@@ -171,27 +175,12 @@ fn sanitize(name: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn unique_tmp(label: &str) -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let p = std::env::temp_dir().join(format!("rmcl_migrate_test_{label}_{nanos}_{n}"));
std::fs::create_dir_all(&p).unwrap();
p
}
#[test]
fn rename_top_level_moves_when_only_old_exists() {
let root = unique_tmp("only_old");
let old = root.join("mcl");
let new = root.join("rmcl");
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
fs::create_dir_all(old.join("sub")).unwrap();
fs::write(old.join("sub").join("f.txt"), b"hi").unwrap();
@@ -204,9 +193,9 @@ mod tests {
#[test]
fn rename_top_level_skips_when_only_new_exists() {
let root = unique_tmp("only_new");
let old = root.join("mcl");
let new = root.join("rmcl");
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
fs::create_dir_all(&new).unwrap();
fs::write(new.join("marker.txt"), b"keep").unwrap();
@@ -218,9 +207,9 @@ mod tests {
#[test]
fn rename_top_level_skips_when_both_exist() {
let root = unique_tmp("both");
let old = root.join("mcl");
let new = root.join("rmcl");
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
fs::create_dir_all(&old).unwrap();
fs::create_dir_all(&new).unwrap();
fs::write(old.join("a"), b"old").unwrap();
@@ -236,9 +225,9 @@ mod tests {
#[test]
fn rename_top_level_noop_when_neither_exists() {
let root = unique_tmp("neither");
let old = root.join("mcl");
let new = root.join("rmcl");
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
rename_top_level(&old, &new);
@@ -248,7 +237,8 @@ mod tests {
#[test]
fn cleanup_instance_leftovers_removes_shim_and_log4j() {
let instances = unique_tmp("inst").join("instances");
let tmp = tempfile::tempdir().unwrap();
let instances = tmp.path().join("instances");
let mc = instances.join("Test").join(".minecraft");
fs::create_dir_all(&mc).unwrap();
fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap();
@@ -262,17 +252,11 @@ mod tests {
assert!(mc.join("keep.txt").exists());
}
#[test]
fn cleanup_instance_leftovers_handles_missing_dir() {
let nowhere = unique_tmp("missing").join("does-not-exist");
cleanup_instance_leftovers(&nowhere);
}
#[test]
#[cfg(target_os = "linux")]
fn rewrite_linux_desktop_entries_renames_and_rewrites_exec() {
let root = unique_tmp("linux_desk");
let data = root.clone();
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path();
let instances = data.join("rmcl").join("instances");
let apps = data.join("applications");
fs::create_dir_all(instances.join("MyPack")).unwrap();
@@ -284,7 +268,7 @@ mod tests {
)
.unwrap();
rewrite_linux_desktop_entries(&data, &instances);
rewrite_linux_desktop_entries(data, &instances);
let new_entry = apps.join("rmcl-MyPack.desktop");
assert!(!old_entry.exists(), "old .desktop should be removed");
@@ -295,9 +279,9 @@ mod tests {
#[test]
fn copy_dir_recursive_copies_nested_tree() {
let root = unique_tmp("copy");
let src = root.join("a");
let dst = root.join("b");
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("a");
let dst = tmp.path().join("b");
fs::create_dir_all(src.join("nested")).unwrap();
fs::write(src.join("top.txt"), b"top").unwrap();
fs::write(src.join("nested").join("inner.txt"), b"inner").unwrap();
+82 -4
View File
@@ -45,8 +45,20 @@ pub struct FabricLibrary {
}
pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", FABRIC_META_BASE);
fetch_fabric_game_versions_from(client, FABRIC_META_BASE).await
}
// same as fetch_fabric_game_versions but lets tests point at a wiremock
// server. fabric's API is hierarchical, so we take the base URL and append
// the rest of the path inside.
pub async fn fetch_fabric_game_versions_from(
client: &HttpClient,
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Fabric game versions from {}", url);
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Fabric game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -61,22 +73,81 @@ pub async fn fetch_fabric_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version);
client.get_json(&url).await
fetch_fabric_versions_from(client, FABRIC_META_BASE, game_version).await
}
pub async fn fetch_fabric_versions_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
tracing::debug!("Fetching Fabric loader versions for {}", game_version);
let versions: Vec<FabricLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_fabric_profile(
client: &HttpClient,
game_version: &str,
loader_version: &str,
) -> Result<FabricProfile, NetError> {
fetch_fabric_profile_from(client, FABRIC_META_BASE, game_version, loader_version).await
}
pub async fn fetch_fabric_profile_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
loader_version: &str,
) -> Result<FabricProfile, NetError> {
let url = format!(
"{}/versions/loader/{}/{}/profile/json",
FABRIC_META_BASE, game_version, loader_version
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
// like fetch_fabric_profile but also returns the raw response bytes so the
// caller can write the upstream JSON byte-for-byte to disk. used by the
// install path so we don't lose data (e.g. any future arguments field) by
// re-serializing through our narrow FabricProfile struct.
pub async fn fetch_fabric_profile_with_raw(
client: &HttpClient,
game_version: &str,
loader_version: &str,
) -> Result<(FabricProfile, Vec<u8>), NetError> {
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version).await
}
pub async fn fetch_fabric_profile_with_raw_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
loader_version: &str,
) -> Result<(FabricProfile, Vec<u8>), NetError> {
let url = format!(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Fabric profile").await
}
// each fabric library entry has a maven coordinate and a base url.
// the coordinate gets resolved to a path and combined with the url to download.
pub async fn download_fabric_libraries(
@@ -85,6 +156,11 @@ pub async fn download_fabric_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Fabric libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -109,10 +185,12 @@ pub async fn download_fabric_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Fabric library: {}", lib.name);
tracing::trace!("Fabric library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Fabric library resolution complete for {}", profile.id);
Ok(())
}
+189 -106
View File
@@ -7,7 +7,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::{GameVersion, InstallError, InstallerError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::{set_action, set_sub_action};
@@ -26,7 +26,16 @@ pub async fn fetch_forge_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let promotions: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
fetch_forge_versions_from(client, FORGE_PROMOTIONS_URL, game_version).await
}
// same as fetch_forge_versions but lets tests point at a wiremock server.
pub async fn fetch_forge_versions_from(
client: &HttpClient,
promotions_url: &str,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let promotions: ForgePromotions = client.get_json(promotions_url).await?;
let prefix = format!("{}-", game_version);
let mut versions: Vec<String> = promotions
@@ -38,13 +47,25 @@ pub async fn fetch_forge_versions(
versions.sort();
versions.dedup();
tracing::debug!(
"Resolved {} Forge version(s) for Minecraft {} from promotions",
versions.len(),
game_version
);
Ok(versions)
}
// extracts unique game versions from the promotion keys by splitting off
// the "-recommended"/"-latest" suffix
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
fetch_forge_game_versions_from(client, FORGE_PROMOTIONS_URL).await
}
pub async fn fetch_forge_game_versions_from(
client: &HttpClient,
promotions_url: &str,
) -> Result<Vec<GameVersion>, NetError> {
let promos: ForgePromotions = client.get_json(promotions_url).await?;
let mut game_versions: Vec<String> = promos
.promos
@@ -54,6 +75,10 @@ pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVe
game_versions.sort();
game_versions.dedup();
game_versions.reverse();
tracing::debug!(
"Resolved {} Forge game version(s) from promotions",
game_versions.len()
);
Ok(game_versions
.into_iter()
@@ -88,13 +113,20 @@ pub async fn download_forge_installer(
let mut last_err = None;
for slug in &slugs {
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
tracing::debug!("Trying Forge installer slug '{}'", slug);
match download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => return Ok(()),
Err(e) => last_err = Some(e),
Ok(()) => {
tracing::debug!("Downloaded Forge installer using slug '{}'", slug);
return Ok(());
}
Err(e) => {
tracing::debug!("Forge installer slug '{}' failed: {}", slug, e);
last_err = Some(e);
}
}
}
@@ -109,7 +141,7 @@ pub async fn run_forge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running Forge installer...");
@@ -124,7 +156,13 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn Forge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
@@ -135,9 +173,16 @@ pub async fn run_forge_installer(
} else {
stderr.lines().last().unwrap_or("unknown error").to_string()
};
return Err(NetError::InstallerFailed(detail));
tracing::debug!(
"Forge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(detail));
}
tracing::debug!("Forge installer completed successfully");
Ok(())
}
@@ -170,74 +215,103 @@ pub(crate) async fn install_forge_from_profile(
installer_path: &Path,
meta_dir: &Path,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
use std::io::Read;
set_action("Installing legacy Forge from profile...");
tracing::debug!(
"Installing legacy Forge from {} into {}",
installer_path.display(),
meta_dir.display()
);
let file = std::fs::File::open(installer_path)?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| NetError::Parse(format!("Failed to open installer as ZIP: {e}")))?;
let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to open installer as ZIP: {e}"
)))
})?;
let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| {
NetError::Parse(format!("install_profile.json not found in installer: {e}"))
InstallError::Installer(InstallerError::Profile(format!(
"install_profile.json not found in installer: {e}"
)))
})?;
serde_json::from_reader(entry)
.map_err(|e| NetError::Parse(format!("Failed to parse install_profile.json: {e}")))?
serde_json::from_reader(entry).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to parse install_profile.json: {e}"
)))
})?
};
let version_info = profile_data
.get("versionInfo")
.ok_or_else(|| NetError::Parse("install_profile.json missing versionInfo".into()))?;
let install_info = profile_data
.get("install")
.ok_or_else(|| NetError::Parse("install_profile.json missing install section".into()))?;
let main_class = version_info
.get("mainClass")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing versionInfo.mainClass".into()))?
.to_string();
let version_info = profile_data.get("versionInfo").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing versionInfo".into(),
))
})?;
let install_info = profile_data.get("install").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing install section".into(),
))
})?;
let libraries = version_info
.get("libraries")
.and_then(|v| v.as_array())
.ok_or_else(|| NetError::Parse("missing versionInfo.libraries".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"missing versionInfo.libraries".into(),
))
})?;
let file_path = install_info
.get("filePath")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.filePath".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
})?;
let install_path_coord = install_info
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.path".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
})?;
// extract the universal jar to the correct maven location
let universal_maven_path =
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Invalid maven coord in install.path: {install_path_coord}"
))
)))
})?;
set_sub_action("Extracting universal JAR...");
let universal_dest = meta_dir.join("libraries").join(&universal_maven_path);
if let Some(parent) = universal_dest.parent() {
std::fs::create_dir_all(parent)?;
std::fs::create_dir_all(parent)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
}
{
let mut entry = archive.by_name(file_path).map_err(|e| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Universal JAR '{file_path}' not found in installer: {e}"
))
)))
})?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(&universal_dest, &buf)?;
entry
.read_to_end(&mut buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
std::fs::write(&universal_dest, &buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
tracing::debug!(
"Extracted legacy Forge universal JAR to {} ({} bytes)",
universal_dest.display(),
buf.len()
);
}
// download libraries needed by this forge version. libs with a url field
@@ -251,12 +325,15 @@ pub(crate) async fn install_forge_from_profile(
let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p,
None => {
return Err(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
return Err(InstallError::Installer(InstallerError::Profile(format!(
"Invalid Maven coordinate: {name}"
))));
}
};
let dest = libraries_dir.join(&maven_path);
if dest.exists() {
tracing::trace!("Legacy Forge library already cached: {}", name);
continue;
}
@@ -268,81 +345,34 @@ pub(crate) async fn install_forge_from_profile(
let download_url = format!("{base_url}/{maven_path}");
set_sub_action(name);
tracing::debug!("Downloading legacy Forge library {}", name);
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
// old forge profiles store game arguments (like --tweakClass) in
// minecraftArguments. extract non-template args to pass at launch.
let game_arguments: Vec<String> = version_info
.get("minecraftArguments")
.and_then(|v| v.as_str())
.map(extract_extra_game_args)
.unwrap_or_default();
set_action("Saving Forge profile...");
let lib_entries: Vec<serde_json::Value> = libraries
.iter()
.filter_map(|l| {
l.get("name")
.and_then(|v| v.as_str())
.map(|n| serde_json::json!({"name": n}))
})
.collect();
let profile_json = serde_json::json!({
"mainClass": main_class,
"libraries": lib_entries,
"gameArguments": game_arguments,
});
crate::instance::loader::save_profile_json(meta_dir, profile_filename, &profile_json)?;
// write the installer's versionInfo as compact JSON. it already has the
// mainClass, the full library list (with name + url for forge-hosted
// libs), and minecraftArguments (the legacy --tweakClass etc). the
// launch flow parses this as a LaunchProfile and - if there's no
// inheritsFrom field - implicitly inherits from the configured game
// version so vanilla libraries layer in via resolve().
//
// we use serde_json::to_vec (not the pretty-print variant via
// save_profile_json) so the written file is content-faithful: every
// field present in the installer's versionInfo round-trips. key order
// and whitespace may differ from the original installer JSON because
// the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped.
let serialized = serde_json::to_vec(version_info).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to serialize Forge profile: {e}"
)))
})?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(())
}
// pulls out game arguments from old forge's minecraftArguments string that
// the launcher doesn't already handle. skips template variables (${...})
// and standard args like --username that we build ourselves.
fn extract_extra_game_args(minecraft_arguments: &str) -> Vec<String> {
let handled = [
"--username",
"--version",
"--gameDir",
"--assetsDir",
"--assetIndex",
"--uuid",
"--accessToken",
"--userProperties",
"--userType",
];
let tokens: Vec<&str> = minecraft_arguments.split_whitespace().collect();
let mut result = Vec::new();
let mut i = 0;
while i < tokens.len() {
let token = tokens[i];
if token.starts_with("--") {
if handled.contains(&token) {
// skip the flag and its value
i += 2;
continue;
}
result.push(token.to_string());
// if the next token is a value (not a flag or template), include it
if i + 1 < tokens.len() && !tokens[i + 1].starts_with("--") {
let val = tokens[i + 1];
if !val.starts_with("${") {
result.push(val.to_string());
}
i += 2;
continue;
}
}
i += 1;
}
result
}
#[cfg(test)]
mod tests {
use super::*;
@@ -375,4 +405,57 @@ mod tests {
Err(e) => panic!("fetch_forge_game_versions failed: {}", e),
}
}
// builds an in-memory zip in a tempdir with the given json as
// install_profile.json. lets the legacy-install-profile detector be
// tested without an actual forge installer.
fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf {
use std::io::Write;
let path = tmp.join("installer.jar");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
zip.start_file("install_profile.json", opts).unwrap();
zip.write_all(serde_json::to_string(json).unwrap().as_bytes())
.unwrap();
zip.finish().unwrap();
path
}
#[test]
fn has_legacy_install_profile_true_when_version_info_present() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"install": {},
"versionInfo": {
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
"mainClass": "net.minecraft.launchwrapper.Launch"
}
}),
);
assert!(has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_when_version_info_absent() {
let tmp = tempfile::tempdir().unwrap();
let jar = make_installer_zip(
tmp.path(),
&serde_json::json!({
"spec": 1,
"minecraft": "1.20.1",
"data": {}
}),
);
assert!(!has_legacy_install_profile(&jar));
}
#[test]
fn has_legacy_install_profile_false_for_missing_jar() {
assert!(!has_legacy_install_profile(std::path::Path::new(
"/nonexistent/installer.jar"
)));
}
}
+125 -33
View File
@@ -23,8 +23,6 @@ pub enum NetError {
Parse(String),
#[error("Server returned error status {status}: {url}")]
StatusError { status: u16, url: String },
#[error("Installer process failed: {0}")]
InstallerFailed(String),
#[error("Task failed: {0}")]
TaskFailed(String),
}
@@ -42,14 +40,19 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
let client = Client::builder()
.user_agent(format!(
"rmcl/{} (Minecraft Launcher)",
env!("CARGO_PKG_VERSION")
))
.user_agent(user_agent.clone())
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new());
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to build configured HTTP client, falling back to reqwest default: {}",
e
);
Client::new()
});
tracing::trace!("Created HTTP client with user-agent '{}'", user_agent);
Self { inner: client }
}
@@ -58,24 +61,103 @@ impl HttpClient {
}
pub async fn get(&self, url: &str) -> Result<reqwest::Response, NetError> {
tracing::trace!("HTTP GET {}", url);
let response = self.inner.get(url).send().await?;
if !response.status().is_success() {
tracing::debug!(
"HTTP GET {} returned non-success status {}",
url,
response.status()
);
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_string(),
});
}
tracing::trace!("HTTP GET {} succeeded with {}", url, response.status());
Ok(response)
}
pub async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, NetError> {
Ok(self.get(url).await?.json().await?)
get_with_retry(self, url, |resp| async move { Ok(resp.json().await?) }).await
}
pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, NetError> {
get_with_retry(
self,
url,
|resp| async move { Ok(resp.bytes().await?.to_vec()) },
)
.await
}
// fetch JSON and also keep the raw bytes. used by install paths that
// want both the parsed shape (for downloading libraries from it) and
// the original bytes (to write byte-for-byte to the loader-profiles
// cache, so any field we don't know about survives).
pub async fn get_json_with_raw<T: DeserializeOwned>(
&self,
url: &str,
label: &str,
) -> Result<(T, Vec<u8>), NetError> {
tracing::debug!("Fetching {} JSON from {}", label, url);
let raw = self.get_bytes(url).await?;
tracing::trace!("Fetched {} byte(s) for {}", raw.len(), label);
let parsed: T = serde_json::from_slice(&raw)
.map_err(|e| NetError::Parse(format!("Failed to parse {label}: {e}")))?;
Ok((parsed, raw))
}
}
// shared retry envelope around `client.get(url).await? -> decode`. retries
// transient failures (timeouts, connect errors, 5xx) with exponential
// backoff. used by both get_json and get_bytes.
async fn get_with_retry<T, F, Fut>(client: &HttpClient, url: &str, decode: F) -> Result<T, NetError>
where
F: Fn(reqwest::Response) -> Fut,
Fut: std::future::Future<Output = Result<T, NetError>>,
{
for attempt in 0..=MAX_RETRIES {
match client.get(url).await {
Ok(resp) => match decode(resp).await {
Ok(value) => return Ok(value),
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
},
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
unreachable!("retry loop returns on success or final error")
}
const MAX_RETRIES: u32 = 3;
const RETRY_BASE_DELAY_MS: u64 = 500;
async fn sleep_before_retry(kind: &str, url: &str, attempt: u32, err: &NetError) {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt);
tracing::warn!(
"{} failed, retrying after {}ms (attempt {}/{}): {}: {}",
kind,
delay,
attempt + 2,
MAX_RETRIES + 1,
url,
err
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
// total will be 0 if the server doesn't send content-length, so callers
// should handle that gracefully. retries transient failures with exponential backoff.
@@ -85,30 +167,25 @@ pub async fn download_file(
dest: &Path,
progress_cb: impl Fn(u64, u64),
) -> Result<(), NetError> {
let mut last_error = None;
tracing::debug!("Downloading {} to {}", url, dest.display());
for attempt in 0..=MAX_RETRIES {
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying download (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
match download_file_once(client, url, dest, &progress_cb).await {
Ok(()) => return Ok(()),
Ok(()) => {
tracing::debug!("Downloaded {} to {}", url, dest.display());
return Ok(());
}
Err(e) if is_retryable(&e) => {
last_error = Some(e);
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("download", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
Err(last_error.unwrap())
unreachable!("retry loop returns on success or final error")
}
// single attempt at downloading a file to disk
@@ -122,6 +199,7 @@ async fn download_file_once(
let response = client.get(url).await?;
let total = response.content_length().unwrap_or(0);
tracing::trace!("Download content length for {}: {}", url, total);
if let Some(parent) = dest.parent() {
tokio::fs::create_dir_all(parent).await?;
@@ -136,11 +214,15 @@ async fn download_file_once(
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
file.flush().await?;
Ok(())
}
// body decode errors and timeouts are worth retrying, but a 404 or disk error isn't
// body decode errors and timeouts are worth retrying, but a 404 or disk
// error isn't. Parse errors stay non-retryable: by the time we hit one
// the response body has fully arrived, so the failure means the upstream
// returned malformed JSON - retrying won't fix that.
fn is_retryable(err: &NetError) -> bool {
match err {
NetError::Http(e) => e.is_timeout() || e.is_body() || e.is_connect(),
@@ -156,12 +238,28 @@ pub fn detect_java_path() -> String {
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
if bin.exists() {
tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
return bin.to_string_lossy().to_string();
}
tracing::warn!(
"JAVA_HOME is set to {}, but {} does not exist",
java_home,
bin.display()
);
}
match which::which("java") {
Ok(path) => {
tracing::trace!("Detected Java from PATH: {}", path.display());
path.to_string_lossy().to_string()
}
Err(e) => {
tracing::warn!(
"Could not find java on PATH, falling back to literal 'java': {}",
e
);
"java".to_string()
}
}
which::which("java")
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "java".to_string())
}
// converts maven coordinates like "org.example:artifact:1.0" into a
@@ -236,10 +334,4 @@ mod tests {
fn maven_empty_string() {
assert_eq!(maven_coord_to_path(""), None);
}
#[test]
fn detect_java_falls_back_to_java() {
let result = detect_java_path();
assert!(!result.is_empty());
}
}
+70 -5
View File
@@ -66,9 +66,16 @@ pub fn loader_from_dependencies(
];
for (key, loader) in &loaders {
if let Some(version) = deps.get(*key) {
tracing::trace!(
"Resolved Modrinth loader dependency {}={} as {}",
key,
version,
loader
);
return (Some(*loader), Some(version.clone()));
}
}
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
(None, None)
}
@@ -101,7 +108,14 @@ pub async fn fetch_project(
slug_or_id: &str,
) -> Result<ProjectInfo, crate::net::NetError> {
let url = format!("{}/project/{}", API_BASE, url_encode(slug_or_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth project '{}'", slug_or_id);
let project: ProjectInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth project '{}' ({})",
project.slug,
project.id
);
Ok(project)
}
pub async fn fetch_versions(
@@ -113,7 +127,14 @@ pub async fn fetch_versions(
API_BASE,
url_encode(slug_or_id)
);
client.get_json(&url).await
tracing::debug!("Fetching Modrinth versions for project '{}'", slug_or_id);
let versions: Vec<VersionInfo> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Modrinth version(s) for project '{}'",
versions.len(),
slug_or_id
);
Ok(versions)
}
pub async fn fetch_version(
@@ -121,7 +142,15 @@ pub async fn fetch_version(
version_id: &str,
) -> Result<VersionInfo, crate::net::NetError> {
let url = format!("{}/version/{}", API_BASE, url_encode(version_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth version '{}'", version_id);
let version: VersionInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth version '{}' ({}) with {} file(s)",
version.name,
version.id,
version.files.len()
);
Ok(version)
}
// grabs the primary file from a version, falling back to the first file
@@ -135,28 +164,64 @@ pub async fn download_mrpack(
.files
.iter()
.find(|f| f.primary)
.or_else(|| version.files.first())
.or_else(|| {
tracing::warn!(
"Modrinth version '{}' has no primary file; using first file",
version.id
);
version.files.first()
})
.ok_or_else(|| crate::net::NetError::Parse("No files in version".to_string()))?;
let mrpack_path = dest.join(&file.filename);
tracing::info!(
"Downloading Modrinth pack file '{}' for version '{}' to {}",
file.filename,
version.id,
mrpack_path.display()
);
crate::net::download_file(client, &file.url, &mrpack_path, |_, _| {}).await?;
Ok(mrpack_path)
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
Ok(index)
}
#[cfg(test)]
mod tests {
use super::*;
// covers each branch of url_encode: unreserved bytes pass through; the
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
// chars, so each byte of the codepoint encodes separately.
#[rstest::rstest]
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
#[case::space("hello world", "hello%20world")]
#[case::reserved("/?&=#", "%2F%3F%26%3D%23")]
#[case::utf8_emoji("\u{2603}", "%E2%98%83")]
#[case::empty("", "")]
fn url_encode_handles(#[case] input: &str, #[case] expected: &str) {
assert_eq!(url_encode(input), expected);
}
#[test]
fn loader_from_fabric_deps() {
let mut deps = HashMap::new();
+113 -71
View File
@@ -76,7 +76,7 @@ pub struct Download {
pub struct Library {
pub name: String,
pub downloads: LibraryDownloads,
pub rules: Option<Vec<Rule>>,
pub rules: Option<Vec<crate::launch_profile::rules::Rule>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -92,17 +92,6 @@ pub struct Artifact {
pub size: u64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Rule {
pub action: String,
pub os: Option<OsRule>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OsRule {
pub name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JavaVersion {
@@ -121,14 +110,41 @@ pub struct AssetObject {
}
pub async fn fetch_version_manifest(client: &HttpClient) -> Result<VersionManifest, NetError> {
client.get_json(MANIFEST_URL).await
fetch_version_manifest_from(client, MANIFEST_URL).await
}
pub async fn fetch_version_meta(
// same as fetch_version_manifest but lets the caller pick the URL. exists so
// integration tests can point at a wiremock server; production callers go
// through fetch_version_manifest with the upstream Mojang URL.
pub async fn fetch_version_manifest_from(
client: &HttpClient,
url: &str,
) -> Result<VersionManifest, NetError> {
tracing::debug!("Fetching Mojang version manifest from {}", url);
let manifest: VersionManifest = client.get_json(url).await?;
tracing::debug!(
"Fetched Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
Ok(manifest)
}
// fetches and parses a version's metadata. also returns the raw response
// bytes so the caller can write the upstream JSON byte-for-byte to disk
// - used by the install path so we don't lose data (e.g. arguments.jvm)
// by re-serializing through our narrow VersionMeta struct.
pub async fn fetch_version_meta_with_raw(
client: &HttpClient,
entry: &VersionEntry,
) -> Result<VersionMeta, NetError> {
client.get_json(&entry.url).await
) -> Result<(VersionMeta, Vec<u8>), NetError> {
tracing::debug!(
"Fetching Mojang version meta '{}' from {}",
entry.id,
entry.url
);
client.get_json_with_raw(&entry.url, "version meta").await
}
pub async fn download_client_jar(
@@ -143,10 +159,16 @@ pub async fn download_client_jar(
if jar_path.exists() {
tracing::info!("Client JAR already cached: {}", meta.id);
tracing::trace!("Cached client JAR path: {}", jar_path.display());
return Ok(());
}
set_action(format!("Downloading Minecraft {}...", meta.id));
tracing::info!(
"Downloading Minecraft client JAR {} to {}",
meta.id,
jar_path.display()
);
let result = download_file(
client,
@@ -168,21 +190,45 @@ pub async fn download_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
set_action("Downloading libraries...");
tracing::debug!(
"Resolving {} libraries for Minecraft {}",
meta.libraries.len(),
meta.id
);
let features = crate::launch_profile::rules::FeatureSet::default();
let host_os_version = crate::launch_profile::system::mojang_os_version();
let rule_ctx = crate::launch_profile::rules::RuleContext {
os_name: crate::launch_profile::system::mojang_os_name(),
os_version: &host_os_version,
arch: crate::launch_profile::system::mojang_arch_name(),
features: &features,
};
let mut downloads = Vec::new();
for library in &meta.libraries {
if !library_allowed_for_current_os(library) {
if let Some(rules) = &library.rules
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
{
tracing::trace!("Skipping library {} due to platform rules", library.name);
continue;
}
let artifact = match &library.downloads.artifact {
Some(artifact) => artifact,
None => continue,
None => {
tracing::trace!(
"Skipping library {} without artifact download",
library.name
);
continue;
}
};
let destination = meta_dir.join("libraries").join(&artifact.path);
if destination.exists() {
tracing::trace!("Library already cached: {}", artifact.path);
continue;
}
@@ -195,6 +241,7 @@ pub async fn download_libraries(
return Ok(());
}
tracing::debug!("Downloading {} missing libraries", downloads.len());
let result = run_parallel_downloads(client, downloads, false).await;
clear();
result
@@ -204,8 +251,24 @@ pub async fn download_assets(
client: &HttpClient,
meta: &VersionMeta,
meta_dir: &Path,
) -> Result<(), NetError> {
download_assets_from(client, meta, meta_dir, ASSETS_BASE_URL).await
}
// same as download_assets but lets tests point at a wiremock server for the
// per-asset CDN downloads. the asset index URL still comes from meta.
pub async fn download_assets_from(
client: &HttpClient,
meta: &VersionMeta,
meta_dir: &Path,
assets_base: &str,
) -> Result<(), NetError> {
set_action("Downloading assets...");
tracing::debug!(
"Fetching asset index {} from {}",
meta.asset_index.id,
meta.asset_index.url
);
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
Ok(index) => index,
@@ -226,19 +289,25 @@ pub async fn download_assets(
match tokio::fs::create_dir_all(parent).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create asset index dir: {}", e);
tracing::debug!("Failed to create asset index dir: {}", e);
}
}
}
match tokio::fs::write(&index_path, json).await {
Ok(_) => {}
Ok(_) => {
tracing::debug!("Saved asset index to {}", index_path.display());
}
Err(e) => {
tracing::error!("Failed to write asset index: {}", e);
tracing::debug!(
"Failed to write asset index {}: {}",
index_path.display(),
e
);
}
}
}
Err(e) => {
tracing::error!("Failed to serialize asset index: {}", e);
tracing::debug!("Failed to serialize asset index: {}", e);
}
}
}
@@ -256,7 +325,7 @@ pub async fn download_assets(
}
let prefix = &object.hash[..2];
let url = format!("{}/{}/{}", ASSETS_BASE_URL, prefix, object.hash);
let url = format!("{}/{}/{}", assets_base, prefix, object.hash);
let destination = meta_dir
.join("assets")
.join("objects")
@@ -276,56 +345,16 @@ pub async fn download_assets(
return Ok(());
}
tracing::debug!(
"Downloading {} missing asset(s) from index {}",
downloads.len(),
meta.asset_index.id
);
let result = run_parallel_downloads(client, downloads, true).await;
clear();
result
}
// mojang's rule system is a bit quirky: no rules means "allow everywhere",
// and rules are evaluated in order where the last matching rule wins.
// a "disallow" for the current OS is an immediate reject though.
fn library_allowed_for_current_os(library: &Library) -> bool {
let rules = match &library.rules {
Some(rules) => rules,
None => return true,
};
let current_os = mojang_os_name();
let mut allowed = false;
for rule in rules {
let matches_os = match &rule.os {
Some(os_rule) => match &os_rule.name {
Some(name) => name == current_os,
None => true,
},
None => true,
};
if !matches_os {
continue;
}
if rule.action == "disallow" {
return false;
}
if rule.action == "allow" {
allowed = true;
}
}
allowed
}
// mojang calls macOS "osx" because apparently it's still 2012
fn mojang_os_name() -> &'static str {
match std::env::consts::OS {
"macos" => "osx",
other => other,
}
}
// bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks
// and feeds new ones in as each completes. collects errors but keeps going
// so it downloads as much as possible before reporting the first failure.
@@ -335,6 +364,11 @@ async fn run_parallel_downloads(
report_count_progress: bool,
) -> Result<(), NetError> {
let total_downloads = downloads.len() as u64;
tracing::debug!(
"Starting {} parallel download job(s), max_concurrent={}",
total_downloads,
MAX_CONCURRENT_DOWNLOADS
);
let completed = Arc::new(AtomicU64::new(0));
let mut queue = downloads.into_iter();
let mut set = JoinSet::new();
@@ -360,13 +394,13 @@ async fn run_parallel_downloads(
set_sub_action(label);
}
Ok(Err(e)) => {
tracing::error!("Download failed: {}", e);
tracing::debug!("Download failed: {}", e);
if first_error.is_none() {
first_error = Some(e);
}
}
Err(e) => {
tracing::error!("Task panicked: {}", e);
tracing::debug!("Task panicked: {}", e);
if first_error.is_none() {
first_error = Some(NetError::TaskFailed(format!("Join error: {}", e)));
}
@@ -396,8 +430,16 @@ fn spawn_download_task(
let task_client = client.clone();
set.spawn(async move {
tracing::trace!(
"Starting parallel download '{}' to {}",
label,
destination.display()
);
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
result.map(|()| label)
result.map(|()| {
tracing::trace!("Finished parallel download '{}'", label);
label
})
});
}
+96 -19
View File
@@ -8,6 +8,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::InstallerError;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
@@ -20,8 +21,10 @@ struct NeoForgeMavenVersions {
versions: Vec<String>,
}
// neoforge dropped the "1." from minecraft versions in their scheme,
// so "1.20.4" becomes prefix "20.4." and "1.21" becomes "21.0."
// neoforge historically dropped the "1." from minecraft versions in
// their scheme, so "1.20.4" becomes prefix "20.4." and "1.21" becomes
// "21.0.". newer minecraft versions such as "26.1.2" keep their full
// version at the start of the neoforge coordinate: "26.1.2.76".
fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
let parts: Vec<&str> = game_version.split('.').collect();
match parts.as_slice() {
@@ -29,13 +32,57 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
["1", minor] => Some(format!("{}.0.", minor)),
// "1.20.4" → prefix "20.4."
["1", minor, patch] => Some(format!("{}.{}.", minor, patch)),
// "26.1.2" → prefix "26.1.2."
[major, minor, patch] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}.{patch}."))
}
// "26.1" → prefix "26.1."
[major, minor] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}."))
}
_ => None,
}
}
fn leading_u32(raw: &str) -> Option<u32> {
let digits: String = raw.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.is_empty() {
None
} else {
digits.parse().ok()
}
}
fn neoforge_version_to_game_version(version: &str) -> Option<String> {
let parts: Vec<&str> = version.split('.').collect();
let major = leading_u32(parts.first()?)?;
if major >= 26 {
let minor = leading_u32(parts.get(1)?)?;
let patch = leading_u32(parts.get(2)?)?;
return Some(format!("{major}.{minor}.{patch}"));
}
let minor = leading_u32(parts.get(1)?)?;
Some(if minor == 0 {
format!("1.{major}")
} else {
format!("1.{major}.{minor}")
})
}
pub async fn fetch_neoforge_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
fetch_neoforge_versions_from(client, NEOFORGE_API_BASE, game_version).await
}
// same as fetch_neoforge_versions but lets tests point at a wiremock server.
pub async fn fetch_neoforge_versions_from(
client: &HttpClient,
api_url: &str,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let prefix = match game_version_to_neoforge_prefix(game_version) {
Some(p) => p,
@@ -47,7 +94,7 @@ pub async fn fetch_neoforge_versions(
}
};
let maven_versions: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
let maven_versions: NeoForgeMavenVersions = client.get_json(api_url).await?;
let versions: Vec<String> = maven_versions
.versions
@@ -55,6 +102,12 @@ pub async fn fetch_neoforge_versions(
.filter(|v| v.starts_with(&prefix) && !v.contains("-beta") && !v.contains("-alpha"))
.collect();
tracing::debug!(
"Resolved {} NeoForge version(s) for Minecraft {} with prefix {}",
versions.len(),
game_version,
prefix
);
Ok(versions)
}
@@ -63,26 +116,25 @@ pub async fn fetch_neoforge_versions(
pub async fn fetch_neoforge_game_versions(
client: &HttpClient,
) -> Result<Vec<GameVersion>, NetError> {
let maven: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
fetch_neoforge_game_versions_from(client, NEOFORGE_API_BASE).await
}
pub async fn fetch_neoforge_game_versions_from(
client: &HttpClient,
api_url: &str,
) -> Result<Vec<GameVersion>, NetError> {
let maven: NeoForgeMavenVersions = client.get_json(api_url).await?;
let mut game_versions: Vec<String> = Vec::new();
for version in &maven.versions {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() >= 2
&& let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>())
if let Some(mc_version) = neoforge_version_to_game_version(version)
&& !game_versions.contains(&mc_version)
{
let mc_version = if minor == 0 {
format!("1.{}", major)
} else {
format!("1.{}.{}", major, minor)
};
if !game_versions.contains(&mc_version) {
game_versions.push(mc_version);
}
game_versions.push(mc_version);
}
}
game_versions.reverse();
tracing::debug!("Resolved {} NeoForge game version(s)", game_versions.len());
Ok(game_versions
.into_iter()
@@ -104,6 +156,11 @@ pub async fn download_neoforge_installer(
);
set_action(format!("Downloading NeoForge {}...", neoforge_version));
tracing::info!(
"Downloading NeoForge installer {} to {}",
neoforge_version,
dest.display()
);
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
@@ -115,12 +172,13 @@ pub async fn run_neoforge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running NeoForge installer...");
let output = match Command::new(java_path)
.arg(format!("-Duser.home={}", instance_dir.display()))
.arg("-jar")
.arg(installer_path)
.arg("--installClient")
@@ -130,17 +188,32 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn NeoForge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
if !output.status.success() {
return Err(NetError::InstallerFailed(format!(
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("").trim();
tracing::debug!(
"NeoForge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
}
tracing::debug!("NeoForge installer completed successfully");
Ok(())
}
@@ -191,6 +264,10 @@ mod tests {
game_version_to_neoforge_prefix("1.21.1"),
Some("21.1.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("26.1.2"),
Some("26.1.2.".to_string())
);
assert_eq!(game_version_to_neoforge_prefix("invalid"), None);
}
}
+81 -4
View File
@@ -42,8 +42,19 @@ pub struct QuiltLibrary {
}
pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", QUILT_META_BASE);
fetch_quilt_game_versions_from(client, QUILT_META_BASE).await
}
// same as fetch_quilt_game_versions but lets tests point at a wiremock
// server. quilt mirrors the fabric API shape.
pub async fn fetch_quilt_game_versions_from(
client: &HttpClient,
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Quilt game versions from {}", url);
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Quilt game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -58,28 +69,92 @@ pub async fn fetch_quilt_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version);
client.get_json(&url).await
fetch_quilt_versions_from(client, QUILT_META_BASE, game_version).await
}
pub async fn fetch_quilt_versions_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
tracing::debug!("Fetching Quilt loader versions for {}", game_version);
let versions: Vec<QuiltLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_quilt_profile(
client: &HttpClient,
game_version: &str,
loader_version: &str,
) -> Result<QuiltProfile, NetError> {
fetch_quilt_profile_from(client, QUILT_META_BASE, game_version, loader_version).await
}
pub async fn fetch_quilt_profile_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
loader_version: &str,
) -> Result<QuiltProfile, NetError> {
let url = format!(
"{}/versions/loader/{}/{}/profile/json",
QUILT_META_BASE, game_version, loader_version
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
// like fetch_quilt_profile but also returns the raw response bytes so the
// caller can write the upstream JSON byte-for-byte to disk. used by the
// install path so we don't lose data (e.g. any future arguments field) by
// re-serializing through our narrow QuiltProfile struct.
pub async fn fetch_quilt_profile_with_raw(
client: &HttpClient,
game_version: &str,
loader_version: &str,
) -> Result<(QuiltProfile, Vec<u8>), NetError> {
fetch_quilt_profile_with_raw_from(client, QUILT_META_BASE, game_version, loader_version).await
}
pub async fn fetch_quilt_profile_with_raw_from(
client: &HttpClient,
meta_base: &str,
game_version: &str,
loader_version: &str,
) -> Result<(QuiltProfile, Vec<u8>), NetError> {
let url = format!(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Quilt profile").await
}
pub async fn download_quilt_libraries(
client: &HttpClient,
profile: &QuiltProfile,
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Quilt libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -104,10 +179,12 @@ pub async fn download_quilt_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Quilt library: {}", lib.name);
tracing::trace!("Quilt library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Quilt library resolution complete for {}", profile.id);
Ok(())
}
+9 -6
View File
@@ -33,12 +33,14 @@ pub static KILL_SENDERS: LazyLock<KillSenders> =
pub fn set_state(name: &str, state: RunState) {
if let Ok(mut map) = RUNNING.lock() {
map.insert(name.to_string(), state);
crate::tui::request_redraw();
}
}
pub fn remove(name: &str) {
if let Ok(mut map) = RUNNING.lock() {
map.remove(name);
crate::tui::request_redraw();
}
}
@@ -59,6 +61,7 @@ pub fn all() -> Vec<(String, RunState)> {
pub fn push_last_played(name: &str, time: DateTime<Utc>) {
if let Ok(mut q) = PENDING_LAST_PLAYED.lock() {
q.push((name.to_string(), time));
crate::tui::request_redraw();
}
}
@@ -142,12 +145,12 @@ mod tests {
assert!(drained.iter().any(|(k, _)| k == "run_test_lp"));
}
#[test]
fn drain_empty_returns_empty() {
let _ = drain_last_played();
let drained = drain_last_played();
assert!(drained.is_empty());
}
// Removed drain_empty_returns_empty: it relied on no other test pushing
// to LAST_PLAYED between the two drain calls, which races with the
// parallel push_and_drain_last_played test. The drain semantics are
// already covered by push_and_drain_last_played, which asserts a
// specific entry is present, and the empty-result path is exercised
// implicitly any time drain runs after that test's cleanup.
#[test]
fn send_kill_returns_false_for_missing() {
+2
View File
@@ -29,6 +29,7 @@ pub struct App {
pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState,
pub(super) logs_state: widgets::logs_viewer::LogsState,
pub(super) account_state: widgets::account::AccountState,
pub(super) settings_state: widgets::settings::SettingsState,
pub(super) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
@@ -87,6 +88,7 @@ impl App {
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
+65 -33
View File
@@ -32,10 +32,13 @@ pub fn push_error(event: ErrorEvent) {
Ok(mut events) => {
let mut event = event;
event.id = NEXT_ERROR_ID.fetch_add(1, Ordering::Relaxed);
events.push_back(event);
while events.len() > MAX_ERROR_EVENTS {
events.pop_front();
}
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Error buffer lock poisoned: {}", e);
@@ -54,7 +57,13 @@ pub fn has_errors() -> bool {
#[must_use]
pub fn pop_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(mut events) => events.pop_front(),
Ok(mut events) => {
let event = events.pop_front();
if event.is_some() {
crate::tui::request_redraw();
}
event
}
Err(_) => None,
}
}
@@ -79,6 +88,13 @@ pub fn peek_all_errors() -> Vec<ErrorEvent> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
static TEST_LOCK: Mutex<()> = Mutex::new(());
fn clear_errors_for_test() {
ERROR_EVENTS.lock().unwrap().clear();
}
fn make_event(msg: &str) -> ErrorEvent {
ErrorEvent {
@@ -89,57 +105,73 @@ mod tests {
}
}
#[test]
fn push_and_pop_fifo() {
push_error(make_event("err_fifo_1"));
push_error(make_event("err_fifo_2"));
let first = pop_error();
assert!(first.is_some() || has_errors());
}
#[test]
fn has_errors_after_push() {
push_error(make_event("err_has"));
assert!(has_errors());
}
#[test]
fn peek_does_not_remove() {
push_error(make_event("err_peek"));
let before = peek_error();
assert!(before.is_some());
assert!(has_errors());
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
push_error(make_event("peek-test"));
let count_before = peek_all_errors().len();
let peeked = peek_error();
let count_after = peek_all_errors().len();
assert_eq!(
count_before, count_after,
"peek should not change queue length"
);
assert!(peeked.is_some());
assert_eq!(peeked.unwrap().message, "peek-test");
}
#[test]
fn peek_all_returns_newest_first() {
push_error(make_event("err_all_a"));
push_error(make_event("err_all_b"));
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
push_error(make_event("newest_a"));
push_error(make_event("newest_b"));
let all = peek_all_errors();
assert!(all.len() >= 2);
if all.len() >= 2 {
assert!(all[0].id >= all[1].id);
}
assert_eq!(all.len(), 2);
assert!(all[0].message.ends_with("_b"));
assert!(all[1].message.ends_with("_a"));
assert!(all[0].id > all[1].id);
}
#[test]
fn auto_assigned_ids_are_unique() {
push_error(make_event("err_id_1"));
push_error(make_event("err_id_2"));
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
push_error(make_event("unique_1"));
push_error(make_event("unique_2"));
let all = peek_all_errors();
if all.len() >= 2 {
let ids: Vec<u64> = all.iter().map(|e| e.id).collect();
let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
assert_eq!(ids.len(), unique.len());
}
assert_eq!(all.len(), 2);
assert_ne!(all[0].id, all[1].id);
}
#[test]
fn overflow_drops_oldest() {
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
for i in 0..(MAX_ERROR_EVENTS + 10) {
push_error(make_event(&format!("overflow_{i}")));
}
let all = peek_all_errors();
assert!(all.len() <= MAX_ERROR_EVENTS);
assert_eq!(all.len(), MAX_ERROR_EVENTS);
assert!(!all.iter().any(|e| e.message == "overflow_0"));
assert!(!all.iter().any(|e| e.message == "overflow_9"));
assert!(all.iter().any(|e| e.message == "overflow_10"));
assert!(all.iter().any(|e| e.message == "overflow_59"));
}
}
+43 -16
View File
@@ -11,9 +11,13 @@ use crate::tui::error_buffer;
use crate::tui::progress;
impl App {
/// main loop: drain async results, render, handle input, repeat at ~60fps
/// main loop: poll async results and input at ~60Hz, drawing only when state changes
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
let mut last_draw = std::time::Instant::now()
.checked_sub(Duration::from_secs(1))
.unwrap_or_else(std::time::Instant::now);
while !self.exit {
let redraw_requested = super::take_redraw_request();
// check if any popup wizard finished and wants to create/import
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
@@ -32,12 +36,20 @@ impl App {
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.mods_state.drain_watcher();
self.mods_state.request_image_loads(&self.picker);
self.mods_state.drain_image_loads(&self.picker);
self.resource_packs_state.drain_pending();
self.resource_packs_state.drain_watcher();
self.resource_packs_state.request_image_loads(&self.picker);
self.resource_packs_state.drain_image_loads(&self.picker);
self.shaders_state.drain_pending();
self.shaders_state.drain_watcher();
self.shaders_state.request_image_loads(&self.picker);
self.shaders_state.drain_image_loads(&self.picker);
self.worlds_state.drain_pending();
self.worlds_state.drain_watcher();
self.worlds_state.request_image_loads(&self.picker);
self.worlds_state.drain_image_loads(&self.picker);
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
@@ -45,14 +57,26 @@ impl App {
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
let progress_active = progress::is_active();
if progress_active {
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
let input_changed = self.handle_events().wrap_err("handle events failed")?;
let continuously_animated = progress_active || error_buffer::has_errors();
let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1);
if input_changed
|| continuously_animated
|| safety_refresh
|| redraw_requested
{
terminal.draw(|frame| self.render_frame(frame))?;
last_draw = std::time::Instant::now();
}
if let Some(path) = self.pending_editor.take()
&& Self::run_editor(terminal, &path)
@@ -65,22 +89,24 @@ impl App {
// polls for input with a 16ms timeout (~60fps). only key presses are handled,
// releases and repeats are ignored thanks to the enhanced keyboard protocol
fn handle_events(&mut self) -> color_eyre::Result<()> {
fn handle_events(&mut self) -> color_eyre::Result<bool> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => self
.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")),
Ok(_) => Ok(()),
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => {
self.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}"))?;
Ok(true)
}
Ok(_) => Ok(true),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
Ok(false)
}
},
Ok(false) => Ok(()),
Ok(false) => Ok(false),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
Ok(false)
}
}
}
@@ -107,6 +133,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
@@ -133,6 +160,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
@@ -254,7 +282,6 @@ impl App {
let instance = match self.instance_manager.load_one(&instance.name) {
Ok(config) => config,
Err(e) => {
tracing::error!("Failed to load instance '{}': {}", instance.name, e);
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
+207 -31
View File
@@ -70,24 +70,69 @@ impl App {
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
let focus_after = match confirm_popup::pending_target() {
Some(confirm_popup::ConfirmTarget::Instance { name }) => {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
FocusedArea::Instances
}
}
Some(confirm_popup::ConfirmTarget::Account { index, .. }) => {
let count = self.account_state.store.accounts.len();
self.account_state.store.remove(index);
if count > 1 {
self.account_state.list_state.selected = Some(index.min(
self.account_state.store.accounts.len().saturating_sub(1),
));
} else {
self.account_state.list_state.selected = None;
}
FocusedArea::Account
}
Some(confirm_popup::ConfirmTarget::ConfigProfile { profile }) => {
if let Err(e) = self.delete_config_profile(&profile) {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
FocusedArea::Settings
}
Some(confirm_popup::ConfirmTarget::Content { name, path }) => {
match delete_content_path(&path) {
Ok(()) => {
self.remove_content_path_from_states(&path);
}
Err(e) => {
tracing::error!("Failed to delete content '{}': {}", name, e);
}
}
FocusedArea::Content
}
None => FocusedArea::Instances,
};
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
self.focused = focus_after;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
let focus_after = match confirm_popup::pending_target() {
Some(confirm_popup::ConfirmTarget::Content { .. }) => FocusedArea::Content,
Some(confirm_popup::ConfirmTarget::Account { .. }) => FocusedArea::Account,
Some(confirm_popup::ConfirmTarget::ConfigProfile { .. }) => {
FocusedArea::Settings
}
_ => FocusedArea::Instances,
};
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
self.focused = focus_after;
return Ok(());
}
_ => {
@@ -97,17 +142,41 @@ impl App {
}
// content area delegates to whichever tab is active.
// worlds get handle_key_no_toggle because you can't "disable" a world like you can a mod
// worlds use the same list navigation without the toggle
if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if key_event.code == KeyCode::Char('d')
&& !self.logs_state.search.active
&& !self.logs_state.viewer_search.active
{
if let Some(pending) = self.logs_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if key_event.code == KeyCode::Char('d') && !self.screenshots_state.search.active {
if let Some(pending) = self.screenshots_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if key_event.code == KeyCode::Char('d') && !self.worlds_state.search.active {
if let Some(pending) = self.worlds_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
{
return Ok(());
@@ -121,14 +190,34 @@ impl App {
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state
&& widgets::content::list::handle_key(&key_event, state)
{
return Ok(());
if let Some(state) = state {
if key_event.code == KeyCode::Char('d') && !state.search.active {
if let Some(pending) = state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& let KeyCode::Char('d') = key_event.code
&& let Some(index) = self.account_state.list_state.selected
&& let Some(account) = self.account_state.store.accounts.get(index)
{
confirm_popup::set_pending(confirm_popup::ConfirmTarget::Account {
username: account.username.clone(),
index,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state)
{
@@ -138,6 +227,7 @@ impl App {
if self.focused == FocusedArea::Settings {
match widgets::settings::handle_key(
&key_event,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
@@ -173,6 +263,53 @@ impl App {
}
return Ok(());
}
widgets::settings::SettingsAction::SelectProfile(profile) => {
if let Some(inst) = self.instances_state.selected_instance().cloned() {
let instance_dir = self.instance_manager.instances_dir.join(&inst.name);
match crate::instance::config_sync::switch_profile(
&inst.name,
inst.config_sync_profile.as_deref(),
profile.as_deref(),
&self.instance_manager.meta_dir,
&instance_dir,
) {
Ok(selected) => {
let mut updated = inst.clone();
updated.config_sync_profile = selected;
if let Err(e) = self.instance_manager.save(&updated) {
tracing::error!("Failed to save config profile: {}", e);
} else {
self.instances_state.replace_instance(&inst.name, updated);
}
}
Err(e) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
}
}
return Ok(());
}
widgets::settings::SettingsAction::ConfirmDeleteProfile(profile) => {
confirm_popup::set_pending(confirm_popup::ConfirmTarget::ConfigProfile {
profile,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
widgets::settings::SettingsAction::Error(message) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message,
pushed_at: std::time::Instant::now(),
});
return Ok(());
}
widgets::settings::SettingsAction::None => {}
}
}
@@ -192,20 +329,14 @@ impl App {
let new_name = self.instances_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.instances_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
if let Ok(()) = self.instance_manager.rename(&old_name, &new_name)
&& let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
}
}
@@ -259,7 +390,7 @@ impl App {
{
if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
confirm_popup::set_pending_instance_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
@@ -345,4 +476,49 @@ impl App {
Ok(())
}
fn delete_config_profile(&mut self, profile: &str) -> color_eyre::Result<()> {
let instances = self.instance_manager.load_all();
for instance in instances
.into_iter()
.filter(|instance| instance.config_sync_profile.as_deref() == Some(profile))
{
let instance_dir = self.instance_manager.instances_dir.join(&instance.name);
let mut updated = instance.clone();
updated.config_sync_profile = crate::instance::config_sync::switch_profile(
&instance.name,
instance.config_sync_profile.as_deref(),
None,
&self.instance_manager.meta_dir,
&instance_dir,
)?;
self.instance_manager.save(&updated)?;
self.instances_state
.replace_instance(&instance.name, updated);
}
crate::instance::config_sync::delete_profile(&self.instance_manager.meta_dir, profile)?;
self.settings_state
.profiles
.retain(|candidate| candidate != profile);
Ok(())
}
fn remove_content_path_from_states(&mut self, path: &std::path::Path) {
self.mods_state.remove_path(path);
self.resource_packs_state.remove_path(path);
self.shaders_state.remove_path(path);
self.worlds_state.remove_path(path);
self.screenshots_state.remove_path(path);
self.logs_state.remove_path(path);
}
}
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => std::fs::remove_file(path),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
+59 -9
View File
@@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::{Level, Subscriber};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::filter::filter_fn;
use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, Layer};
@@ -16,6 +17,9 @@ use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
const MINECRAFT_LOG_TARGET: &str = "mc_instance";
const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace";
// capped at 5000 lines so it doesn't eat all the ram if something goes haywire
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
@@ -58,10 +62,10 @@ pub fn init() -> WorkerGuard {
let file_appender = tracing_appender::rolling::never(&log_dir, format!("rmcl_{now}.log"));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::builder()
.with_default_directive(Level::INFO.into())
.from_env_lossy()
.add_directive("mc_instance=off".parse().unwrap());
let file_filter =
EnvFilter::try_from_env("RUST_LOG").unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILE_FILTER));
let file_filter =
file_filter.add_directive(format!("{MINECRAFT_LOG_TARGET}=off").parse().unwrap());
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
@@ -83,10 +87,18 @@ pub fn init() -> WorkerGuard {
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false)
.with_filter(env_filter),
.with_filter(file_filter),
)
.with(
tui_logger::TuiTracingSubscriberLayer.with_filter(filter_fn(|metadata| {
should_record_app_log(metadata.target(), *metadata.level())
})),
)
.with(
StatusLayer::new(error_buffer::ERROR_EVENTS.clone()).with_filter(filter_fn(
|metadata| should_record_app_log(metadata.target(), *metadata.level()),
)),
)
.with(tui_logger::TuiTracingSubscriberLayer)
.with(StatusLayer::new(error_buffer::ERROR_EVENTS.clone()))
.init();
guard
@@ -119,9 +131,11 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
Level::TRACE => "TRACE",
};
let now = chrono::Local::now().format("%H:%M:%S");
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
if should_record_app_log(target, level) {
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
}
if level <= Level::WARN {
if level <= Level::WARN && should_record_app_log(target, level) {
error_buffer::push_error(ErrorEvent {
id: 0,
level,
@@ -132,6 +146,14 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
}
}
fn should_record_app_log(target: &str, level: Level) -> bool {
if target == MINECRAFT_LOG_TARGET {
return false;
}
target == "rmcl" || target.starts_with("rmcl::") || level <= Level::WARN
}
#[derive(Default)]
struct MessageVisitor {
message: String,
@@ -157,3 +179,31 @@ impl Visit for MessageVisitor {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minecraft_events_are_not_general_app_logs() {
assert!(!should_record_app_log(MINECRAFT_LOG_TARGET, Level::ERROR));
}
#[test]
fn rmcl_events_are_general_app_logs() {
assert!(should_record_app_log(
"rmcl::instance::manager",
Level::TRACE
));
}
#[test]
fn dependency_debug_events_are_not_general_app_logs() {
assert!(!should_record_app_log("log", Level::DEBUG));
}
#[test]
fn dependency_warnings_are_general_app_logs() {
assert!(should_record_app_log("notify", Level::WARN));
}
}
+32 -1
View File
@@ -9,6 +9,18 @@ pub mod progress;
mod render;
pub mod widgets;
use std::sync::atomic::{AtomicBool, Ordering};
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
pub fn request_redraw() {
REDRAW_REQUESTED.store(true, Ordering::Release);
}
pub(super) fn take_redraw_request() -> bool {
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
}
pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> {
@@ -37,8 +49,27 @@ pub async fn show() -> color_eyre::Result<()> {
// figure out the terminal's font cell size for rendering images.
// falls back to halfblock characters if the terminal doesn't respond
let picker = ratatui_image::picker::Picker::from_query_stdio()
let mut picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let detected_protocol = picker.protocol_type();
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
crate::config::settings::ImageProtocol::Halfblocks
| crate::config::settings::ImageProtocol::Quadrants => {
ratatui_image::picker::ProtocolType::Halfblocks
}
crate::config::settings::ImageProtocol::Kitty
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
{
ratatui_image::picker::ProtocolType::Kitty
}
crate::config::settings::ImageProtocol::Iterm2
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
{
ratatui_image::picker::ProtocolType::Iterm2
}
_ => ratatui_image::picker::ProtocolType::Halfblocks,
};
picker.set_protocol_type(requested_protocol);
let result = app::App::new(picker).run(&mut terminal).await;
+10
View File
@@ -19,6 +19,7 @@ pub fn set_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.current_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -31,6 +32,7 @@ pub fn set_progress(current: u64, total: u64) {
match PROGRESS.lock() {
Ok(mut state) => {
state.progress = Some((current, total));
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -43,6 +45,7 @@ pub fn set_sub_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.sub_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -57,9 +60,16 @@ pub fn clear() {
state.current_action = None;
state.progress = None;
state.sub_action = None;
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
}
}
}
pub fn is_active() -> bool {
PROGRESS
.lock()
.is_ok_and(|state| state.current_action.is_some())
}
+9 -8
View File
@@ -65,13 +65,14 @@ impl App {
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
&self.picker,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(24),
Constraint::Percentage(46),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
@@ -86,6 +87,7 @@ impl App {
frame,
bottom_chunks[1],
self.focused,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
);
@@ -123,12 +125,11 @@ impl App {
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
if self.focused == FocusedArea::ConfirmDelete
&& let Some(target) = confirm_popup::pending_target()
{
let area = confirm_popup_area(frame.area(), &target);
frame.render_widget(ConfirmPopup::for_target(&target), area);
}
}
+5 -73
View File
@@ -27,7 +27,6 @@ pub enum AddMode {
ChooseType,
OfflineNameInput(String),
OfflineBlocked,
ConfirmDelete(usize),
DeviceCodeWaiting {
info: DeviceCodeInfo,
pending: Arc<Mutex<Option<AuthResult>>>,
@@ -163,28 +162,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
}
_ => true,
},
AddMode::ConfirmDelete(idx) => {
let idx = *idx;
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let count = state.store.accounts.len();
state.store.remove(idx);
if count > 1 {
state.list_state.selected =
Some(idx.min(state.store.accounts.len().saturating_sub(1)));
} else {
state.list_state.selected = None;
}
state.add_mode = AddMode::None;
true
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
state.add_mode = AddMode::None;
true
}
_ => true,
}
}
AddMode::None => {
let count = state.store.accounts.len();
match key_event.code {
@@ -192,12 +169,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
state.add_mode = AddMode::ChooseType;
true
}
KeyCode::Char('d') => {
if let Some(idx) = state.list_state.selected {
state.add_mode = AddMode::ConfirmDelete(idx);
}
true
}
KeyCode::Enter => {
if let Some(idx) = state.list_state.selected {
state.store.set_active(idx);
@@ -276,7 +247,6 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
AddMode::ChooseType => render_choose_popup(frame),
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
AddMode::OfflineBlocked => render_offline_blocked_popup(frame),
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
AddMode::None => {}
}
@@ -310,9 +280,11 @@ fn render_account_list(
let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected;
let stripe_bg = theme.background();
let bg = stripe_bg;
let bg = if show_selected {
theme.stripe()
} else {
theme.background()
};
let active_marker = if *is_active { "\u{25b8} " } else { " " };
@@ -493,46 +465,6 @@ fn render_offline_blocked_popup(frame: &mut Frame) {
.render(area, frame.buffer_mut());
}
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let username = state
.store
.accounts
.get(idx)
.map(|a| a.username.as_str())
.unwrap_or("?");
let border_color = theme.text_dim();
let title = Line::from(Span::styled(
format!(" Delete '{}' ", username),
Style::default()
.fg(border_color)
.add_modifier(Modifier::BOLD),
));
let body = "This will permanently remove this account";
let popup_w = (username.len() + 14).max(body.len() + 2).min(48) as u16 + 2;
let area = popup_area(frame, popup_w, 3);
let bg_color = theme.surface();
let text_color = theme.text();
PopupFrame {
title,
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove this account")
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
}
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
+431 -54
View File
@@ -4,7 +4,7 @@
// also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
@@ -16,12 +16,12 @@ use ratatui::{
text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};
use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtocol};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList {
@@ -29,6 +29,18 @@ struct CachedList {
selected: Option<usize>,
}
struct PendingContentImage {
file_stem: String,
path: std::path::PathBuf,
icon_lines: Vec<Vec<IconCell>>,
image: Option<image::DynamicImage>,
}
struct DisplayMetadata {
description: String,
has_description: bool,
}
// result from the notify-triggered background diff
struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>,
@@ -42,6 +54,11 @@ pub struct ContentListState {
pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>,
pub loading: bool,
image_protocols: HashMap<String, StatefulProtocol>,
requested_images: HashSet<String>,
pending_images: Arc<Mutex<Vec<PendingContentImage>>>,
images_dirty: bool,
display_metadata: HashMap<String, DisplayMetadata>,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
@@ -56,6 +73,12 @@ pub struct ContentListState {
content_ext: Option<&'static str>,
}
#[derive(Clone, Debug)]
pub struct PendingContentDelete {
pub name: String,
pub path: std::path::PathBuf,
}
impl Default for ContentListState {
fn default() -> Self {
Self {
@@ -64,6 +87,11 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(),
loaded_for: None,
loading: false,
image_protocols: HashMap::new(),
requested_images: HashSet::new(),
pending_images: Arc::new(Mutex::new(Vec::new())),
images_dirty: true,
display_metadata: HashMap::new(),
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
stream_rx: None,
@@ -77,6 +105,108 @@ impl Default for ContentListState {
}
impl ContentListState {
pub fn request_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
if !self.images_dirty {
return;
}
self.images_dirty = false;
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let use_quadrants = crate::config::SETTINGS.ui.image_protocol
== crate::config::settings::ImageProtocol::Quadrants;
if !use_image_protocol {
self.image_protocols.clear();
}
let valid_stems: HashSet<&str> = self
.entries
.iter()
.map(|entry| entry.file_stem.as_str())
.collect();
self.image_protocols
.retain(|stem, _| valid_stems.contains(stem.as_str()));
self.requested_images
.retain(|stem| valid_stems.contains(stem.as_str()));
let font_size = picker.font_size();
for entry in &self.entries {
if entry.icon_bytes.is_none()
|| !self.requested_images.insert(entry.file_stem.clone())
{
continue;
}
let file_stem = entry.file_stem.clone();
let path = entry.path.clone();
let bytes = entry.icon_bytes.clone().unwrap_or_default();
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u32;
let columns = square_icon_columns(rows as u16, font_size);
let pending = self.pending_images.clone();
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let image = image::load_from_memory(&bytes).ok()?;
let icon_lines = if use_quadrants {
crate::instance::content::mods::make_icon_quadrants_from_image(
&image,
columns,
rows as u16,
)
} else {
crate::instance::content::mods::make_icon_pixels_from_image(
&image,
columns,
rows as u16,
)
};
let side = rows * u32::from(font_size.1.max(1));
let image = use_image_protocol.then(|| {
image.resize_exact(side, side, image::imageops::FilterType::Lanczos3)
});
Some(PendingContentImage {
file_stem,
path,
icon_lines,
image,
})
})
.await
.ok()
.flatten();
if let Some(result) = result
&& let Ok(mut pending) = pending.lock()
{
pending.push(result);
crate::tui::request_redraw();
}
});
}
}
pub fn drain_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
let images = match self.pending_images.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => return,
};
for result in images {
if let Some(entry) = self
.entries
.iter_mut()
.find(|entry| {
entry.file_stem == result.file_stem && entry.path == result.path
})
{
entry.icon_lines = Some(result.icon_lines);
if let Some(image) = result.image {
self.image_protocols
.insert(result.file_stem, picker.new_resize_protocol(image));
}
}
}
}
// drain streaming entries from the initial load. each entry arrives
// individually and is inserted in sorted position for a smooth fill-in
pub fn drain_pending(&mut self) {
@@ -85,16 +215,19 @@ impl ContentListState {
};
let mut received = false;
let mut received_count = 0usize;
let mut finished = false;
loop {
match rx.try_recv() {
Ok(entry) => {
received = true;
self.images_dirty = true;
received_count += 1;
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| {
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
})
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
@@ -109,6 +242,20 @@ impl ContentListState {
if received || finished {
self.loading = false;
if received_count > 0 {
tracing::trace!(
"Drained {} streamed content entries for {}",
received_count,
self.loaded_for.as_deref().unwrap_or("<unknown>")
);
}
if finished {
tracing::debug!(
"Finished content scan for {} with {} entries",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
self.entries.len()
);
}
if self.list_state.selected.is_none() && !self.entries.is_empty() {
self.list_state.selected = Some(0);
}
@@ -131,8 +278,16 @@ impl ContentListState {
let Some(diff) = diff else {
return;
};
self.images_dirty = true;
// apply toggles (enabled/path changes)
tracing::debug!(
"Applying content watcher diff for {}: toggled={} removed={} added={}",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
diff.toggled.len(),
diff.removed.len(),
diff.added.len()
);
for (stem, enabled, path) in &diff.toggled {
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
entry.enabled = *enabled;
@@ -144,10 +299,15 @@ impl ContentListState {
if !diff.removed.is_empty() {
self.entries
.retain(|e| !diff.removed.contains(&e.file_stem));
for stem in &diff.removed {
self.display_metadata.remove(stem);
}
}
// insert new entries in sorted position
for entry in diff.added {
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -160,8 +320,7 @@ impl ContentListState {
if self.entries.is_empty() {
self.list_state.selected = None;
} else {
self.list_state.selected =
Some(sel.min(self.entries.len().saturating_sub(1)));
self.list_state.selected = Some(sel.min(self.entries.len().saturating_sub(1)));
}
}
@@ -192,7 +351,12 @@ impl ContentListState {
let watch_dir = dir.clone();
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
if res.is_err() {
if let Err(e) = &res {
tracing::warn!(
"Content watcher event error for {}: {}",
watch_dir.display(),
e
);
return;
}
@@ -235,11 +399,7 @@ impl ContentListState {
for (stem, (old_path, old_enabled)) in known_map.iter() {
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
if *disk_enabled != *old_enabled || *disk_path != *old_path {
toggled.push((
stem.clone(),
*disk_enabled,
disk_path.clone(),
));
toggled.push((stem.clone(), *disk_enabled, disk_path.clone()));
}
} else {
removed.push(stem.clone());
@@ -267,6 +427,7 @@ impl ContentListState {
&& let Ok(mut slot) = diff_slot.lock()
{
*slot = Some(diff);
crate::tui::request_redraw();
}
if !dirty.load(Ordering::Relaxed) {
@@ -281,6 +442,7 @@ impl ContentListState {
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
tracing::warn!("Failed to watch {}: {e}", dir.display());
} else {
tracing::debug!("Watching content directory {}", dir.display());
self._watcher = Some(w);
}
}
@@ -300,6 +462,16 @@ impl ContentListState {
.map(|(i, _)| i)
.collect()
}
pub fn pending_delete(&self) -> Option<PendingContentDelete> {
let filtered = self.filtered_indices();
let real_idx = self.list_state.selected.and_then(|i| filtered.get(i))?;
let entry = self.entries.get(*real_idx)?;
Some(PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
}
impl ContentListState {
@@ -315,11 +487,19 @@ impl ContentListState {
) {
self.scan_one_fn = Some(scan_one_fn);
self.content_ext = Some(ext);
self.images_dirty = true;
self.image_protocols.clear();
self.requested_images.clear();
// save current entries to cache
if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty()
{
tracing::trace!(
"Caching {} content entries for {}",
self.entries.len(),
prev
);
self.cache.insert(
prev,
CachedList {
@@ -332,16 +512,23 @@ impl ContentListState {
// try cache first
if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries;
self.rebuild_display_metadata();
self.list_state.selected = cached.selected;
self.loading = false;
self.stream_rx = None;
self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar();
tracing::debug!(
"Restored {} cached content entries for {}",
self.entries.len(),
instance_name
);
return;
}
// no cache, stream entries one by one as each file is scanned
self.entries.clear();
self.display_metadata.clear();
self.list_state = TuiListState::default();
self.loading = true;
self.loaded_for = Some(instance_name.to_string());
@@ -351,36 +538,53 @@ impl ContentListState {
self.stream_rx = Some(rx);
let dir = content_dir.to_path_buf();
tracing::debug!(
"Starting content scan for {} in {}",
instance_name,
content_dir.display()
);
tokio::spawn(async move {
let _ = tokio::task::spawn_blocking(move || {
let read_dir = match std::fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return,
Err(e) => {
tracing::warn!("Failed to read content directory {}: {}", dir.display(), e);
return;
}
};
let disabled_ext = format!("{ext}.disabled");
for dir_entry in read_dir.flatten() {
let path = dir_entry.path();
let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
tracing::trace!(
"Skipping content path with invalid filename: {}",
path.display()
);
continue;
};
let (enabled, file_stem) =
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
continue;
};
let (enabled, file_stem) = if let Some(stem) = fname.strip_suffix(&disabled_ext)
{
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
tracing::trace!(
"Skipping content path with unsupported extension: {}",
path.display()
);
continue;
};
let entry = scan_one_fn(&path, &file_stem, enabled);
if tx.send(entry).is_err() {
break; // receiver dropped (instance switched)
}
crate::tui::request_redraw();
}
})
.await;
@@ -394,6 +598,14 @@ impl ContentListState {
self.scrollbar_state = ScrollbarState::new(max).position(pos);
}
fn rebuild_display_metadata(&mut self) {
self.display_metadata = self
.entries
.iter()
.map(|entry| (entry.file_stem.clone(), display_metadata(entry)))
.collect();
}
// enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) {
@@ -429,10 +641,40 @@ impl ContentListState {
entry.path = new_path;
}
Err(e) => {
tracing::error!("Failed to toggle '{}': {}", entry.file_stem, e);
tracing::error!(
"Failed to toggle '{}' from {} to {}: {}",
entry.file_stem,
entry.path.display(),
new_path.display(),
e
);
}
}
}
pub fn remove_path(&mut self, path: &Path) {
let file_stem = self
.entries
.iter()
.find(|entry| entry.path == path)
.map(|entry| entry.file_stem.clone());
self.entries.retain(|entry| entry.path != path);
if let Some(file_stem) = file_stem {
self.image_protocols.remove(&file_stem);
self.requested_images.remove(&file_stem);
self.display_metadata.remove(&file_stem);
}
self.images_dirty = true;
if let Some(sel) = self.list_state.selected {
let visible_count = self.filtered_indices().len();
if visible_count == 0 {
self.list_state.selected = None;
} else {
self.list_state.selected = Some(sel.min(visible_count.saturating_sub(1)));
}
}
self.update_scrollbar();
}
}
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
@@ -477,6 +719,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -512,6 +755,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -557,6 +801,7 @@ pub fn render(
is_focused: bool,
loading_text: &str,
empty_text: &str,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
if state.loading {
@@ -587,24 +832,23 @@ pub fn render(
state.list_state.selected = Some(count.saturating_sub(1));
}
let snapshot: Vec<SnapshotRow> = filtered
.iter()
.map(|&i| {
let entry = &state.entries[i];
(
entry.name.clone(),
entry.description.clone(),
entry.enabled,
entry.icon_lines.clone(),
)
})
.collect();
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let entries = &state.entries;
let display_metadata = &state.display_metadata;
let filtered_rows = &filtered;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index];
let entry = &entries[filtered_rows[context.index]];
let name = &entry.name;
let metadata = display_metadata.get(&entry.file_stem);
let enabled = entry.enabled;
let icon_pixels = &entry.icon_lines;
let has_image = entry.icon_bytes.is_some();
let protocol_columns = protocol_icon_columns(entry, picker) as usize;
let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled;
let use_mc_colors = enabled;
let stripe_bg = if context.index % 2 == 0 {
theme.background()
@@ -612,7 +856,7 @@ pub fn render(
theme.stripe()
};
let (name_style, description_style, background) = match (*enabled, show_selected) {
let (name_style, description_style, background) = match (enabled, show_selected) {
(true, true) => (
Style::default()
.fg(theme.accent())
@@ -644,9 +888,8 @@ pub fn render(
};
let has_icon = icon_pixels.is_some();
let full_desc = strip_mc_codes(description);
let stripped_desc = full_desc.lines().next().unwrap_or("").trim().to_string();
let has_description = !stripped_desc.is_empty();
let stripped_desc = metadata.map_or("", |metadata| metadata.description.as_str());
let has_description = metadata.is_some_and(|metadata| metadata.has_description);
let compact = !has_icon && !has_description;
let selector = if show_selected {
@@ -678,7 +921,12 @@ pub fn render(
};
let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0));
line_0.extend(icon_spans(
icon_pixels.as_ref(),
0,
use_image_protocol && has_image,
protocol_columns,
));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
@@ -690,16 +938,26 @@ pub fn render(
if has_description {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1));
row.extend(icon_spans(
icon_pixels.as_ref(),
1,
use_image_protocol && has_image,
protocol_columns,
));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style));
row.push(Span::styled(stripped_desc.to_string(), description_style));
lines.push(Line::from(row));
}
let desc_rows = if has_description { 1 } else { 0 };
for r in (1 + desc_rows)..icon_row_count {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), r));
row.extend(icon_spans(
icon_pixels.as_ref(),
r,
use_image_protocol && has_image,
protocol_columns,
));
lines.push(Line::from(row));
}
@@ -724,7 +982,7 @@ pub fn render(
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.clone(), description_style),
Span::styled(stripped_desc.to_string(), description_style),
]));
}
@@ -737,6 +995,10 @@ pub fn render(
let list = ListView::new(builder, count);
frame.render_stateful_widget(list, area, &mut state.list_state);
if picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks {
render_image_icons(frame, area, state, &filtered, picker);
}
let scrollbar_area = Rect {
x: area.x + area.width.saturating_sub(0),
y: area.y + 1,
@@ -760,6 +1022,76 @@ pub fn render(
);
}
fn render_image_icons(
frame: &mut Frame,
area: Rect,
state: &mut ContentListState,
filtered: &[usize],
picker: &ratatui_image::picker::Picker,
) {
let truncation = state.list_state.scroll_truncation();
let mut y = area.y;
let first = state.list_state.scroll_offset_index();
for (visible_index, &entry_index) in filtered.iter().enumerate().skip(first) {
let Some(entry) = state.entries.get(entry_index) else {
continue;
};
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let has_description = state
.display_metadata
.get(&entry.file_stem)
.is_some_and(|metadata| metadata.has_description);
let height = icon_rows.max(if has_description { 2 } else { 1 }) as u16;
if y >= area.y + area.height {
break;
}
let top_crop = if visible_index == first {
truncation.min(icon_rows as u16)
} else {
0
};
let visible_icon_rows = (icon_rows as u16)
.saturating_sub(top_crop)
.min(area.y + area.height - y);
if visible_icon_rows > 0
&& entry.icon_bytes.is_some()
&& let Some(protocol) = state.image_protocols.get_mut(&entry.file_stem)
{
let icon_area = Rect {
x: area.x + 1,
y,
width: protocol_icon_columns(entry, picker).min(area.width.saturating_sub(1)),
height: visible_icon_rows,
};
if icon_area.height > 0 && icon_area.width > 0 {
let clipped = top_crop > 0 || visible_icon_rows < icon_rows as u16;
let resize = if clipped {
Resize::Crop(Some(CropOptions {
clip_top: top_crop > 0,
clip_left: false,
}))
} else {
Resize::Scale(None)
};
let widget: StatefulImage<StatefulProtocol> =
StatefulImage::default().resize(resize);
frame.render_stateful_widget(widget, icon_area, protocol);
}
}
let visible_height = if visible_index == first {
height.saturating_sub(truncation)
} else {
height
};
y = y.saturating_add(visible_height);
if visible_index + 1 >= filtered.len() {
break;
}
}
}
// minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> {
@@ -849,16 +1181,33 @@ fn strip_mc_codes(text: &str) -> String {
result
}
fn display_metadata(entry: &ContentEntry) -> DisplayMetadata {
let description = strip_mc_codes(&entry.description);
let description = description.lines().next().unwrap_or("").trim().to_string();
DisplayMetadata {
has_description: !description.is_empty(),
description,
}
}
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
fn icon_spans(
icon_pixels: Option<&Vec<Vec<IconCell>>>,
row: usize,
use_image_protocol: bool,
protocol_columns: usize,
) -> Vec<Span<'static>> {
if use_image_protocol {
return vec![Span::raw(" ".repeat(protocol_columns))];
}
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
.iter()
.map(|cell| {
Span::styled(
"\u{2584}",
cell.symbol.to_string(),
Style::default()
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
@@ -875,14 +1224,25 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
}
}
fn protocol_icon_columns(
entry: &crate::instance::content::mods::ContentEntry,
picker: &ratatui_image::picker::Picker,
) -> u16 {
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u16;
square_icon_columns(rows, picker.font_size())
}
fn square_icon_columns(rows: u16, font_size: (u16, u16)) -> u16 {
let width = u32::from(font_size.0.max(1));
let height = u32::from(font_size.1.max(1));
((u32::from(rows) * height + width / 2) / width).max(1) as u16
}
// reads a content directory and builds a stem -> (path, enabled) map.
// used both by watch_dir to initialize known state and by the watcher
// thread to detect changes. when ext is empty (worlds), only directories
// are included.
fn read_dir_stems(
dir: &std::path::Path,
ext: &str,
) -> HashMap<String, (std::path::PathBuf, bool)> {
fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::path::PathBuf, bool)> {
let mut map = HashMap::new();
let Ok(read_dir) = std::fs::read_dir(dir) else {
return map;
@@ -915,3 +1275,20 @@ fn read_dir_stems(
map
}
#[cfg(test)]
mod tests {
use super::square_icon_columns;
#[test]
fn square_columns_follow_terminal_cell_ratio() {
assert_eq!(square_icon_columns(3, (8, 16)), 6);
assert_eq!(square_icon_columns(3, (8, 18)), 7);
assert_eq!(square_icon_columns(6, (8, 18)), 14);
}
#[test]
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
}
+50 -8
View File
@@ -80,6 +80,7 @@ pub fn render(
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content;
@@ -148,12 +149,14 @@ pub fn render(
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
("j/k", " navigate"),
("⏎", " toggle"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
],
ContentTab::Worlds => &[
("j/k", " navigate"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
@@ -161,6 +164,7 @@ pub fn render(
ContentTab::Screenshots => &[
("Shift+HJKL", " grid"),
("⏎", " open"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
@@ -170,6 +174,7 @@ pub fn render(
&[
("j/k", " scroll"),
("g/G", " top/bottom"),
("d", " delete"),
("Esc", " back"),
("/", " search"),
]
@@ -177,6 +182,7 @@ pub fn render(
&[
("j/k", " navigate"),
("⏎", " view"),
("d", " delete"),
("h/l", " tabs"),
("/", " search"),
]
@@ -215,8 +221,16 @@ pub fn render(
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("mods");
mods_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_mod, ".jar");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
);
mods_state.watch_dir(content_dir);
}
super::list::render(
@@ -226,6 +240,7 @@ pub fn render(
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
} else {
frame.render_widget(
@@ -238,8 +253,16 @@ pub fn render(
ContentTab::ResourcePacks => {
if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks");
resource_packs_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_resource_pack, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
);
resource_packs_state.watch_dir(content_dir);
}
super::list::render(
@@ -249,6 +272,7 @@ pub fn render(
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
} else {
frame.render_widget(
@@ -261,8 +285,16 @@ pub fn render(
ContentTab::Shaders => {
if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks");
shaders_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_shader, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
);
shaders_state.watch_dir(content_dir);
}
super::list::render(
@@ -272,6 +304,7 @@ pub fn render(
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
} else {
frame.render_widget(
@@ -322,8 +355,16 @@ pub fn render(
ContentTab::Worlds => {
if let Some(instance) = instance {
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("saves");
worlds_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_world, "");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("saves");
worlds_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_world,
"",
);
worlds_state.watch_dir(content_dir);
}
super::list::render(
@@ -333,6 +374,7 @@ pub fn render(
is_focused,
"Loading worlds...",
"No worlds saved.",
picker,
);
} else {
frame.render_widget(
+84
View File
@@ -337,3 +337,87 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
&mut state.scrollbar_state,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_last_played_none_returns_never_played() {
assert_eq!(format_last_played(None), "Never played");
}
// each #[case] picks a "seconds ago" value that lands in exactly one
// bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601,
// or "minutes" to "seconds") makes one of these cases fail.
#[rstest::rstest]
#[case::just_now(0, "Just now")]
#[case::just_now_upper(59, "Just now")]
#[case::minutes(60, "1 minutes ago")]
#[case::minutes_upper(3599, "59 minutes ago")]
#[case::hours(3600, "1 hours ago")]
#[case::hours_upper(86_399, "23 hours ago")]
#[case::days(86_400, "1 days ago")]
#[case::days_upper(2_591_999, "29 days ago")]
#[case::months(2_592_000, "1 months ago")]
#[case::months_upper(31_535_999, "12 months ago")]
#[case::over_a_year(31_536_000, "Over a year ago")]
fn format_last_played_buckets(#[case] seconds_ago: i64, #[case] expected: &str) {
let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago);
assert_eq!(format_last_played(Some(dt)), expected);
}
use crate::instance::models::{InstanceConfig, ModLoader};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
fn synthetic_instance(name: &str) -> InstanceConfig {
// last_played intentionally None so the rendered text is the
// deterministic "Never played" string. anything else would make the
// snapshot drift relative to chrono::Utc::now().
InstanceConfig {
name: name.to_string(),
game_version: "1.20.1".to_string(),
loader: ModLoader::Vanilla,
loader_version: None,
created: chrono::Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
}
}
#[test]
fn instances_list_renders_three_instances() {
let mut state = State::with_instances(vec![
synthetic_instance("Vanilla 1.20.1"),
synthetic_instance("Forge Pack"),
synthetic_instance("Fabric Test"),
]);
let backend = TestBackend::new(40, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn instances_list_renders_empty() {
let mut state = State::with_instances(vec![]);
let backend = TestBackend::new(40, 8);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
}
+89 -18
View File
@@ -17,6 +17,7 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::instance::launch::parser::LogLevel;
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -36,7 +37,7 @@ pub struct LogsState {
pub viewer_search: super::search::SearchState,
selected_path: Option<std::path::PathBuf>,
pending: PendingLogs,
rescan_counter: u8,
last_rescan: std::time::Instant,
instances_dir_cache: Option<std::path::PathBuf>,
was_live: bool,
}
@@ -58,7 +59,7 @@ impl Default for LogsState {
viewer_search: super::search::SearchState::default(),
selected_path: None,
pending: Arc::new(Mutex::new(None)),
rescan_counter: 0,
last_rescan: std::time::Instant::now(),
instances_dir_cache: None,
was_live: false,
}
@@ -76,6 +77,7 @@ impl LogsState {
self.viewer_scroll = 0;
self.viewer_focused = false;
self.selected_path = None;
self.last_rescan = std::time::Instant::now();
let dir = instances_dir.to_path_buf();
let tag = instance_name.to_string();
@@ -91,17 +93,13 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
pub fn drain_pending(&mut self) {
// when the instance stops while viewing the live log, transition
// to the on-disk log file so the viewer doesn't go blank
let live_now = self.has_live();
if self.was_live && !live_now && self.list_state.selected == Some(0) {
self.load_selected_content();
}
self.was_live = live_now;
let taken = match self.pending.lock() {
@@ -132,16 +130,25 @@ impl LogsState {
}
// periodically re-scan log files in case new ones appeared while playing.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1);
if !self.rescan_counter.is_multiple_of(120) {
if self.last_rescan.elapsed() < std::time::Duration::from_secs(2) {
return;
}
self.last_rescan = std::time::Instant::now();
let (Some(dir), Some(name)) = (&self.instances_dir_cache, &self.loaded_for) else {
return;
};
if !matches!(
crate::running::get(name),
Some(
crate::running::RunState::Authenticating
| crate::running::RunState::Starting
| crate::running::RunState::Running
)
) {
return;
}
let dir = dir.clone();
let tag = name.clone();
@@ -157,16 +164,20 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
// when an instance is running, a synthetic "Live" entry is injected at index 0
// when an instance is active or has just crashed, a synthetic "Live" entry
// is injected at index 0 so parsed live log styling is retained.
fn has_live(&self) -> bool {
let name = self.loaded_for.as_deref().unwrap_or("");
matches!(
crate::running::get(name),
Some(crate::running::RunState::Running) | Some(crate::running::RunState::Starting)
Some(crate::running::RunState::Running)
| Some(crate::running::RunState::Starting)
| Some(crate::running::RunState::Crashed(_))
)
}
@@ -229,6 +240,33 @@ impl LogsState {
self.viewer_scrollbar_state =
ScrollbarState::new(self.viewer_max_scroll).position(self.viewer_scroll);
}
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let index = self.file_index_for_selected()?;
let entry = self.entries.get(index)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
let display_count = self.display_count();
if display_count == 0 {
self.list_state.selected = None;
self.viewer_focused = false;
self.selected_path = None;
self.viewer_lines.clear();
self.viewer_scroll = 0;
} else if let Some(sel) = self.list_state.selected {
self.list_state.selected = Some(sel.min(display_count.saturating_sub(1)));
self.load_selected_content();
}
self.update_scrollbar();
}
}
pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
@@ -515,16 +553,27 @@ fn render_viewer(
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let all_lines: Vec<String> = if is_live {
let all_lines: Vec<ViewerLine> = if is_live {
let name = state.loaded_for.as_deref().unwrap_or("");
crate::instance_logs::get_all(name)
crate::instance_logs::get_entries(name)
.into_iter()
.map(|line| ViewerLine {
text: line.text,
level: Some(line.level),
})
.collect()
} else {
state.viewer_lines.clone()
state
.viewer_lines
.iter()
.cloned()
.map(|text| ViewerLine { text, level: None })
.collect()
};
let lines: Vec<&String> = all_lines
let lines: Vec<&ViewerLine> = all_lines
.iter()
.filter(|l| state.viewer_search.matches(l))
.filter(|l| state.viewer_search.matches(&l.text))
.collect();
let visible_height = area.height as usize;
@@ -548,7 +597,14 @@ fn render_viewer(
.iter()
.skip(state.viewer_scroll)
.take(visible_height)
.map(|line| search.highlight_line(line, line_level_style(line)))
.map(|line| {
search.highlight_line(
&line.text,
line.level
.map(log_level_style)
.unwrap_or_else(|| line_level_style(&line.text)),
)
})
.collect();
frame.render_widget(Paragraph::new(styled_lines), area);
@@ -576,6 +632,21 @@ fn render_viewer(
);
}
struct ViewerLine {
text: String,
level: Option<LogLevel>,
}
fn log_level_style(level: LogLevel) -> Style {
let theme = THEME.as_ref();
match level {
LogLevel::Error => Style::default().fg(theme.error()),
LogLevel::Warn => Style::default().fg(theme.warning()),
LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()),
LogLevel::Info => Style::default().fg(theme.text()),
}
}
// color-code log lines by severity so errors actually stand out
// instead of drowning in a wall of white text
fn line_level_style(line: &str) -> Style {
+1 -1
View File
@@ -9,12 +9,12 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod settings;
pub mod instances;
pub mod logs_viewer;
pub mod popups;
pub mod screenshots_grid;
pub mod search;
pub mod settings;
pub mod status;
// highlight the first character of a title with the accent color,
+82 -18
View File
@@ -1,4 +1,4 @@
// "are you sure?" popup for instance deletion. uses global state so the
// "are you sure?" popup for destructive actions. uses global state so the
// confirmation target persists across render frames.
use std::sync::LazyLock;
@@ -19,13 +19,57 @@ static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
#[derive(Debug, Default)]
struct ConfirmState {
instance_name: String,
target: Option<ConfirmTarget>,
}
pub fn set_pending_delete(name: impl Into<String>) {
#[derive(Debug, Clone)]
pub enum ConfirmTarget {
Instance {
name: String,
},
Account {
username: String,
index: usize,
},
ConfigProfile {
profile: String,
},
Content {
name: String,
path: std::path::PathBuf,
},
}
impl ConfirmTarget {
fn title(&self) -> String {
format!(" Delete '{}' ", self.name())
}
fn body(&self) -> &'static str {
match self {
ConfirmTarget::Instance { .. } => "This will permanently remove the instance",
ConfirmTarget::Account { .. } => "This will permanently remove this account",
ConfirmTarget::ConfigProfile { .. } => {
"This will permanently remove this config profile"
}
ConfirmTarget::Content { .. } => "This will permanently remove the selected item",
}
}
pub fn name(&self) -> &str {
match self {
ConfirmTarget::Instance { name } => name,
ConfirmTarget::Account { username, .. } => username,
ConfirmTarget::ConfigProfile { profile } => profile,
ConfirmTarget::Content { name, .. } => name,
}
}
}
pub fn set_pending(target: ConfirmTarget) {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name = name.into();
s.target = Some(target);
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -33,17 +77,32 @@ pub fn set_pending_delete(name: impl Into<String>) {
}
}
pub fn pending_delete_name() -> String {
pub fn set_pending_delete(name: impl Into<String>) {
set_pending(ConfirmTarget::Instance { name: name.into() });
}
pub fn set_pending_instance_delete(name: impl Into<String>) {
set_pending_delete(name);
}
pub fn set_pending_content_delete(name: impl Into<String>, path: impl Into<std::path::PathBuf>) {
set_pending(ConfirmTarget::Content {
name: name.into(),
path: path.into(),
});
}
pub fn pending_target() -> Option<ConfirmTarget> {
match CONFIRM_STATE.lock() {
Ok(s) => s.instance_name.clone(),
Err(_) => String::new(),
Ok(s) => s.target.clone(),
Err(_) => None,
}
}
pub fn clear_pending() {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name.clear();
s.target = None;
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -52,15 +111,21 @@ pub fn clear_pending() {
}
pub struct ConfirmPopup {
instance_name: String,
title: String,
body: &'static str,
}
impl ConfirmPopup {
pub fn new(instance_name: impl Into<String>) -> Self {
pub fn new(title: impl Into<String>, body: &'static str) -> Self {
Self {
instance_name: instance_name.into(),
title: title.into(),
body,
}
}
pub fn for_target(target: &ConfirmTarget) -> Self {
Self::new(target.title(), target.body())
}
}
impl Widget for ConfirmPopup {
@@ -69,7 +134,7 @@ impl Widget for ConfirmPopup {
let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
self.title,
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
@@ -86,7 +151,7 @@ impl Widget for ConfirmPopup {
keybinds: Some(kb),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance")
Paragraph::new(self.body)
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
@@ -96,15 +161,14 @@ impl Widget for ConfirmPopup {
}
}
pub fn confirm_popup_area(frame_area: Rect, name: &str) -> Rect {
pub fn confirm_popup_area(frame_area: Rect, target: &ConfirmTarget) -> Rect {
use super::word_wrap_size;
use ratatui::layout::Constraint;
const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance";
let title_w = name.len() + 12;
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let title_w = target.name().len() + 12;
let (body_w, _) = word_wrap_size(target.body(), MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(BODY, inner_w);
let (_, lines) = word_wrap_size(target.body(), inner_w);
let popup_w = ((inner_w + 2) as u16).min(frame_area.width.saturating_sub(4));
let popup_h = ((lines + 2) as u16).min(frame_area.height.saturating_sub(4));
frame_area.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
+111
View File
@@ -94,3 +94,114 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128
height: popup_h,
})
}
#[cfg(test)]
mod render_tests {
use super::*;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use std::time::Instant;
use tracing::Level;
use crate::tui::error_buffer::ErrorEvent;
fn render(event: ErrorEvent, width: u16, height: u16) -> Terminal<TestBackend> {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| {
let popup = ErrorPopup::new(event);
f.render_widget(popup, f.area());
})
.unwrap();
terminal
}
fn event(level: Level, message: &str) -> ErrorEvent {
ErrorEvent {
id: 1,
level,
message: message.to_string(),
pushed_at: Instant::now(),
}
}
#[test]
fn warn_level_renders() {
let term = render(event(Level::WARN, "Disk space low"), 40, 5);
insta::assert_snapshot!(term.backend());
}
#[test]
fn error_level_renders() {
let term = render(event(Level::ERROR, "Connection refused"), 40, 5);
insta::assert_snapshot!(term.backend());
}
// info-level events hit the catch-all `_` arm in the label match; previously
// there was no test covering it.
#[test]
fn info_level_renders() {
let term = render(event(Level::INFO, "Reloaded config"), 40, 5);
insta::assert_snapshot!(term.backend());
}
#[test]
fn long_message_wraps() {
let msg = "The Minecraft launcher could not reach the Mojang version manifest \
after three retries. Check your network connection or proxy settings.";
let term = render(event(Level::ERROR, msg), 40, 10);
insta::assert_snapshot!(term.backend());
}
#[test]
fn narrow_frame_renders() {
let term = render(event(Level::WARN, "Short message"), 18, 5);
insta::assert_snapshot!(term.backend());
}
}
#[cfg(test)]
mod area_tests {
use super::popup_area;
use crate::config::SETTINGS;
use ratatui::layout::Rect;
fn frame() -> Rect {
Rect::new(0, 0, 80, 24)
}
#[test]
fn returns_none_after_dismiss_timeout() {
let past_dismiss = SETTINGS.ui.error_auto_dismiss_ms as u128 + 1;
assert!(popup_area(frame(), "msg", 0, past_dismiss).is_none());
}
#[test]
fn returns_some_inside_dismiss_window() {
assert!(popup_area(frame(), "msg", 0, 0).is_some());
}
#[test]
fn returns_none_when_vertical_room_too_small() {
// base_y = 22 leaves only height 24 - 22 - 1 = 1 row of usable space,
// less than the minimum 3 needed for border + content + border.
assert!(popup_area(frame(), "msg", 22, 0).is_none());
}
#[test]
fn clamps_popup_width_to_frame() {
// a wider-than-the-frame message gets clamped so the popup fits
// inside frame.width minus the right-edge padding (saturating_sub(4)).
let huge = "x".repeat(200);
let area = popup_area(frame(), &huge, 0, 0).unwrap();
assert!(area.width <= frame().width.saturating_sub(4));
}
#[test]
fn anchors_popup_to_right_edge() {
let area = popup_area(frame(), "msg", 0, 0).unwrap();
// popup_w is added to base_x to reach frame.width - 2 (right-edge gutter)
assert_eq!(area.x + area.width + 2, frame().width);
}
}
@@ -238,3 +238,156 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
}
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// serialise against parallel tests of the same global IMPORT_STATE.
static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn reset_import_state(step: ImportStep) {
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
*guard = ImportWizardState::default();
guard.step = step;
}
#[test]
fn import_modpack_renders_input_step() {
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
reset_import_state(ImportStep::Input);
let backend = TestBackend::new(60, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn import_modpack_renders_fetching_step() {
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
reset_import_state(ImportStep::Fetching);
let backend = TestBackend::new(60, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// Version step: pre-populate versions as LoadState::Loaded with synthetic
// VersionInfo entries so render walks the list path without triggering
// any network helpers.
#[test]
fn import_modpack_renders_version_step() {
use crate::net::modrinth::VersionInfo;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
*guard = ImportWizardState::default();
guard.step = ImportStep::Version;
guard.project_title = Some("Synthetic Pack".into());
guard.versions = LoadState::Loaded(vec![
VersionInfo {
id: "v1".into(),
name: "1.0.0".into(),
version_number: "1.0.0".into(),
game_versions: vec!["1.20.1".into()],
loaders: vec!["fabric".into()],
files: vec![],
},
VersionInfo {
id: "v2".into(),
name: "0.9.0".into(),
version_number: "0.9.0".into(),
game_versions: vec!["1.20.1".into()],
loaders: vec!["fabric".into()],
files: vec![],
},
]);
}
let backend = TestBackend::new(60, 14);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// Confirm step: needs a populated ImportSummary so the render path
// doesn't bail. ImportSummary is constructed manually with synthetic
// values; archive_path is a fake tempdir-ish path that never gets read.
#[test]
fn import_modpack_renders_confirm_step() {
use crate::instance::import::{ImportSummary, PackFormat};
use crate::instance::models::ModLoader;
use std::path::PathBuf;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
*guard = ImportWizardState::default();
guard.step = ImportStep::Confirm;
guard.summary = Some(ImportSummary {
name: "Synthetic Pack".into(),
pack_version: "1.0.0".into(),
game_version: "1.20.1".into(),
loader: ModLoader::Fabric,
loader_version: Some("0.15.0".into()),
mod_count: 42,
override_count: 3,
format: PackFormat::Mrpack,
archive_path: PathBuf::from("/tmp/synthetic.mrpack"),
});
}
let backend = TestBackend::new(60, 14);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// Confirm step with loader_version=None: covers the branch where the
// pack didn't declare a loader version (rare upstream, but happens for
// older mmc packs). render_confirm_step has to handle the Option.
#[test]
fn import_modpack_renders_confirm_step_without_loader_version() {
use crate::instance::import::{ImportSummary, PackFormat};
use crate::instance::models::ModLoader;
use std::path::PathBuf;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock");
*guard = ImportWizardState::default();
guard.step = ImportStep::Confirm;
guard.summary = Some(ImportSummary {
name: "Vanilla Pack".into(),
pack_version: "2.0".into(),
game_version: "1.20.1".into(),
loader: ModLoader::Vanilla,
loader_version: None,
mod_count: 0,
override_count: 12,
format: PackFormat::Mmc,
archive_path: PathBuf::from("/tmp/vanilla.zip"),
});
}
let backend = TestBackend::new(60, 14);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::ImportPopup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
}
@@ -0,0 +1,18 @@
---
source: src/tui/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
"│Name: Synthetic Pack │"
"│Pack Version: 1.0.0 │"
"│MC Version: 1.20.1 │"
"│Loader: Fabric 0.15.0 │"
"│Mods: 42 files │"
"│Overrides: 3 files │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────[h] back [Enter] import╯"
@@ -0,0 +1,18 @@
---
source: src/tui/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
"│Name: Vanilla Pack │"
"│Pack Version: 2.0 │"
"│MC Version: 1.20.1 │"
"│Loader: Vanilla │"
"│Mods: 0 files │"
"│Overrides: 12 files │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────[h] back [Enter] import╯"
@@ -0,0 +1,16 @@
---
source: src/tui/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
"│Fetching modpack info... │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────────────────[Esc] cancel╯"
@@ -0,0 +1,16 @@
---
source: src/tui/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
"│URL, slug, or pack file path...█ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰─────────────────────────────────────────────[Enter] fetch╯"
@@ -0,0 +1,18 @@
---
source: src/tui/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
"│▶ 1.0.0 1.20.1 fabric │"
"│ 0.9.0 1.20.1 fabric │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────[/] search [h] back [Enter] select╯"
@@ -324,3 +324,148 @@ fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe
.wrap(Wrap { trim: true })
.render(area, buf);
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// WIZARD_STATE is a process-global static; without serialisation, parallel
// tests would race when each test sets the step and then renders, since
// render re-acquires the WIZARD_STATE mutex internally. this guard mutex
// ensures only one wizard snapshot test runs at a time.
static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn reset_wizard_state(step: WizardStep) {
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
*guard = WizardState::default();
guard.step = step;
}
#[test]
fn new_instance_renders_name_step() {
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
// Name is the default step; render touches no network helpers.
reset_wizard_state(WizardStep::Name);
let backend = TestBackend::new(60, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Popup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn new_instance_renders_loader_step() {
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
// Loader step is reached after Name; render just paints the hardcoded
// loader list, no network.
reset_wizard_state(WizardStep::Loader);
let backend = TestBackend::new(60, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Popup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// Version step: pre-populate versions as LoadState::Loaded so
// ensure_versions_loaded short-circuits and never spawns a network task.
// the three synthetic versions are marked stable=true so they show with
// show_snapshots=false (the default).
#[test]
fn new_instance_renders_version_step() {
use crate::instance::loader::GameVersion;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
*guard = WizardState::default();
guard.step = WizardStep::Version;
guard.versions = LoadState::Loaded(vec![
GameVersion {
id: "1.20.1".into(),
stable: true,
},
GameVersion {
id: "1.19.4".into(),
stable: true,
},
GameVersion {
id: "1.18.2".into(),
stable: true,
},
]);
}
let backend = TestBackend::new(60, 14);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Popup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// LoaderVersion step: needs both versions and loader_versions pre-loaded.
// pick a non-Vanilla loader (loader_idx=2 = Forge) so the step doesn't
// skip itself to Confirm.
#[test]
fn new_instance_renders_loader_version_step() {
use crate::instance::loader::GameVersion;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
*guard = WizardState::default();
guard.step = WizardStep::LoaderVersion;
guard.loader_idx = 2; // Forge
guard.versions = LoadState::Loaded(vec![GameVersion {
id: "1.20.1".into(),
stable: true,
}]);
guard.loader_versions =
LoadState::Loaded(vec!["47.2.0".into(), "47.1.0".into(), "47.0.50".into()]);
}
let backend = TestBackend::new(60, 14);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Popup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
// Confirm step: paints a summary, no network, no list. requires
// versions + loader_versions Loaded so selected_*() return Some.
#[test]
fn new_instance_renders_confirm_step() {
use crate::instance::loader::GameVersion;
use tui_prompts::TextState;
let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
{
let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock");
*guard = WizardState::default();
guard.step = WizardStep::Confirm;
guard.loader_idx = 1; // Fabric
guard.versions = LoadState::Loaded(vec![GameVersion {
id: "1.20.1".into(),
stable: true,
}]);
guard.loader_versions = LoadState::Loaded(vec!["0.15.0".into()]);
// TextState exposes only constructors; rebuilding with the
// desired initial value is the supported path.
guard.name_state = TextState::new().with_value("MyPack");
}
let backend = TestBackend::new(60, 12);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| render(f, f.area(), FocusedArea::Popup))
.unwrap();
insta::assert_snapshot!(terminal.backend());
}
}
@@ -0,0 +1,16 @@
---
source: src/tui/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
"│Name: MyPack │"
"│MC: 1.20.1 │"
"│Loader: Fabric │"
"│Loader version: 0.15.0 │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────[h] back [Enter] create╯"
@@ -0,0 +1,16 @@
---
source: src/tui/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
"│▶ Vanilla │"
"│ Fabric │"
"│ Forge │"
"│ NeoForge │"
"│ Quilt │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────[h] back [Enter] select╯"
@@ -0,0 +1,18 @@
---
source: src/tui/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
"│▶ 47.2.0 │"
"│ 47.1.0 │"
"│ 47.0.50 │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────[h] back [Enter] select╯"
@@ -0,0 +1,16 @@
---
source: src/tui/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
"│Instance name...█ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────────────[Enter] continue╯"
@@ -0,0 +1,18 @@
---
source: src/tui/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
"│▶ 1.20.1 │"
"│ 1.19.4 │"
"│ 1.18.2 │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰────────────[/] search [s] snap [h] back [Enter] select╯"
@@ -0,0 +1,9 @@
---
source: src/tui/widgets/popups/error.rs
expression: term.backend()
---
"╭ ERROR ───────────────────────────────╮"
"│Connection refused │"
"│ │"
"│ │"
"╰──────────────────────────────────────╯"
@@ -0,0 +1,9 @@
---
source: src/tui/widgets/popups/error.rs
expression: term.backend()
---
"╭ INFO ────────────────────────────────╮"
"│Reloaded config │"
"│ │"
"│ │"
"╰──────────────────────────────────────╯"
@@ -0,0 +1,14 @@
---
source: src/tui/widgets/popups/error.rs
expression: term.backend()
---
"╭ ERROR ───────────────────────────────╮"
"│The Minecraft launcher could not reach│"
"│the Mojang version manifest after │"
"│three retries. Check your network │"
"│connection or proxy settings. │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────────╯"
@@ -0,0 +1,9 @@
---
source: src/tui/widgets/popups/error.rs
expression: term.backend()
---
"╭ WARN ──────────╮"
"│Short message │"
"│ │"
"│ │"
"╰────────────────╯"
@@ -0,0 +1,9 @@
---
source: src/tui/widgets/popups/error.rs
expression: term.backend()
---
"╭ WARN ────────────────────────────────╮"
"│Disk space low │"
"│ │"
"│ │"
"╰──────────────────────────────────────╯"
+26
View File
@@ -92,6 +92,7 @@ impl ScreenshotsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
@@ -148,6 +149,7 @@ impl ScreenshotsState {
&& let Ok(mut slot) = pending.lock()
{
slot.push((idx, img));
crate::tui::request_redraw();
}
});
}
@@ -173,6 +175,30 @@ impl ScreenshotsState {
}
self.entries.len().div_ceil(self.cols)
}
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let entry = self.entries.get(self.selected)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
self.protocols.clear();
self.requested.clear();
if self.entries.is_empty() {
self.selected = 0;
self.scroll_row = 0;
} else {
self.selected = self.selected.min(self.entries.len().saturating_sub(1));
self.ensure_visible();
}
}
}
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
+476 -54
View File
@@ -1,27 +1,193 @@
// settings panel: shows instance config (memory, java, jvm args, resolution)
// and provides keybinds to open config files in $EDITOR
// settings panel: manages config profiles and shows compact instance info.
// also provides keybinds to open config files in $EDITOR.
use ratatui::{
Frame,
layout::Rect,
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
use std::{
path::{Path, PathBuf},
process::Command,
};
use crate::config::theme::{BORDER_STYLE, THEME};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::{
SETTINGS,
theme::{BORDER_STYLE, THEME},
};
use crate::instance::models::InstanceConfig;
use crate::tui::app::FocusedArea;
use super::styled_title;
const LOCAL_PROFILE_LABEL: &str = "instance default";
#[derive(Default)]
pub enum AddMode {
#[default]
None,
ProfileName(String),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SettingsPane {
#[default]
Profile,
Info,
}
pub struct SettingsState {
pub list_state: TuiListState,
pub profiles: Vec<String>,
pub add_mode: AddMode,
pub pane: SettingsPane,
meta_dir: PathBuf,
active_profile: Option<String>,
instance_name: Option<String>,
java_key: Option<String>,
java_source: Option<String>,
java_label: String,
}
impl SettingsState {
pub fn new(meta_dir: PathBuf) -> Self {
let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| {
tracing::warn!("Failed to load config sync profiles: {}", e);
Vec::new()
});
let mut state = Self {
list_state: TuiListState::default(),
profiles,
add_mode: AddMode::None,
pane: SettingsPane::Profile,
meta_dir,
active_profile: None,
instance_name: None,
java_key: None,
java_source: None,
java_label: "unknown".to_string(),
};
state.select_active();
state
}
fn reload_profiles(&mut self) {
match crate::instance::config_sync::list_profiles(&self.meta_dir) {
Ok(mut profiles) => {
add_active_profile(&mut profiles, self.active_profile.as_deref());
self.profiles = profiles;
}
Err(e) => tracing::warn!("Failed to reload config sync profiles: {}", e),
}
}
fn select_active(&mut self) {
self.list_state.selected = Some(
self.active_profile
.as_deref()
.and_then(|active| self.profiles.iter().position(|profile| profile == active))
.map(|idx| idx + 1)
.unwrap_or(0),
);
}
fn count(&self) -> usize {
self.profiles.len() + 1
}
fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) {
let instance_name = instance.map(|inst| inst.name.clone());
let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone());
let active_profile = active_profile
.filter(|profile| self.profiles.iter().any(|candidate| candidate == profile));
if self.instance_name != instance_name || self.active_profile != active_profile {
self.instance_name = instance_name;
self.active_profile = active_profile;
add_active_profile(&mut self.profiles, self.active_profile.as_deref());
self.select_active();
}
let java_key = instance.map(java_path_key);
if self.java_key != java_key {
let java_source = instance.map(effective_java_path);
self.java_label = java_source
.as_deref()
.map(java_version_label)
.unwrap_or_else(|| "unknown".to_string());
self.java_key = java_key;
self.java_source = java_source;
}
}
}
fn add_active_profile(profiles: &mut Vec<String>, active_profile: Option<&str>) {
if let Some(active) = active_profile
&& !profiles.iter().any(|profile| profile == active)
{
profiles.push(active.to_string());
profiles.sort_unstable();
}
}
fn java_path_key(instance: &InstanceConfig) -> String {
instance
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("<auto>")
.to_string()
}
fn effective_java_path(instance: &InstanceConfig) -> String {
instance
.java_path
.clone()
.or_else(|| SETTINGS.paths.effective_java_path().map(str::to_string))
.unwrap_or_else(crate::net::detect_java_path)
}
fn java_version_label(java_path: &str) -> String {
let output = Command::new(java_path).arg("-version").output();
let Ok(output) = output else {
return "unknown".to_string();
};
let raw = String::from_utf8_lossy(if output.stderr.is_empty() {
&output.stdout
} else {
&output.stderr
});
let first_line = raw.lines().next().unwrap_or_default();
let Some(version) = first_line.split('"').nth(1) else {
return "unknown".to_string();
};
let major = if let Some(stripped) = version.strip_prefix("1.") {
stripped.split('.').next().unwrap_or(stripped)
} else {
version.split('.').next().unwrap_or(version)
};
if major.is_empty() {
"unknown".to_string()
} else {
format!("jdk{major}")
}
}
pub fn render(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path,
_instances_dir: &Path,
) {
state.update_for_instance(instance);
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings {
theme.accent()
@@ -36,14 +202,22 @@ pub fn render(
.border_style(Style::default().fg(color));
if focused == FocusedArea::Settings {
let lines = super::popups::keybind_lines_wrapped(
&[
("e", " edit instance"),
("g", " edit global"),
("d", " desktop"),
let keybinds: &[(&str, &str)] = match state.pane {
SettingsPane::Profile => &[
("⏎", " select"),
("a", " add"),
("d", " del"),
("j/k", " move"),
("h/l", " tab"),
],
area.width.saturating_sub(2),
);
SettingsPane::Info => &[
("e", " inst"),
("g", " global"),
("d", " desk"),
("h/l", " tab"),
],
};
let lines = super::popups::keybind_lines_wrapped(keybinds, area.width.saturating_sub(2));
for line in lines {
block = block.title_bottom(line);
}
@@ -52,69 +226,317 @@ pub fn render(
let inner = block.inner(area);
frame.render_widget(block, area);
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
inner,
);
return;
};
if inner.width >= 42 {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50),
Constraint::Length(3),
Constraint::Percentage(50),
])
.split(inner);
render_profile_list(frame, chunks[0], focused, state);
render_separator(frame, chunks[1], focused, state.pane);
render_instance_info(frame, chunks[2], focused, state, instance);
} else {
render_profile_list(frame, inner, focused, state);
}
if let AddMode::ProfileName(name) = &state.add_mode {
render_add_profile_popup(frame, name);
}
}
fn render_separator(frame: &mut Frame, area: Rect, focused: FocusedArea, pane: SettingsPane) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings && pane == SettingsPane::Info {
theme.accent()
} else {
theme.border()
};
let line = if area.width >= 3 {
" │ \n".repeat(area.height as usize)
} else {
"│\n".repeat(area.height as usize)
};
frame.render_widget(Paragraph::new(line).style(Style::default().fg(color)), area);
}
fn render_instance_info(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &SettingsState,
instance: Option<&InstanceConfig>,
) {
let theme = THEME.as_ref();
let label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(theme.text_dim());
let memory_min = inst.memory_min.as_deref().unwrap_or("512M");
let memory_max = inst.memory_max.as_deref().unwrap_or("2G");
let java_path = inst.java_path.as_deref().unwrap_or("system");
let jvm_args = if inst.jvm_args.is_empty() {
"none".to_string()
} else {
inst.jvm_args.join(" ")
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
};
let resolution = inst
.resolution
.map(|(w, h)| format!("{}x{}", w, h))
.unwrap_or_else(|| "default".to_string());
let memory_min = inst
.memory_min
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_min);
let memory_max = inst
.memory_max
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_max);
let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info {
value_style.fg(theme.accent())
} else {
value_style
};
let desktop = if crate::instance::desktop::exists(&inst.name) {
"yes"
} else {
"no"
};
let lines = vec![
Line::from(vec![
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), value_style),
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), active_style),
]),
Line::from(vec![
Span::styled("Java ", label_style),
Span::styled(java_path, value_style),
Span::styled("Java ", label_style),
Span::styled(state.java_label.as_str(), active_style),
]),
Line::from(vec![
Span::styled("JVM ", label_style),
Span::styled(jvm_args, dim_style),
]),
Line::from(vec![
Span::styled("Display ", label_style),
Span::styled(resolution, value_style),
Span::styled("Desktop ", label_style),
Span::styled(desktop, active_style),
]),
];
frame.render_widget(Paragraph::new(lines), inner);
frame.render_widget(Paragraph::new(lines), area);
}
fn render_profile_list(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
) {
let is_focused = focused == FocusedArea::Settings;
let pane = state.pane;
let active_profile = state.active_profile.clone();
let profiles = state.profiles.clone();
let count = profiles.len() + 1;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let name = if context.index == 0 {
LOCAL_PROFILE_LABEL.to_string()
} else {
profiles[context.index - 1].clone()
};
let is_active = if context.index == 0 {
active_profile.is_none()
} else {
active_profile.as_deref() == Some(name.as_str())
};
let show_selected = is_focused && pane == SettingsPane::Profile && context.is_selected;
let marker = if is_active { "\u{25b8} " } else { " " };
let background = if show_selected {
theme.stripe()
} else {
theme.background()
};
let style = if show_selected {
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else if is_active {
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.text())
};
let line = Line::from(vec![
Span::styled(marker, Style::default().fg(theme.success())),
Span::styled(name, style),
]);
(
ratatui::text::Text::from(line).style(Style::default().bg(background)),
1,
)
});
frame.render_stateful_widget(ListView::new(builder, count), area, &mut state.list_state);
}
fn render_add_profile_popup(frame: &mut Frame, name: &str) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 42, 5);
let name = name.to_string();
let border_color = theme.text_dim();
let bg_color = theme.surface();
let dim_color = theme.text_dim();
let text_color = theme.text();
PopupFrame {
title: Line::from(Span::styled(
" Config Profile ",
Style::default()
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " create"), ("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
let line = if name.is_empty() {
Line::from(vec![
Span::styled("Profile name...", Style::default().fg(dim_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(name.as_str(), Style::default().fg(text_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
}
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
let area = frame.area();
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = area.y + (area.height.saturating_sub(height)) / 2;
Rect {
x,
y,
width: width.min(area.width),
height: height.min(area.height),
}
}
pub enum SettingsAction {
None,
EditInstance(std::path::PathBuf),
EditGlobal(std::path::PathBuf),
EditInstance(PathBuf),
EditGlobal(PathBuf),
ToggleDesktop,
SelectProfile(Option<String>),
ConfirmDeleteProfile(String),
Error(String),
}
pub fn handle_key(
key_event: &crossterm::event::KeyEvent,
key_event: &KeyEvent,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
instances_dir: &std::path::Path,
instances_dir: &Path,
) -> SettingsAction {
if let AddMode::ProfileName(name) = &state.add_mode {
match key_event.code {
KeyCode::Enter => {
let name = name.trim().to_string();
state.add_mode = AddMode::None;
if name.is_empty() {
return SettingsAction::None;
}
return match crate::instance::config_sync::create_profile(&state.meta_dir, &name) {
Ok(profile) => {
state.reload_profiles();
state.active_profile = Some(profile);
state.select_active();
SettingsAction::SelectProfile(state.active_profile.clone())
}
Err(e) => SettingsAction::Error(e.to_string()),
};
}
KeyCode::Esc => {
state.add_mode = AddMode::None;
return SettingsAction::None;
}
KeyCode::Backspace => {
let mut new_name = name.clone();
new_name.pop();
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
KeyCode::Char(c) => {
let mut new_name = name.clone();
new_name.push(c);
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
_ => return SettingsAction::None,
}
}
match key_event.code {
crossterm::event::KeyCode::Char('e') => {
KeyCode::Char('h') | KeyCode::Left => {
state.pane = SettingsPane::Profile;
SettingsAction::None
}
KeyCode::Char('l') | KeyCode::Right => {
state.pane = SettingsPane::Info;
SettingsAction::None
}
KeyCode::Enter if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
let profile = if selected == 0 {
None
} else {
state.profiles.get(selected - 1).cloned()
};
SettingsAction::SelectProfile(profile)
}
KeyCode::Char('a') if state.pane == SettingsPane::Profile => {
state.add_mode = AddMode::ProfileName(String::new());
SettingsAction::None
}
KeyCode::Char('d') if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
if selected == 0 {
SettingsAction::None
} else if let Some(profile) = state.profiles.get(selected - 1) {
SettingsAction::ConfirmDeleteProfile(profile.clone())
} else {
SettingsAction::None
}
}
KeyCode::Char('j') | KeyCode::Down if state.pane == SettingsPane::Profile => {
let count = state.count();
if count > 0 {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some((cur + 1).min(count - 1));
}
SettingsAction::None
}
KeyCode::Char('k') | KeyCode::Up if state.pane == SettingsPane::Profile => {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some(cur.saturating_sub(1));
SettingsAction::None
}
KeyCode::Char('e') if state.pane == SettingsPane::Info => {
if let Some(inst) = instance {
let path = instances_dir.join(&inst.name).join("instance.json");
SettingsAction::EditInstance(path)
@@ -122,11 +544,11 @@ pub fn handle_key(
SettingsAction::None
}
}
crossterm::event::KeyCode::Char('g') => {
KeyCode::Char('g') if state.pane == SettingsPane::Info => {
let path = crate::config::get_config_path().join("config.toml");
SettingsAction::EditGlobal(path)
}
crossterm::event::KeyCode::Char('d') => SettingsAction::ToggleDesktop,
KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop,
_ => SettingsAction::None,
}
}
@@ -0,0 +1,12 @@
---
source: src/tui/widgets/instances.rs
expression: terminal.backend()
---
"╭Instances─────────────────────────────╮"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"│ │"
"╰──────────────────────────────────────╯"
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more