Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d6e67bbba | ||
|
|
1a6c6ad9f5 | ||
|
|
1feb1679ff | ||
|
|
441607f0da | ||
|
|
33b2d856bc | ||
|
|
de9d11e2f3 | ||
|
|
b43ed3e807 | ||
|
|
035bae98d9 | ||
|
|
82665bd4e6 | ||
|
|
82d215f58b | ||
|
|
52747158e9 | ||
|
|
1019169100 | ||
|
|
5dbb2be873 | ||
|
|
9f463c80bc | ||
|
|
aa19e5bde1 | ||
|
|
7c1de45a2a | ||
|
|
ce34a28776 | ||
|
|
edb8efd033 | ||
|
|
b3da19cbaf | ||
|
|
e2caf66c19 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
- name: install JDK
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
+12
-190
@@ -7,206 +7,28 @@ on:
|
||||
branches: [master]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
artifact: mcl
|
||||
- os: ubuntu-latest
|
||||
target: aarch64-unknown-linux-gnu
|
||||
artifact: mcl
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
artifact: mcl.exe
|
||||
- os: macos-latest
|
||||
target: x86_64-apple-darwin
|
||||
artifact: mcl
|
||||
- os: macos-latest
|
||||
target: aarch64-apple-darwin
|
||||
artifact: mcl
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: install JDK
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
- name: install cross-compilation deps (aarch64-linux)
|
||||
if: matrix.target == 'aarch64-unknown-linux-gnu'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
|
||||
- name: check
|
||||
run: cargo check --locked
|
||||
|
||||
- name: build
|
||||
env:
|
||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
||||
run: cargo build --release --target ${{ matrix.target }}
|
||||
|
||||
- name: package (unix)
|
||||
if: runner.os != 'Windows'
|
||||
run: |
|
||||
cd target/${{ matrix.target }}/release
|
||||
tar czf ../../../mcl-${{ matrix.target }}.tar.gz ${{ matrix.artifact }}
|
||||
|
||||
- name: package (windows)
|
||||
if: runner.os == 'Windows'
|
||||
run: |
|
||||
cd target/${{ matrix.target }}/release
|
||||
Compress-Archive -Path ${{ matrix.artifact }} -DestinationPath ../../../mcl-${{ matrix.target }}.zip
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: mcl-${{ matrix.target }}
|
||||
path: mcl-${{ matrix.target }}.*
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
|
||||
outputs:
|
||||
released: ${{ steps.check.outputs.exists == 'false' }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: get version
|
||||
id: version
|
||||
run: |
|
||||
version=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: check if release exists
|
||||
id: check
|
||||
run: |
|
||||
if gh release view "${{ steps.version.outputs.tag }}" > /dev/null 2>&1; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: download artifacts
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: create and push tag
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
run: |
|
||||
git tag "${{ steps.version.outputs.tag }}"
|
||||
git push origin "${{ steps.version.outputs.tag }}"
|
||||
|
||||
- name: generate changelog
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
id: changelog
|
||||
uses: orhun/git-cliff-action@v4
|
||||
with:
|
||||
args: --latest --strip header
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: create release
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
run: |
|
||||
gh release create "${{ steps.version.outputs.tag }}" \
|
||||
--title "${{ steps.version.outputs.tag }}" \
|
||||
--notes "${{ steps.changelog.outputs.content }}" \
|
||||
artifacts/mcl-*/*
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
publish-crates:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
if: needs.release.outputs.released == 'true'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: publish to crates.io
|
||||
run: cargo publish --allow-dirty
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
|
||||
publish-aur:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
if: needs.release.outputs.released == 'true'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
# mcl-launcher (source package)
|
||||
- name: prepare mcl-launcher
|
||||
run: |
|
||||
sed -i "s|^pkgver=.*|pkgver=${{ needs.release.outputs.version }}|" pkg/mcl-launcher/PKGBUILD
|
||||
cp pkg/mcl-launcher/PKGBUILD PKGBUILD
|
||||
|
||||
- name: update checksums for mcl-launcher
|
||||
uses: datakrama/archlinux-package-action@v2
|
||||
with:
|
||||
updpkgsums: true
|
||||
srcinfo: true
|
||||
flags: ""
|
||||
namcap: false
|
||||
|
||||
- name: publish mcl-launcher to AUR
|
||||
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||
with:
|
||||
pkgname: mcl-launcher
|
||||
pkgbuild: PKGBUILD
|
||||
assets: .SRCINFO
|
||||
commit_username: objz
|
||||
commit_email: me@objz.dev
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_message: "Update to ${{ needs.release.outputs.version }}"
|
||||
|
||||
# mcl-launcher-bin (binary package)
|
||||
- name: prepare mcl-launcher-bin
|
||||
run: |
|
||||
sed -i "s|^pkgver=.*|pkgver=${{ needs.release.outputs.version }}|" pkg/mcl-launcher-bin/PKGBUILD
|
||||
cp pkg/mcl-launcher-bin/PKGBUILD PKGBUILD
|
||||
rm -f .SRCINFO
|
||||
|
||||
- name: update checksums for mcl-launcher-bin
|
||||
uses: datakrama/archlinux-package-action@v2
|
||||
with:
|
||||
updpkgsums: true
|
||||
srcinfo: true
|
||||
flags: ""
|
||||
namcap: false
|
||||
|
||||
- name: publish mcl-launcher-bin to AUR
|
||||
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||
with:
|
||||
pkgname: mcl-launcher-bin
|
||||
pkgbuild: PKGBUILD
|
||||
assets: .SRCINFO
|
||||
commit_username: objz
|
||||
commit_email: me@objz.dev
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_message: "Update to ${{ needs.release.outputs.version }}"
|
||||
- name: clippy
|
||||
run: cargo clippy --all-targets --locked -- -D warnings
|
||||
@@ -0,0 +1,102 @@
|
||||
name: publish AUR
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
plan:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PLAN: ${{ inputs.plan }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
||||
|
||||
- name: get version
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
version="$(jq --raw-output '.releases[0].app_version' <<< "$PLAN")"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: prepare mcl-launcher
|
||||
run: |
|
||||
sed -i "s|^pkgver=.*|pkgver=${{ steps.version.outputs.version }}|" pkg/mcl-launcher/PKGBUILD
|
||||
cp pkg/mcl-launcher/PKGBUILD PKGBUILD
|
||||
|
||||
- name: update checksums for mcl-launcher
|
||||
uses: datakrama/archlinux-package-action@v2
|
||||
with:
|
||||
updpkgsums: true
|
||||
srcinfo: true
|
||||
flags: ""
|
||||
namcap: false
|
||||
|
||||
- name: publish mcl-launcher to AUR
|
||||
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||
with:
|
||||
pkgname: mcl-launcher
|
||||
pkgbuild: PKGBUILD
|
||||
assets: .SRCINFO
|
||||
commit_username: objz
|
||||
commit_email: me@objz.dev
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_message: "Update to ${{ steps.version.outputs.version }}"
|
||||
|
||||
- name: prepare mcl-launcher-bin
|
||||
run: |
|
||||
sed -i "s|^pkgver=.*|pkgver=${{ steps.version.outputs.version }}|" pkg/mcl-launcher-bin/PKGBUILD
|
||||
cp pkg/mcl-launcher-bin/PKGBUILD PKGBUILD
|
||||
rm -f .SRCINFO
|
||||
|
||||
- name: update checksums for mcl-launcher-bin
|
||||
uses: datakrama/archlinux-package-action@v2
|
||||
with:
|
||||
updpkgsums: true
|
||||
srcinfo: true
|
||||
flags: ""
|
||||
namcap: false
|
||||
|
||||
- name: publish mcl-launcher-bin to AUR
|
||||
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||
with:
|
||||
pkgname: mcl-launcher-bin
|
||||
pkgbuild: PKGBUILD
|
||||
assets: .SRCINFO
|
||||
commit_username: objz
|
||||
commit_email: me@objz.dev
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_message: "Update to ${{ steps.version.outputs.version }}"
|
||||
|
||||
- name: prepare mcl-launcher-git
|
||||
run: |
|
||||
cp pkg/mcl-launcher-git/PKGBUILD PKGBUILD
|
||||
rm -f .SRCINFO
|
||||
|
||||
- name: update metadata for mcl-launcher-git
|
||||
uses: datakrama/archlinux-package-action@v2
|
||||
with:
|
||||
updpkgsums: true
|
||||
srcinfo: true
|
||||
flags: ""
|
||||
namcap: false
|
||||
|
||||
- name: publish mcl-launcher-git to AUR
|
||||
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||
with:
|
||||
pkgname: mcl-launcher-git
|
||||
pkgbuild: PKGBUILD
|
||||
assets: .SRCINFO
|
||||
commit_username: objz
|
||||
commit_email: me@objz.dev
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_message: "Update package metadata"
|
||||
@@ -0,0 +1,53 @@
|
||||
name: publish Chocolatey
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
plan:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PLAN: ${{ inputs.plan }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
||||
|
||||
- name: prepare Chocolatey package
|
||||
id: package
|
||||
shell: bash
|
||||
run: |
|
||||
tag="$(jq --raw-output '.announcement_tag' <<< "$PLAN")"
|
||||
version="$(jq --raw-output '.releases[0].app_version' <<< "$PLAN")"
|
||||
package_dir="target/chocolatey/mcl-launcher"
|
||||
checksum_file="mcl-launcher-x86_64-pc-windows-msvc.msi.sha256"
|
||||
|
||||
mkdir -p "$package_dir"
|
||||
cp -R pkg/chocolatey/* "$package_dir/"
|
||||
gh release download "$tag" --pattern "$checksum_file" --dir "$package_dir"
|
||||
|
||||
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"
|
||||
|
||||
- name: pack Chocolatey package
|
||||
uses: crazy-max/ghaction-chocolatey@v4
|
||||
with:
|
||||
args: pack ${{ steps.package.outputs.package_dir }}/mcl-launcher.nuspec --version ${{ steps.package.outputs.version }} --output-directory target/chocolatey/out
|
||||
|
||||
- name: push Chocolatey package
|
||||
uses: crazy-max/ghaction-chocolatey@v4
|
||||
with:
|
||||
args: push target/chocolatey/out/mcl-launcher.${{ steps.package.outputs.version }}.nupkg --source "https://push.chocolatey.org/" --api-key "${{ secrets.CHOCOLATEY_API_KEY }}"
|
||||
@@ -0,0 +1,28 @@
|
||||
name: publish crates
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
plan:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
||||
|
||||
- name: install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: publish to crates.io
|
||||
run: cargo publish --allow-dirty
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
@@ -0,0 +1,99 @@
|
||||
name: publish WinGet
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
plan:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: prepare WinGet manifest
|
||||
id: manifest
|
||||
shell: pwsh
|
||||
env:
|
||||
PLAN: ${{ inputs.plan }}
|
||||
run: |
|
||||
$plan = $env:PLAN | ConvertFrom-Json
|
||||
$tag = $plan.announcement_tag
|
||||
$version = $plan.releases[0].app_version
|
||||
$identifier = 'Objz.MclLauncher'
|
||||
$packagePath = "manifests/o/Objz/MclLauncher/$version"
|
||||
$installerFile = 'mcl-launcher-x86_64-pc-windows-msvc.msi'
|
||||
$checksumFile = "$installerFile.sha256"
|
||||
$installerUrl = "https://github.com/objz/mcl/releases/download/$tag/$installerFile"
|
||||
$checksumUrl = "https://github.com/objz/mcl/releases/download/$tag/$checksumFile"
|
||||
|
||||
New-Item -ItemType Directory -Path $packagePath -Force | Out-Null
|
||||
Invoke-WebRequest -Uri $checksumUrl -OutFile "$packagePath/$checksumFile"
|
||||
$checksum = (((Get-Content "$packagePath/$checksumFile" -Raw) -split '\s+')[0]).ToUpperInvariant()
|
||||
|
||||
$versionManifest = @"
|
||||
PackageIdentifier: $identifier
|
||||
PackageVersion: $version
|
||||
DefaultLocale: en-US
|
||||
ManifestType: version
|
||||
ManifestVersion: 1.9.0
|
||||
"@
|
||||
$versionManifest | Set-Content -Path "$packagePath/$identifier.yaml" -Encoding utf8
|
||||
|
||||
$installerManifest = @"
|
||||
PackageIdentifier: $identifier
|
||||
PackageVersion: $version
|
||||
InstallerType: wix
|
||||
Scope: machine
|
||||
InstallerSwitches:
|
||||
Silent: /quiet /norestart
|
||||
SilentWithProgress: /passive /norestart
|
||||
UpgradeBehavior: install
|
||||
Commands:
|
||||
- mcl
|
||||
Installers:
|
||||
- Architecture: x64
|
||||
InstallerUrl: $installerUrl
|
||||
InstallerSha256: $checksum
|
||||
ManifestType: installer
|
||||
ManifestVersion: 1.9.0
|
||||
"@
|
||||
$installerManifest | Set-Content -Path "$packagePath/$identifier.installer.yaml" -Encoding utf8
|
||||
|
||||
$localeManifest = @"
|
||||
PackageIdentifier: $identifier
|
||||
PackageVersion: $version
|
||||
PackageLocale: en-US
|
||||
Publisher: objz
|
||||
PublisherUrl: https://github.com/objz
|
||||
PublisherSupportUrl: https://github.com/objz/mcl/issues
|
||||
Author: objz
|
||||
PackageName: mcl-launcher
|
||||
PackageUrl: https://github.com/objz/mcl
|
||||
License: GPL-3.0-only
|
||||
LicenseUrl: https://github.com/objz/mcl/blob/master/LICENSE
|
||||
Copyright: Copyright (c) objz
|
||||
ShortDescription: Minecraft launcher TUI
|
||||
Description: A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.
|
||||
Moniker: mcl
|
||||
Tags:
|
||||
- minecraft
|
||||
- launcher
|
||||
- cli
|
||||
- tui
|
||||
ManifestType: defaultLocale
|
||||
ManifestVersion: 1.9.0
|
||||
"@
|
||||
$localeManifest | Set-Content -Path "$packagePath/$identifier.locale.en-US.yaml" -Encoding utf8
|
||||
|
||||
"path=$packagePath" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: submit WinGet manifest
|
||||
shell: pwsh
|
||||
run: |
|
||||
Invoke-WebRequest -Uri https://aka.ms/wingetcreate/latest -OutFile wingetcreate.exe
|
||||
.\wingetcreate.exe submit "${{ steps.manifest.outputs.path }}" --token "${{ secrets.WINGET_TOKEN }}"
|
||||
@@ -0,0 +1,404 @@
|
||||
# This file was autogenerated by dist: https://axodotdev.github.io/cargo-dist
|
||||
#
|
||||
# Copyright 2022-2024, axodotdev
|
||||
# SPDX-License-Identifier: MIT or Apache-2.0
|
||||
#
|
||||
# CI that:
|
||||
#
|
||||
# * checks for a Git Tag that looks like a release
|
||||
# * builds artifacts with dist (archives, installers, hashes)
|
||||
# * uploads those artifacts to temporary workflow zip
|
||||
# * on success, uploads the artifacts to a GitHub Release
|
||||
#
|
||||
# Note that the GitHub Release will be created with a generated
|
||||
# title/body based on your changelogs.
|
||||
|
||||
name: Release
|
||||
permissions:
|
||||
"contents": "write"
|
||||
|
||||
# This task will run whenever you push a git tag that looks like a version
|
||||
# like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc.
|
||||
# Various formats will be parsed into a VERSION and an optional PACKAGE_NAME, where
|
||||
# PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION
|
||||
# must be a Cargo-style SemVer Version (must have at least major.minor.patch).
|
||||
#
|
||||
# If PACKAGE_NAME is specified, then the announcement will be for that
|
||||
# package (erroring out if it doesn't have the given version or isn't dist-able).
|
||||
#
|
||||
# If PACKAGE_NAME isn't specified, then the announcement will be for all
|
||||
# (dist-able) packages in the workspace with that version (this mode is
|
||||
# intended for workspaces with only one dist-able package, or with all dist-able
|
||||
# packages versioned/released in lockstep).
|
||||
#
|
||||
# If you push multiple tags at once, separate instances of this workflow will
|
||||
# spin up, creating an independent announcement for each one. However, GitHub
|
||||
# will hard limit this to 3 tags per commit, as it will assume more tags is a
|
||||
# mistake.
|
||||
#
|
||||
# If there's a prerelease-style suffix to the version, then the release(s)
|
||||
# will be marked as a prerelease.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
tags:
|
||||
- '**[0-9]+.[0-9]+.[0-9]+*'
|
||||
|
||||
jobs:
|
||||
# Run 'dist plan' (or host) to determine what tasks we need to do
|
||||
plan:
|
||||
runs-on: "ubuntu-22.04"
|
||||
outputs:
|
||||
val: ${{ steps.plan.outputs.manifest }}
|
||||
tag: ${{ !github.event.pull_request && github.ref_name || '' }}
|
||||
tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }}
|
||||
publishing: ${{ !github.event.pull_request }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install dist
|
||||
# we specify bash to get pipefail; it guards against the `curl` command
|
||||
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
||||
shell: bash
|
||||
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.31.0/cargo-dist-installer.sh | sh"
|
||||
- name: Cache dist
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/dist
|
||||
# sure would be cool if github gave us proper conditionals...
|
||||
# so here's a doubly-nested ternary-via-truthiness to try to provide the best possible
|
||||
# functionality based on whether this is a pull_request, and whether it's from a fork.
|
||||
# (PRs run on the *source* but secrets are usually on the *target* -- that's *good*
|
||||
# but also really annoying to build CI around when it needs secrets to work right.)
|
||||
- id: plan
|
||||
run: |
|
||||
dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json
|
||||
echo "dist ran successfully"
|
||||
cat plan-dist-manifest.json
|
||||
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||
- name: "Upload dist-manifest.json"
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-plan-dist-manifest
|
||||
path: plan-dist-manifest.json
|
||||
|
||||
# Build and packages all the platform-specific things
|
||||
build-local-artifacts:
|
||||
name: build-local-artifacts (${{ join(matrix.targets, ', ') }})
|
||||
# Let the initial task tell us to not run (currently very blunt)
|
||||
needs:
|
||||
- plan
|
||||
if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Target platforms/runners are computed by dist in create-release.
|
||||
# Each member of the matrix has the following arguments:
|
||||
#
|
||||
# - runner: the github runner
|
||||
# - dist-args: cli flags to pass to dist
|
||||
# - install-dist: expression to run to install dist on the runner
|
||||
#
|
||||
# Typically there will be:
|
||||
# - 1 "global" task that builds universal installers
|
||||
# - N "local" tasks that build each platform's binaries and platform-specific installers
|
||||
matrix: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container: ${{ matrix.container && matrix.container.image || null }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json
|
||||
steps:
|
||||
- name: enable windows longpaths
|
||||
run: |
|
||||
git config --global core.longpaths true
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install Rust non-interactively if not already installed
|
||||
if: ${{ matrix.container }}
|
||||
run: |
|
||||
if ! command -v cargo > /dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
||||
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
||||
fi
|
||||
- name: "install JDK"
|
||||
uses: "actions/setup-java@v5"
|
||||
with:
|
||||
"distribution": "temurin"
|
||||
"java-version": "21"
|
||||
- name: Install dist
|
||||
run: ${{ matrix.install_dist.run }}
|
||||
# Get the dist-manifest
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
merge-multiple: true
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
${{ matrix.packages_install }}
|
||||
- name: Build artifacts
|
||||
run: |
|
||||
# Actually do builds and make zips and whatnot
|
||||
dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json
|
||||
echo "dist ran successfully"
|
||||
- id: cargo-dist
|
||||
name: Post-build
|
||||
# We force bash here just because github makes it really hard to get values up
|
||||
# to "real" actions without writing to env-vars, and writing to env-vars has
|
||||
# inconsistent syntax between shell and powershell.
|
||||
shell: bash
|
||||
run: |
|
||||
# Parse out what we just built and upload it to scratch storage
|
||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
||||
dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||
- name: "Upload artifacts"
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-build-local-${{ join(matrix.targets, '_') }}
|
||||
path: |
|
||||
${{ steps.cargo-dist.outputs.paths }}
|
||||
${{ env.BUILD_MANIFEST_NAME }}
|
||||
|
||||
# Build and package all the platform-agnostic(ish) things
|
||||
build-global-artifacts:
|
||||
needs:
|
||||
- plan
|
||||
- build-local-artifacts
|
||||
runs-on: "ubuntu-22.04"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install cached dist
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Get all the local artifacts for the global tasks to use (for e.g. checksums)
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
merge-multiple: true
|
||||
- id: cargo-dist
|
||||
shell: bash
|
||||
run: |
|
||||
dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json
|
||||
echo "dist ran successfully"
|
||||
|
||||
# Parse out what we just built and upload it to scratch storage
|
||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
||||
jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||
- name: "Upload artifacts"
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-build-global
|
||||
path: |
|
||||
${{ steps.cargo-dist.outputs.paths }}
|
||||
${{ env.BUILD_MANIFEST_NAME }}
|
||||
# Determines if we should publish/announce
|
||||
host:
|
||||
needs:
|
||||
- plan
|
||||
- build-local-artifacts
|
||||
- build-global-artifacts
|
||||
# Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine)
|
||||
if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
runs-on: "ubuntu-22.04"
|
||||
outputs:
|
||||
val: ${{ steps.host.outputs.manifest }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install cached dist
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Fetch artifacts from scratch-storage
|
||||
- name: Fetch artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
merge-multiple: true
|
||||
- id: host
|
||||
shell: bash
|
||||
run: |
|
||||
dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json
|
||||
echo "artifacts uploaded and released successfully"
|
||||
cat dist-manifest.json
|
||||
echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||
- name: "Upload dist-manifest.json"
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
# Overwrite the previous copy
|
||||
name: artifacts-dist-manifest
|
||||
path: dist-manifest.json
|
||||
# Create a GitHub Release while uploading all files to it
|
||||
- name: "Download GitHub Artifacts"
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Cleanup
|
||||
run: |
|
||||
# Remove the granular manifests
|
||||
rm -f artifacts/*-dist-manifest.json
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}"
|
||||
ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}"
|
||||
ANNOUNCEMENT_BODY: "${{ fromJson(steps.host.outputs.manifest).announcement_github_body }}"
|
||||
RELEASE_COMMIT: "${{ github.sha }}"
|
||||
run: |
|
||||
# Write and read notes from a file to avoid quoting breaking things
|
||||
echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt
|
||||
|
||||
gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*
|
||||
|
||||
publish-homebrew-formula:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
runs-on: "ubuntu-22.04"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PLAN: ${{ needs.plan.outputs.val }}
|
||||
GITHUB_USER: "axo bot"
|
||||
GITHUB_EMAIL: "admin+bot@axo.dev"
|
||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: true
|
||||
repository: "objz/homebrew-tap"
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
# So we have access to the formula
|
||||
- name: Fetch homebrew formulae
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: Formula/
|
||||
merge-multiple: true
|
||||
# This is extra complex because you can make your Formula name not match your app name
|
||||
# so we need to find releases with a *.rb file, and publish with that filename.
|
||||
- name: Commit formula files
|
||||
run: |
|
||||
git config --global user.name "${GITHUB_USER}"
|
||||
git config --global user.email "${GITHUB_EMAIL}"
|
||||
|
||||
for release in $(echo "$PLAN" | jq --compact-output '.releases[] | select([.artifacts[] | endswith(".rb")] | any)'); do
|
||||
filename=$(echo "$release" | jq '.artifacts[] | select(endswith(".rb"))' --raw-output)
|
||||
name=$(echo "$filename" | sed "s/\.rb$//")
|
||||
version=$(echo "$release" | jq .app_version --raw-output)
|
||||
|
||||
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
||||
brew update
|
||||
# We avoid reformatting user-provided data such as the app description and homepage.
|
||||
brew style --except-cops FormulaAudit/Homepage,FormulaAudit/Desc,FormulaAuditStrict --fix "Formula/${filename}" || true
|
||||
|
||||
git add "Formula/${filename}"
|
||||
git commit -m "${name} ${version}"
|
||||
done
|
||||
git push
|
||||
|
||||
custom-publish-crates:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||
uses: ./.github/workflows/publish-crates.yml
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
custom-publish-aur:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||
uses: ./.github/workflows/publish-aur.yml
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
custom-publish-winget:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||
uses: ./.github/workflows/publish-winget.yml
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
custom-publish-chocolatey:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||
uses: ./.github/workflows/publish-chocolatey.yml
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
announce:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
- publish-homebrew-formula
|
||||
- custom-publish-crates
|
||||
- custom-publish-aur
|
||||
- custom-publish-winget
|
||||
- custom-publish-chocolatey
|
||||
# use "always() && ..." to allow us to wait for all publish jobs while
|
||||
# still allowing individual publish jobs to skip themselves (for prereleases).
|
||||
# "host" however must run to completion, no skipping allowed!
|
||||
if: ${{ always() && needs.host.result == 'success' && (needs.publish-homebrew-formula.result == 'skipped' || needs.publish-homebrew-formula.result == 'success') && (needs.custom-publish-crates.result == 'skipped' || needs.custom-publish-crates.result == 'success') && (needs.custom-publish-aur.result == 'skipped' || needs.custom-publish-aur.result == 'success') && (needs.custom-publish-winget.result == 'skipped' || needs.custom-publish-winget.result == 'success') && (needs.custom-publish-chocolatey.result == 'skipped' || needs.custom-publish-chocolatey.result == 'success') }}
|
||||
runs-on: "ubuntu-22.04"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
@@ -0,0 +1,94 @@
|
||||
name: tag release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_run:
|
||||
workflows: ["build"]
|
||||
branches: [master]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: tag-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
tag-release:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
ref: ${{ github.event.workflow_run.head_sha || 'master' }}
|
||||
|
||||
- name: decide release tag
|
||||
id: release
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
version=$(awk '
|
||||
$0 == "[package]" { in_package = 1; next }
|
||||
/^\[/ && in_package { exit }
|
||||
in_package && $1 == "version" {
|
||||
gsub(/"/, "", $3)
|
||||
print $3
|
||||
exit
|
||||
}
|
||||
' Cargo.toml)
|
||||
|
||||
if [[ -z "$version" ]]; then
|
||||
echo "failed to read package version from Cargo.toml" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
latest=$(
|
||||
git tag --list \
|
||||
| sed -nE 's/^v?([0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?)$/\1/p' \
|
||||
| sort -V \
|
||||
| tail -n1
|
||||
)
|
||||
|
||||
should_release=false
|
||||
if [[ -z "$latest" ]]; then
|
||||
should_release=true
|
||||
elif [[ "$version" != "$latest" && "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -n1)" == "$version" ]]; then
|
||||
should_release=true
|
||||
fi
|
||||
|
||||
tag="v${version}"
|
||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||
echo "latest=${latest}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
||||
echo "should-release=${should_release}" >> "$GITHUB_OUTPUT"
|
||||
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if [[ "$should_release" == "true" ]]; then
|
||||
echo "Cargo.toml version ${version} is newer than latest tag ${latest:-<none>}; creating ${tag}."
|
||||
else
|
||||
echo "Cargo.toml version ${version} is not newer than latest tag ${latest}; skipping release."
|
||||
fi
|
||||
|
||||
- name: create release tag
|
||||
if: ${{ steps.release.outputs.should-release == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
TAG_NAME: ${{ steps.release.outputs.tag }}
|
||||
TAG_SHA: ${{ steps.release.outputs.sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${GH_TOKEN}" ]]; then
|
||||
echo "RELEASE_TOKEN is required so the created tag can trigger the generated release workflow." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/refs" \
|
||||
-f "ref=refs/tags/${TAG_NAME}" \
|
||||
-f "sha=${TAG_SHA}"
|
||||
+2
-2
@@ -34,7 +34,7 @@ the codebase is split roughly like this:
|
||||
|
||||
- `src/cli/` handles command line interface
|
||||
- `src/config/` has settings, paths, theme config
|
||||
- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch.rs` builds the java command and spawns minecraft. `manager.rs` does instance CRUD
|
||||
- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch/` builds the java command and spawns minecraft, with `patches.rs` handling lwjgl3ify classpath patches. `manager.rs` does instance CRUD
|
||||
- `src/net/` is the networking layer. http client, file downloads, and API clients per service
|
||||
- `src/tui/` is the terminal UI built with ratatui
|
||||
|
||||
@@ -52,4 +52,4 @@ start with what you did: `added`, `fixed`, `refactored`, etc. lowercase. separat
|
||||
|
||||
## before submitting
|
||||
|
||||
make sure `cargo build`, `cargo clippy`, and `cargo test` all pass.
|
||||
make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. you'll need a JDK (`javac` and `jar` on PATH) for the build script that compiles the java shim.
|
||||
Generated
+106
-1
@@ -1023,6 +1023,15 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fsevent-sys"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "funty"
|
||||
version = "2.0.0"
|
||||
@@ -1508,6 +1517,26 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"inotify-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify-sys"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
@@ -1692,6 +1721,26 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
|
||||
dependencies = [
|
||||
"kqueue-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue-sys"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lab"
|
||||
version = "0.11.0"
|
||||
@@ -1830,7 +1879,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mcl-launcher"
|
||||
version = "0.1.0"
|
||||
version = "0.2.3"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
@@ -1843,6 +1892,7 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"minecraft-msa-auth",
|
||||
"notify",
|
||||
"oauth2",
|
||||
"open",
|
||||
"ratatui",
|
||||
@@ -1972,6 +2022,33 @@ dependencies = [
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify"
|
||||
version = "8.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"fsevent-sys",
|
||||
"inotify",
|
||||
"kqueue",
|
||||
"libc",
|
||||
"log",
|
||||
"mio",
|
||||
"notify-types",
|
||||
"walkdir",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-types"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
@@ -3017,6 +3094,15 @@ dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
@@ -3972,6 +4058,16 @@ dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
@@ -4245,6 +4341,15 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
|
||||
+14
-1
@@ -1,15 +1,22 @@
|
||||
[package]
|
||||
name = "mcl-launcher"
|
||||
version = "0.2.0"
|
||||
version = "0.2.3"
|
||||
authors = ["objz"]
|
||||
edition = "2024"
|
||||
description = "A fully featured Minecraft launcher TUI"
|
||||
repository = "https://github.com/objz/mcl"
|
||||
homepage = "https://github.com/objz/mcl"
|
||||
license = "GPL-3.0-only"
|
||||
readme = "README.md"
|
||||
keywords = ["minecraft", "launcher", "tui", "ratatui"]
|
||||
categories = ["command-line-utilities", "games"]
|
||||
|
||||
[package.metadata.wix]
|
||||
upgrade-guid = "BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE"
|
||||
path-guid = "E5863AC2-13FC-45C8-B79D-55338F371A8A"
|
||||
license = false
|
||||
eula = false
|
||||
|
||||
[[bin]]
|
||||
name = "mcl"
|
||||
path = "src/main.rs"
|
||||
@@ -50,6 +57,7 @@ oauth2 = "5.0.0"
|
||||
open = "5"
|
||||
which = "8.0.2"
|
||||
dirs = "6.0.0"
|
||||
notify = "8"
|
||||
|
||||
|
||||
[profile.release]
|
||||
@@ -58,5 +66,10 @@ lto = true
|
||||
opt-level = "s"
|
||||
strip = true
|
||||
|
||||
# The profile that 'dist' will build with
|
||||
[profile.dist]
|
||||
inherits = "release"
|
||||
lto = "thin"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -48,6 +48,36 @@ Authentication is performed through Microsoft’s official services.
|
||||
|
||||
## installation
|
||||
|
||||
### macOS / Linux
|
||||
|
||||
release builds include shell and Homebrew installers generated by
|
||||
[`cargo-dist`](https://axodotdev.github.io/cargo-dist/).
|
||||
|
||||
```sh
|
||||
# installer script
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/objz/mcl/releases/latest/download/mcl-launcher-installer.sh | sh
|
||||
|
||||
# Homebrew tap
|
||||
brew install objz/tap/mcl-launcher
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
release builds include a PowerShell installer and an MSI. WinGet and Chocolatey
|
||||
packages are submitted from release CI and become available after repository
|
||||
review.
|
||||
|
||||
```powershell
|
||||
# installer script
|
||||
powershell -ExecutionPolicy Bypass -c "irm https://github.com/objz/mcl/releases/latest/download/mcl-launcher-installer.ps1 | iex"
|
||||
|
||||
# WinGet
|
||||
winget install Objz.MclLauncher
|
||||
|
||||
# Chocolatey
|
||||
choco install mcl-launcher
|
||||
```
|
||||
|
||||
### Arch Linux
|
||||
|
||||
[](https://aur.archlinux.org/packages/mcl-launcher)
|
||||
@@ -69,7 +99,7 @@ also available on [crates.io](https://crates.io/crates/mcl-launcher)
|
||||
|
||||
### from source
|
||||
|
||||
requires a Rust toolchain.
|
||||
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
||||
|
||||
```sh
|
||||
git clone https://github.com/objz/mcl.git
|
||||
@@ -77,24 +107,31 @@ cd mcl
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
### other platforms
|
||||
|
||||
mcl can be compiled for Linux, macOS, and Windows. right now it's only packaged for Arch Linux (AUR) but official packages for other platforms and package managers will be added continuously.
|
||||
|
||||
---
|
||||
|
||||
## where things live
|
||||
|
||||
| path | what |
|
||||
|---|---|
|
||||
| `~/.config/mcl/config.toml` | general config (paths, memory defaults, UI settings) |
|
||||
| `~/.config/mcl/theme.toml` | theme, border style, color overrides |
|
||||
| `~/.config/mcl/accounts.json` | accounts |
|
||||
| `~/.local/share/mcl/instances/` | instances, each in its own directory |
|
||||
| `~/.local/share/mcl/meta/` | cached game metadata, libraries, assets, loader profiles |
|
||||
### config & data
|
||||
|
||||
settings, accounts, instances, and cached game metadata.
|
||||
|
||||
| what | Linux | macOS | Windows |
|
||||
|---|---|---|---|
|
||||
| config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/mcl/` | `~/Library/Application Support/mcl/` | `%APPDATA%\mcl\` |
|
||||
| instances | `~/.local/share/mcl/instances/` | `~/Library/Application Support/mcl/instances/` | `%LOCALAPPDATA%\mcl\instances\` |
|
||||
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/mcl/meta/` | `~/Library/Application Support/mcl/meta/` | `%LOCALAPPDATA%\mcl\meta\` |
|
||||
|
||||
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
|
||||
|
||||
### logs
|
||||
|
||||
launcher logs are per-session and contain mcl's own output. instance launch logs capture game stdout/stderr per launch.
|
||||
|
||||
| what | Linux | macOS | Windows |
|
||||
|---|---|---|---|
|
||||
| launcher logs | `~/.cache/mcl/` | `~/Library/Caches/mcl/` | `%LOCALAPPDATA%\mcl\` |
|
||||
| instance launch logs | `<instances>/<name>/.minecraft/logs/launches/` | same | same |
|
||||
|
||||
---
|
||||
|
||||
## configuration
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=java/MclShim.java");
|
||||
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let out = Path::new(&out_dir);
|
||||
|
||||
// compile MclShim.java into a jar that gets embedded via include_bytes!
|
||||
let status = Command::new("javac")
|
||||
.arg("-source")
|
||||
.arg("8")
|
||||
.arg("-target")
|
||||
.arg("8")
|
||||
.arg("-d")
|
||||
.arg(out.to_str().unwrap())
|
||||
.arg("java/MclShim.java")
|
||||
.status()
|
||||
.expect("Failed to run javac - is a JDK installed?");
|
||||
|
||||
assert!(status.success(), "javac failed to compile MclShim.java");
|
||||
|
||||
// package into a jar
|
||||
let jar_path = out.join("mcl-shim.jar");
|
||||
let status = Command::new("jar")
|
||||
.arg("cfe")
|
||||
.arg(jar_path.to_str().unwrap())
|
||||
.arg("MclShim")
|
||||
.arg("-C")
|
||||
.arg(out.to_str().unwrap())
|
||||
.arg("MclShim.class")
|
||||
.status()
|
||||
.expect("Failed to run jar - is a JDK installed?");
|
||||
|
||||
assert!(status.success(), "jar failed to create mcl-shim.jar");
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
[workspace]
|
||||
members = ["cargo:."]
|
||||
|
||||
# Config for 'dist'
|
||||
[dist]
|
||||
# The preferred dist version to use in CI (Cargo.toml SemVer syntax)
|
||||
cargo-dist-version = "0.31.0"
|
||||
# CI backends to support
|
||||
ci = "github"
|
||||
# The installers to generate for each app
|
||||
installers = ["shell", "powershell", "homebrew", "msi"]
|
||||
# A GitHub repo to push Homebrew formulas to
|
||||
tap = "objz/homebrew-tap"
|
||||
# Target platforms to build apps for (Rust target-triple syntax)
|
||||
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
|
||||
# Path that installers should place binaries in
|
||||
install-path = "CARGO_HOME"
|
||||
# Publish jobs to run in CI
|
||||
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget", "./publish-chocolatey"]
|
||||
# Custom permissions for publish jobs
|
||||
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "read" }, publish-chocolatey = { contents = "read" } }
|
||||
# Extra setup steps for release artifact builders
|
||||
github-build-setup = "../dist-build-setup.yml"
|
||||
# Where to host releases
|
||||
hosting = "github"
|
||||
# Whether to install an updater program
|
||||
install-updater = false
|
||||
@@ -0,0 +1,19 @@
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class MclShim {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length == 0) {
|
||||
System.err.println("Usage: MclShim <mainClass> [args...]");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String mainClass = args[0];
|
||||
String[] remaining = new String[args.length - 1];
|
||||
System.arraycopy(args, 1, remaining, 0, remaining.length);
|
||||
|
||||
ClassLoader loader = ClassLoader.getSystemClassLoader();
|
||||
Class<?> clazz = loader.loadClass(mainClass);
|
||||
Method main = clazz.getMethod("main", String[].class);
|
||||
main.invoke(null, (Object) remaining);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>mcl-launcher</id>
|
||||
<version>0.0.0</version>
|
||||
<packageSourceUrl>https://github.com/objz/mcl</packageSourceUrl>
|
||||
<owners>objz</owners>
|
||||
<title>mcl-launcher</title>
|
||||
<authors>objz</authors>
|
||||
<projectUrl>https://github.com/objz/mcl</projectUrl>
|
||||
<licenseUrl>https://github.com/objz/mcl/blob/master/LICENSE</licenseUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<projectSourceUrl>https://github.com/objz/mcl</projectSourceUrl>
|
||||
<docsUrl>https://github.com/objz/mcl#readme</docsUrl>
|
||||
<bugTrackerUrl>https://github.com/objz/mcl/issues</bugTrackerUrl>
|
||||
<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>
|
||||
</metadata>
|
||||
<files>
|
||||
<file src="tools\**" target="tools" />
|
||||
</files>
|
||||
</package>
|
||||
@@ -0,0 +1,12 @@
|
||||
VERIFICATION
|
||||
|
||||
This package downloads the official MSI from the GitHub release:
|
||||
|
||||
https://github.com/objz/mcl/releases/download/__TAG__/mcl-launcher-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/mcl/releases/download/__TAG__/mcl-launcher-x86_64-pc-windows-msvc.msi.sha256
|
||||
|
||||
Expected SHA256:
|
||||
__CHECKSUM64__
|
||||
@@ -0,0 +1,14 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$packageArgs = @{
|
||||
packageName = $env:ChocolateyPackageName
|
||||
fileType = 'msi'
|
||||
url64bit = 'https://github.com/objz/mcl/releases/download/__TAG__/mcl-launcher-x86_64-pc-windows-msvc.msi'
|
||||
softwareName = 'mcl-launcher*'
|
||||
checksum64 = '__CHECKSUM64__'
|
||||
checksumType64 = 'sha256'
|
||||
silentArgs = '/quiet /norestart'
|
||||
validExitCodes = @(0, 3010, 1641)
|
||||
}
|
||||
|
||||
Install-ChocolateyPackage @packageArgs
|
||||
@@ -10,8 +10,8 @@ depends=()
|
||||
provides=('mcl-launcher')
|
||||
conflicts=('mcl-launcher' 'mcl-launcher-git')
|
||||
source=("LICENSE-${pkgver}::${url}/raw/v${pkgver}/LICENSE" "README-${pkgver}::${url}/raw/v${pkgver}/README.md")
|
||||
source_x86_64=("${url}/releases/download/v${pkgver}/mcl-x86_64-unknown-linux-gnu.tar.gz")
|
||||
source_aarch64=("${url}/releases/download/v${pkgver}/mcl-aarch64-unknown-linux-gnu.tar.gz")
|
||||
source_x86_64=("${url}/releases/download/v${pkgver}/mcl-launcher-x86_64-unknown-linux-gnu.tar.xz")
|
||||
source_aarch64=("${url}/releases/download/v${pkgver}/mcl-launcher-aarch64-unknown-linux-gnu.tar.xz")
|
||||
sha256sums=('SKIP' 'SKIP')
|
||||
sha256sums_x86_64=('SKIP')
|
||||
sha256sums_aarch64=('SKIP')
|
||||
|
||||
@@ -7,7 +7,7 @@ arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/objz/mcl"
|
||||
license=('GPL-3.0-only')
|
||||
depends=()
|
||||
makedepends=('git' 'rust' 'cargo')
|
||||
makedepends=('git' 'rust' 'cargo' 'jdk-openjdk')
|
||||
provides=('mcl-launcher')
|
||||
conflicts=('mcl-launcher' 'mcl-launcher-bin')
|
||||
source=("git+$url.git")
|
||||
|
||||
@@ -7,7 +7,7 @@ arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/objz/mcl"
|
||||
license=('GPL-3.0-only')
|
||||
depends=()
|
||||
makedepends=('rust' 'cargo')
|
||||
makedepends=('rust' 'cargo' 'jdk-openjdk')
|
||||
provides=('mcl-launcher')
|
||||
conflicts=('mcl-launcher-bin' 'mcl-launcher-git')
|
||||
source=("${url}/archive/v${pkgver}.tar.gz")
|
||||
|
||||
+32
-3
@@ -12,6 +12,10 @@ pub struct Account {
|
||||
pub active: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub refresh_token: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cached_mc_token: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cached_mc_token_expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
@@ -62,6 +66,12 @@ impl AccountStore {
|
||||
self.accounts.iter().find(|a| a.active)
|
||||
}
|
||||
|
||||
pub fn has_microsoft_account(&self) -> bool {
|
||||
self.accounts
|
||||
.iter()
|
||||
.any(|account| account.account_type == AccountType::Microsoft)
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, index: usize) {
|
||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
||||
acc.active = i == index;
|
||||
@@ -123,6 +133,8 @@ pub fn create_offline_account(username: &str) -> Account {
|
||||
account_type: AccountType::Offline,
|
||||
active: false,
|
||||
refresh_token: None,
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,12 +197,18 @@ mod tests {
|
||||
}
|
||||
|
||||
fn dummy_account(name: &str) -> Account {
|
||||
create_offline_account(name)
|
||||
}
|
||||
|
||||
fn microsoft_account(name: &str) -> Account {
|
||||
Account {
|
||||
uuid: offline_uuid(name),
|
||||
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
|
||||
username: name.to_owned(),
|
||||
account_type: AccountType::Offline,
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
refresh_token: None,
|
||||
refresh_token: Some("refresh".to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,6 +252,17 @@ mod tests {
|
||||
assert!(store.active_account().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
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"));
|
||||
assert!(!store.has_microsoft_account());
|
||||
|
||||
store.add(microsoft_account("Owner"));
|
||||
assert!(store.has_microsoft_account());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_active_account_returns_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+3
-3
@@ -3,7 +3,7 @@ mod accounts;
|
||||
mod oauth;
|
||||
|
||||
pub use accounts::{
|
||||
account_store_path, create_offline_account, offline_uuid, Account, AccountStore, AccountType,
|
||||
AuthResult,
|
||||
Account, AccountStore, AccountType, AuthResult, account_store_path, create_offline_account,
|
||||
offline_uuid,
|
||||
};
|
||||
pub use oauth::{refresh_and_get_token, start_microsoft_auth, DeviceCodeInfo, DEVICE_CODE_DISPLAY};
|
||||
pub use oauth::{DEVICE_CODE_DISPLAY, DeviceCodeInfo, refresh_and_get_token, start_microsoft_auth};
|
||||
+83
-6
@@ -19,6 +19,8 @@ const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth
|
||||
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
|
||||
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
|
||||
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
|
||||
const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60;
|
||||
const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DeviceCodeInfo {
|
||||
@@ -131,7 +133,7 @@ async fn exchange_and_build_account(
|
||||
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
||||
};
|
||||
|
||||
// mojang returns uuids without dashes because of course they do
|
||||
// mojang returns uuids without dashes
|
||||
let uuid = if profile.id.len() == 32 {
|
||||
format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
@@ -151,15 +153,42 @@ async fn exchange_and_build_account(
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
// returns (mc_access_token, new_refresh_token). for offline accounts it just
|
||||
// hands back a dummy token since the server doesn't care.
|
||||
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> {
|
||||
fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
|
||||
let (Some(cached), Some(expires_at)) = (
|
||||
account.cached_mc_token.as_deref(),
|
||||
account.cached_mc_token_expires_at,
|
||||
) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS {
|
||||
Some(cached)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at).
|
||||
// cached tokens return no expiry so callers don't rewrite the account store.
|
||||
pub async fn refresh_and_get_token(
|
||||
account: &Account,
|
||||
) -> Result<(String, Option<String>, Option<i64>), String> {
|
||||
match account.account_type {
|
||||
AccountType::Offline => Ok(("0".to_owned(), None)),
|
||||
AccountType::Offline => Ok(("0".to_owned(), None, None)),
|
||||
AccountType::Microsoft => {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
if let Some(cached) = valid_cached_mc_token(account, now) {
|
||||
tracing::info!("Using cached Minecraft token for '{}'", account.username);
|
||||
return Ok((cached.to_owned(), None, None));
|
||||
}
|
||||
|
||||
tracing::info!("Refreshing Minecraft token for '{}'", account.username);
|
||||
|
||||
let refresh = account.refresh_token.as_deref().ok_or_else(|| {
|
||||
format!(
|
||||
"No saved credentials for '{}'. Please remove and re-add the account.",
|
||||
@@ -192,7 +221,55 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<
|
||||
.await
|
||||
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
|
||||
|
||||
Ok((mc_token.access_token().as_ref().to_owned(), new_refresh))
|
||||
// minecraft-msa-auth does not expose this expiry here, so cache
|
||||
// conservatively and refresh before the token gets close.
|
||||
let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS;
|
||||
|
||||
Ok((
|
||||
mc_token.access_token().as_ref().to_owned(),
|
||||
new_refresh,
|
||||
Some(expires_at),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
|
||||
Account {
|
||||
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
||||
username: "TestPlayer".to_owned(),
|
||||
account_type: AccountType::Microsoft,
|
||||
active: true,
|
||||
refresh_token: Some("refresh".to_owned()),
|
||||
cached_mc_token: Some("cached".to_owned()),
|
||||
cached_mc_token_expires_at,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_mc_token_is_valid_before_refresh_margin() {
|
||||
let now = 1_000;
|
||||
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1));
|
||||
|
||||
assert_eq!(valid_cached_mc_token(&account, now), Some("cached"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_mc_token_expires_inside_refresh_margin() {
|
||||
let now = 1_000;
|
||||
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
|
||||
|
||||
assert!(valid_cached_mc_token(&account, now).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_mc_token_requires_expiry() {
|
||||
let account = microsoft_account(None);
|
||||
|
||||
assert!(valid_cached_mc_token(&account, 1_000).is_none());
|
||||
}
|
||||
}
|
||||
+61
-28
@@ -21,13 +21,13 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
// trait indirection so a mock store can be swapped in for tests
|
||||
trait AccountStoreLike {
|
||||
fn accounts(&self) -> &[Account];
|
||||
fn has_microsoft_account(&self) -> bool;
|
||||
fn add_account(&mut self, account: Account);
|
||||
}
|
||||
|
||||
impl AccountStoreLike for AccountStore {
|
||||
fn accounts(&self) -> &[Account] {
|
||||
&self.accounts
|
||||
fn has_microsoft_account(&self) -> bool {
|
||||
AccountStore::has_microsoft_account(self)
|
||||
}
|
||||
|
||||
fn add_account(&mut self, account: Account) {
|
||||
@@ -81,28 +81,30 @@ async fn add_microsoft_account() -> CliResult {
|
||||
// wait for the device code to become available before showing it
|
||||
loop {
|
||||
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
||||
&& let Some(info) = slot.as_ref() {
|
||||
println!("Open: {}", info.verification_uri);
|
||||
println!("Code: {}", info.user_code);
|
||||
break;
|
||||
}
|
||||
&& let Some(info) = slot.as_ref()
|
||||
{
|
||||
println!("Open: {}", info.verification_uri);
|
||||
println!("Code: {}", info.user_code);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
|
||||
// now wait for the user to complete auth in their browser
|
||||
loop {
|
||||
if let Ok(slot) = result_arc.lock()
|
||||
&& let Some(result) = slot.as_ref() {
|
||||
return match result {
|
||||
AuthResult::Success(account) => {
|
||||
let mut store = AccountStore::load();
|
||||
store.add(account.clone());
|
||||
println!("Added Microsoft account '{}'.", account.username);
|
||||
Ok(())
|
||||
}
|
||||
AuthResult::Error(message) => Err(io::Error::other(message.clone()).into()),
|
||||
};
|
||||
}
|
||||
&& let Some(result) = slot.as_ref()
|
||||
{
|
||||
return match result {
|
||||
AuthResult::Success(account) => {
|
||||
let mut store = AccountStore::load();
|
||||
store.add(account.clone());
|
||||
println!("Added Microsoft account '{}'.", account.username);
|
||||
Ok(())
|
||||
}
|
||||
AuthResult::Error(message) => Err(io::Error::other(message.clone()).into()),
|
||||
};
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
@@ -112,6 +114,12 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
|
||||
if username.is_empty() {
|
||||
return Err(io::Error::other("offline username cannot be empty").into());
|
||||
}
|
||||
if !store.has_microsoft_account() {
|
||||
return Err(io::Error::other(
|
||||
"add a Microsoft account that owns Minecraft before adding offline accounts",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
store.add_account(crate::auth::create_offline_account(username));
|
||||
Ok(())
|
||||
@@ -120,7 +128,7 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
|
||||
fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
let index = find_account_index(store.accounts(), username)
|
||||
let index = find_account_index(&store.accounts, username)
|
||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||
|
||||
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
||||
@@ -136,7 +144,7 @@ fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
fn use_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
let index = find_account_index(store.accounts(), username)
|
||||
let index = find_account_index(&store.accounts, username)
|
||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||
store.set_active(index);
|
||||
println!("Active account set to '{}'.", username);
|
||||
@@ -153,7 +161,7 @@ use super::utils::{confirm, required_arg};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{add_offline_account, AccountStoreLike};
|
||||
use super::{AccountStoreLike, add_offline_account};
|
||||
use crate::auth::{Account, AccountType};
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -162,8 +170,10 @@ mod tests {
|
||||
}
|
||||
|
||||
impl AccountStoreLike for MockStore {
|
||||
fn accounts(&self) -> &[Account] {
|
||||
&self.accounts
|
||||
fn has_microsoft_account(&self) -> bool {
|
||||
self.accounts
|
||||
.iter()
|
||||
.any(|account| account.account_type == AccountType::Microsoft)
|
||||
}
|
||||
|
||||
fn add_account(&mut self, account: Account) {
|
||||
@@ -171,14 +181,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn microsoft_account() -> Account {
|
||||
Account {
|
||||
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
|
||||
username: "Owner".to_owned(),
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
refresh_token: Some("refresh".to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_offline_account_through_store() {
|
||||
fn creates_offline_account_after_microsoft_account_exists() {
|
||||
let mut store = MockStore::default();
|
||||
store.add_account(microsoft_account());
|
||||
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
||||
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert_eq!(store.accounts[0].username, "Steve");
|
||||
assert_eq!(store.accounts[0].account_type, AccountType::Offline);
|
||||
assert_eq!(store.accounts.len(), 2);
|
||||
assert_eq!(store.accounts[1].username, "Steve");
|
||||
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_offline_account_before_microsoft_account_exists() {
|
||||
let mut store = MockStore::default();
|
||||
let err = add_offline_account(&mut store, "Steve")
|
||||
.expect_err("offline account should require a microsoft account");
|
||||
|
||||
assert!(err.to_string().contains("Microsoft account"));
|
||||
assert!(store.accounts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+1
-1
@@ -2,8 +2,8 @@
|
||||
// resolves the input, downloads if needed, then hands off to the import engine.
|
||||
use clap::ArgMatches;
|
||||
|
||||
use crate::instance::import::{parse_import_input, ImportInput};
|
||||
use crate::instance::InstanceManager;
|
||||
use crate::instance::import::{ImportInput, parse_import_input};
|
||||
use crate::net::modrinth;
|
||||
|
||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
+3
-11
@@ -65,7 +65,7 @@ fn manager() -> InstanceManager {
|
||||
|
||||
fn list_instances() -> CliResult {
|
||||
let mut instances = manager().load_all();
|
||||
instances.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
|
||||
instances.sort_by_key(|instance| instance.name.to_lowercase());
|
||||
|
||||
let rows = instances
|
||||
.into_iter()
|
||||
@@ -249,18 +249,10 @@ fn apply_config_update(
|
||||
) -> CliResult {
|
||||
match key {
|
||||
"memory-max" => {
|
||||
config.memory_max = if value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(value.to_string())
|
||||
}
|
||||
config.memory_max = crate::instance::normalize_memory_value(value);
|
||||
}
|
||||
"memory-min" => {
|
||||
config.memory_min = if value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(value.to_string())
|
||||
}
|
||||
config.memory_min = crate::instance::normalize_memory_value(value);
|
||||
}
|
||||
"java-path" => {
|
||||
config.java_path = if value.is_empty() {
|
||||
|
||||
+1
-5
@@ -34,11 +34,7 @@ pub fn format_datetime(value: &DateTime<Utc>) -> String {
|
||||
}
|
||||
|
||||
pub fn active_marker(active: bool) -> &'static str {
|
||||
if active {
|
||||
">"
|
||||
} else {
|
||||
" "
|
||||
}
|
||||
if active { ">" } else { " " }
|
||||
}
|
||||
|
||||
// find the widest value in each column to pad everything evenly
|
||||
|
||||
+1
-1
@@ -9,8 +9,8 @@ use clap::ArgMatches;
|
||||
use crate::cli::instance::parse_loader;
|
||||
use crate::cli::output::print_table;
|
||||
use crate::instance::ModLoader;
|
||||
use crate::net::mojang::{VersionEntry, VersionManifest};
|
||||
use crate::net::HttpClient;
|
||||
use crate::net::mojang::{VersionEntry, VersionManifest};
|
||||
|
||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
|
||||
@@ -53,9 +53,10 @@ pub fn resolve_path(raw: &str) -> PathBuf {
|
||||
return home.join(stripped);
|
||||
}
|
||||
} else if raw == "~"
|
||||
&& let Some(home) = dirs_next::home_dir() {
|
||||
return home;
|
||||
}
|
||||
&& let Some(home) = dirs_next::home_dir()
|
||||
{
|
||||
return home;
|
||||
}
|
||||
PathBuf::from(raw)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ pub mod shaders;
|
||||
pub mod worlds;
|
||||
|
||||
pub use mods::{ContentEntry, scan_mods, toggle_entry};
|
||||
pub use resource_packs::scan_resource_packs;
|
||||
pub use shaders::scan_shaders;
|
||||
pub use worlds::scan_worlds;
|
||||
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};
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
|
||||
+371
-43
@@ -1,6 +1,8 @@
|
||||
// mod scanning, metadata extraction, and icon rendering for the content list.
|
||||
// jar files are just zips, so it cracks them open looking for fabric.mod.json to get
|
||||
// names, descriptions, and icons. if that fails, just the filename is used. it's fine.
|
||||
// jar files are just zips, so it cracks them open looking for loader-specific
|
||||
// metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get
|
||||
// names, descriptions, and icons. if none of those work, falls back to common
|
||||
// root-level icon paths (logo.png, icon.png, pack.png) or just the filename.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -41,18 +43,75 @@ struct FabricModJson {
|
||||
}
|
||||
|
||||
impl FabricModJson {
|
||||
// fabric's icon field can be a string path or a map of resolution -> path.
|
||||
// if it's a map, just grab the first one. good enough.
|
||||
fn icon_path(&self) -> String {
|
||||
match &self.icon {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::Object(map) => map
|
||||
.values()
|
||||
.find_map(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
_ => String::new(),
|
||||
}
|
||||
icon_path_from_value(&self.icon)
|
||||
}
|
||||
}
|
||||
|
||||
// fabric and quilt both support icon as a string path or a map of
|
||||
// resolution -> path. if it's a map, just grab the first one.
|
||||
fn icon_path_from_value(value: &serde_json::Value) -> String {
|
||||
match value {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::Object(map) => map
|
||||
.values()
|
||||
.find_map(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// quilt puts its metadata under a "metadata" sub-object
|
||||
#[derive(Deserialize, Default)]
|
||||
struct QuiltModJson {
|
||||
#[serde(default)]
|
||||
quilt_loader: QuiltLoader,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct QuiltLoader {
|
||||
#[serde(default)]
|
||||
metadata: QuiltMetadata,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct QuiltMetadata {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
icon: serde_json::Value,
|
||||
}
|
||||
|
||||
impl QuiltMetadata {
|
||||
fn icon_path(&self) -> String {
|
||||
icon_path_from_value(&self.icon)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||
let (name, description, icon_bytes) = read_mod_metadata(path);
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(fallback_icon()));
|
||||
|
||||
let display_name = if name.is_empty() {
|
||||
file_stem.to_owned()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
|
||||
ContentEntry {
|
||||
file_stem: file_stem.to_owned(),
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path: path.to_path_buf(),
|
||||
icon_lines,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,34 +139,17 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
|
||||
continue;
|
||||
};
|
||||
|
||||
let (name, description, icon_bytes) = read_mod_metadata(&path);
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(fallback_icon()));
|
||||
|
||||
let display_name = if name.is_empty() {
|
||||
file_stem.clone()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
entries.push(ContentEntry {
|
||||
file_stem,
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path,
|
||||
icon_lines,
|
||||
});
|
||||
entries.push(scan_one_mod(&path, &file_stem, enabled));
|
||||
}
|
||||
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
entries
|
||||
}
|
||||
|
||||
// tries fabric.mod.json first for rich metadata. if that's missing (forge/other mods),
|
||||
// still attempts to grab pack.png as a last resort for an icon
|
||||
// tries each loader's metadata file to extract name, description, and icon.
|
||||
// checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge),
|
||||
// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of
|
||||
// those yield an icon, falls back to common root-level paths.
|
||||
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
let file = match std::fs::File::open(jar_path) {
|
||||
Ok(file) => file,
|
||||
@@ -119,19 +161,43 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
Err(_) => return (String::new(), String::new(), None),
|
||||
};
|
||||
|
||||
if let Some((name, description, icon_path)) = read_fabric_meta(&mut archive) {
|
||||
let icon_bytes = if icon_path.is_empty() {
|
||||
None
|
||||
} else {
|
||||
read_zip_bytes(&mut archive, &icon_path)
|
||||
};
|
||||
return (name, description, icon_bytes);
|
||||
// try each loader's metadata in order. if we get metadata but the
|
||||
// declared icon path is missing, fall back to common root-level icons.
|
||||
type MetaReader = fn(&mut zip::ZipArchive<std::fs::File>) -> Option<(String, String, String)>;
|
||||
let readers: [MetaReader; 4] = [
|
||||
read_fabric_meta,
|
||||
read_quilt_meta,
|
||||
read_forge_toml_meta,
|
||||
read_mcmod_info,
|
||||
];
|
||||
|
||||
for reader in &readers {
|
||||
if let Some((name, description, icon_path)) = reader(&mut archive) {
|
||||
let icon_path = icon_path.trim_start_matches('/');
|
||||
let icon = if icon_path.is_empty() {
|
||||
None
|
||||
} else {
|
||||
read_zip_bytes(&mut archive, icon_path)
|
||||
}
|
||||
.or_else(|| try_fallback_icons(&mut archive));
|
||||
return (name, description, icon);
|
||||
}
|
||||
}
|
||||
|
||||
let icon_bytes = read_zip_bytes(&mut archive, "pack.png");
|
||||
// no recognized metadata at all, try common icon paths
|
||||
let icon_bytes = try_fallback_icons(&mut archive);
|
||||
(String::new(), String::new(), icon_bytes)
|
||||
}
|
||||
|
||||
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||
for path in ["logo.png", "icon.png", "pack.png"] {
|
||||
if let Some(bytes) = read_zip_bytes(archive, path) {
|
||||
return Some(bytes);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_fabric_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
@@ -144,6 +210,98 @@ fn read_fabric_meta(
|
||||
Some((data.name, data.description, icon))
|
||||
}
|
||||
|
||||
fn read_quilt_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
let mut entry = archive.by_name("quilt.mod.json").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
||||
let meta = data.quilt_loader.metadata;
|
||||
let icon = meta.icon_path();
|
||||
Some((meta.name, meta.description, icon))
|
||||
}
|
||||
|
||||
// forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml)
|
||||
// share the same format. we only need the top-level logoFile and the first
|
||||
// [[mods]] entry for name/description.
|
||||
// some jars (e.g. dependency-only libs) have a mods.toml with logoFile
|
||||
// but no [[mods]] section. we still want the icon in that case.
|
||||
fn read_forge_toml_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml")
|
||||
.or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?;
|
||||
let table: toml::Table = raw.parse().ok()?;
|
||||
let logo = table
|
||||
.get("logoFile")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let (name, description) = table
|
||||
.get("mods")
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|v| v.as_table())
|
||||
.map(|first| {
|
||||
let n = first
|
||||
.get("displayName")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let d = first
|
||||
.get("description")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_owned();
|
||||
(n, d)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Some((name, description, logo))
|
||||
}
|
||||
|
||||
// legacy forge mcmod.info is either a bare json array of mod entries
|
||||
// or an object with a "modList" key wrapping the array
|
||||
fn read_mcmod_info(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
let mut entry = archive.by_name("mcmod.info").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
|
||||
let first = match &parsed {
|
||||
serde_json::Value::Array(arr) => arr.first()?,
|
||||
serde_json::Value::Object(obj) => obj.get("modList")?.as_array()?.first()?,
|
||||
_ => return None,
|
||||
};
|
||||
let name = first
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let description = first
|
||||
.get("description")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let logo = first
|
||||
.get("logoFile")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
Some((name, description, logo))
|
||||
}
|
||||
|
||||
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
||||
let mut entry = archive.by_name(path).ok()?;
|
||||
let mut s = String::new();
|
||||
entry.read_to_string(&mut s).ok()?;
|
||||
Some(s)
|
||||
}
|
||||
|
||||
// some mod authors put raw newlines/tabs inside json string values which is
|
||||
// technically invalid json. walks through character by character, tracking
|
||||
// whether it's inside a string, and escapes the offending characters.
|
||||
@@ -407,6 +565,176 @@ mod tests {
|
||||
assert!(dir.join("mymod.jar").exists());
|
||||
}
|
||||
|
||||
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();
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let options: zip::write::FileOptions<()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
for (entry_name, data) in entries {
|
||||
zip.start_file(*entry_name, options).unwrap();
|
||||
zip.write_all(data).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_fabric_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#;
|
||||
make_jar(
|
||||
&dir,
|
||||
"fabric-mod.jar",
|
||||
&[("fabric.mod.json", meta.as_bytes())],
|
||||
);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "Fabric Mod");
|
||||
assert_eq!(mods[0].description, "A fabric mod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_quilt_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta =
|
||||
r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#;
|
||||
make_jar(
|
||||
&dir,
|
||||
"quilt-mod.jar",
|
||||
&[("quilt.mod.json", meta.as_bytes())],
|
||||
);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "Quilt Mod");
|
||||
assert_eq!(mods[0].description, "A quilt mod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_forge_toml_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta = r#"
|
||||
logoFile = "logo.png"
|
||||
|
||||
[[mods]]
|
||||
displayName = "Forge Mod"
|
||||
description = "A forge mod"
|
||||
"#;
|
||||
make_jar(
|
||||
&dir,
|
||||
"forge-mod.jar",
|
||||
&[("META-INF/mods.toml", meta.as_bytes())],
|
||||
);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "Forge Mod");
|
||||
assert_eq!(mods[0].description, "A forge mod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_neoforge_toml_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta = r#"
|
||||
logoFile = "logo.png"
|
||||
|
||||
[[mods]]
|
||||
displayName = "NeoForge Mod"
|
||||
description = "A neoforge mod"
|
||||
"#;
|
||||
make_jar(
|
||||
&dir,
|
||||
"neoforge-mod.jar",
|
||||
&[("META-INF/neoforge.mods.toml", meta.as_bytes())],
|
||||
);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "NeoForge Mod");
|
||||
assert_eq!(mods[0].description, "A neoforge mod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_mcmod_info_array() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#;
|
||||
make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "Legacy Mod");
|
||||
assert_eq!(mods[0].description, "An old forge mod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_reads_mcmod_info_modlist() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#;
|
||||
make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
assert_eq!(mods[0].name, "Wrapped Mod");
|
||||
assert_eq!(mods[0].description, "Has modList wrapper");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_prefers_fabric_over_forge() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#;
|
||||
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
||||
make_jar(
|
||||
&dir,
|
||||
"multi.jar",
|
||||
&[
|
||||
("fabric.mod.json", fabric.as_bytes()),
|
||||
("META-INF/mods.toml", forge.as_bytes()),
|
||||
],
|
||||
);
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods[0].name, "Fabric Name");
|
||||
}
|
||||
|
||||
#[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()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_path_from_value_string() {
|
||||
let val = serde_json::json!("assets/icon.png");
|
||||
assert_eq!(icon_path_from_value(&val), "assets/icon.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_path_from_value_map() {
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_path_from_value_null() {
|
||||
let val = serde_json::Value::Null;
|
||||
assert_eq!(icon_path_from_value(&val), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_entry_disable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
use super::mods::{ContentEntry, make_icon_pixels};
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub(crate) struct PackMcMeta {
|
||||
@@ -43,6 +43,36 @@ pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||
let is_dir = path.is_dir();
|
||||
let (name, description, icon_bytes) = if is_dir {
|
||||
read_pack_metadata_from_dir(path)
|
||||
} else {
|
||||
read_pack_metadata_from_zip(path)
|
||||
};
|
||||
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(super::mods::fallback_icon()));
|
||||
|
||||
let display_name = if name.is_empty() {
|
||||
file_stem.to_owned()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
|
||||
ContentEntry {
|
||||
file_stem: file_stem.to_owned(),
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path: path.to_path_buf(),
|
||||
icon_lines,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let packs_dir = instances_dir
|
||||
.join(instance_name)
|
||||
@@ -63,8 +93,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
let (enabled, file_stem) = if path.is_dir() {
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
@@ -72,27 +101,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
|
||||
continue;
|
||||
};
|
||||
|
||||
let (name, description, icon_bytes) = if is_dir {
|
||||
read_pack_metadata_from_dir(&path)
|
||||
} else {
|
||||
read_pack_metadata_from_zip(&path)
|
||||
};
|
||||
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(super::mods::fallback_icon()));
|
||||
|
||||
let display_name = if name.is_empty() { file_stem.clone() } else { name };
|
||||
entries.push(ContentEntry {
|
||||
file_stem,
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path,
|
||||
icon_lines,
|
||||
});
|
||||
entries.push(scan_one_resource_pack(&path, &file_stem, enabled));
|
||||
}
|
||||
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
@@ -194,10 +203,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
||||
let dir = tmp
|
||||
.join(instance)
|
||||
.join(".minecraft")
|
||||
.join("resourcepacks");
|
||||
let dir = tmp.join(instance).join(".minecraft").join("resourcepacks");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
@@ -3,8 +3,31 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
use super::resource_packs::{extract_description, PackMcMeta};
|
||||
use super::mods::{ContentEntry, make_icon_pixels};
|
||||
use super::resource_packs::{PackMcMeta, extract_description};
|
||||
|
||||
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||
let is_dir = path.is_dir();
|
||||
let (description, icon_bytes) = if is_dir {
|
||||
read_shader_metadata_from_dir(path)
|
||||
} else {
|
||||
read_shader_metadata_from_zip(path)
|
||||
};
|
||||
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
|
||||
ContentEntry {
|
||||
file_stem: file_stem.to_owned(),
|
||||
name: file_stem.to_owned(),
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path: path.to_path_buf(),
|
||||
icon_lines,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let shaders_dir = instances_dir
|
||||
@@ -26,8 +49,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
let (enabled, file_stem) = if path.is_dir() {
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
@@ -35,25 +57,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
|
||||
continue;
|
||||
};
|
||||
|
||||
let (description, icon_bytes) = if is_dir {
|
||||
read_shader_metadata_from_dir(&path)
|
||||
} else {
|
||||
read_shader_metadata_from_zip(&path)
|
||||
};
|
||||
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
|
||||
entries.push(ContentEntry {
|
||||
name: file_stem.clone(),
|
||||
file_stem,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path,
|
||||
icon_lines,
|
||||
});
|
||||
entries.push(scan_one_shader(&path, &file_stem, enabled));
|
||||
}
|
||||
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
|
||||
@@ -4,7 +4,27 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
use super::mods::{ContentEntry, make_icon_pixels};
|
||||
|
||||
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||
.or_else(|| Some(super::mods::fallback_icon_large()));
|
||||
|
||||
let description = world_description(path);
|
||||
|
||||
ContentEntry {
|
||||
name: file_stem.to_owned(),
|
||||
file_stem: file_stem.to_owned(),
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path: path.to_path_buf(),
|
||||
icon_lines,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let saves_dir = instances_dir
|
||||
@@ -31,24 +51,7 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntr
|
||||
};
|
||||
|
||||
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
|
||||
|
||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||
.or_else(|| Some(super::mods::fallback_icon_large()));
|
||||
|
||||
let description = world_description(&path);
|
||||
|
||||
entries.push(ContentEntry {
|
||||
name: file_stem.clone(),
|
||||
file_stem,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path,
|
||||
icon_lines,
|
||||
});
|
||||
entries.push(scan_one_world(&path, &file_stem, enabled));
|
||||
}
|
||||
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
@@ -77,14 +80,16 @@ fn world_description(world_dir: &Path) -> String {
|
||||
let mut lines = Vec::new();
|
||||
|
||||
if let Some(secs) = created
|
||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
||||
{
|
||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
|
||||
if let Some(secs) = modified
|
||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
||||
{
|
||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
|
||||
if dir_size > 0 {
|
||||
lines.push(format!("Size: {}", format_size(dir_size)));
|
||||
@@ -100,9 +105,10 @@ fn dir_size_approx(path: &Path) -> u64 {
|
||||
if let Ok(rd) = std::fs::read_dir(path) {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(meta) = entry.metadata()
|
||||
&& meta.is_file() {
|
||||
total += meta.len();
|
||||
}
|
||||
&& meta.is_file()
|
||||
{
|
||||
total += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check region folder too (main chunk data)
|
||||
@@ -181,8 +187,14 @@ mod tests {
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -59,8 +59,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
let (loader_opt, loader_version) = pack.loader();
|
||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||
|
||||
let name = instance_name_from_cfg(path)
|
||||
.unwrap_or_else(|| "Imported Pack".to_string());
|
||||
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
|
||||
|
||||
let (mod_count, override_count) = count_content_files(path)?;
|
||||
|
||||
|
||||
@@ -70,17 +70,20 @@ 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> {
|
||||
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()))?;
|
||||
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") {
|
||||
return Ok(PackFormat::Mrpack);
|
||||
}
|
||||
|
||||
// mmc-pack.json can be at root or one directory deep
|
||||
if archive.file_names().any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json")) {
|
||||
if archive
|
||||
.file_names()
|
||||
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
|
||||
{
|
||||
return Ok(PackFormat::Mmc);
|
||||
}
|
||||
|
||||
@@ -100,12 +103,20 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
|
||||
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
||||
let candidate = base.to_string();
|
||||
if !instances_dir.join(&candidate).join("instance.json").exists() {
|
||||
if !instances_dir
|
||||
.join(&candidate)
|
||||
.join("instance.json")
|
||||
.exists()
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
for n in 2..100 {
|
||||
let candidate = format!("{base} ({n})");
|
||||
if !instances_dir.join(&candidate).join("instance.json").exists() {
|
||||
if !instances_dir
|
||||
.join(&candidate)
|
||||
.join("instance.json")
|
||||
.exists()
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,8 +87,8 @@ async fn download_mod_files(
|
||||
index: &MrpackIndex,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let client = crate::net::HttpClient::new();
|
||||
let total = index.files.len();
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
// builds the full java command line and spawns minecraft as a child process.
|
||||
// handles classpath assembly, auth token injection, and log capture.
|
||||
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
|
||||
|
||||
mod patches;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::auth::{Account, AccountType};
|
||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -76,6 +80,17 @@ struct LoaderLibrary {
|
||||
name: String,
|
||||
}
|
||||
|
||||
struct GameAuth {
|
||||
username: String,
|
||||
uuid: String,
|
||||
token: String,
|
||||
user_type: String,
|
||||
}
|
||||
|
||||
fn account_can_launch(has_microsoft_account: bool, account: &Account) -> bool {
|
||||
account.account_type == AccountType::Microsoft || has_microsoft_account
|
||||
}
|
||||
|
||||
// mojang's library rules are a fun little state machine: each rule can allow
|
||||
// or disallow based on OS. if no rule matches the current OS, the library is
|
||||
// included only if no rule "dominated" (matched at all). yes, it's weird.
|
||||
@@ -107,6 +122,38 @@ fn lib_allowed(lib: &MetaLibrary) -> bool {
|
||||
!dominated
|
||||
}
|
||||
|
||||
fn build_game_args(
|
||||
config: &InstanceConfig,
|
||||
minecraft_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
asset_index_id: &str,
|
||||
auth: GameAuth,
|
||||
loader_game_args: Vec<String>,
|
||||
) -> Vec<String> {
|
||||
let mut game_args = vec![
|
||||
"--username".to_string(),
|
||||
auth.username,
|
||||
"--version".to_string(),
|
||||
config.game_version.clone(),
|
||||
"--gameDir".to_string(),
|
||||
minecraft_dir.to_string_lossy().into_owned(),
|
||||
"--assetsDir".to_string(),
|
||||
meta_dir.join("assets").to_string_lossy().into_owned(),
|
||||
"--assetIndex".to_string(),
|
||||
asset_index_id.to_string(),
|
||||
"--uuid".to_string(),
|
||||
auth.uuid,
|
||||
"--accessToken".to_string(),
|
||||
auth.token,
|
||||
"--userProperties".to_string(),
|
||||
"{}".to_string(),
|
||||
"--userType".to_string(),
|
||||
auth.user_type,
|
||||
];
|
||||
game_args.extend(loader_game_args);
|
||||
game_args
|
||||
}
|
||||
|
||||
pub async fn launch(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
@@ -193,15 +240,14 @@ pub async fn launch(
|
||||
.join(format!("{}.jar", config.game_version)),
|
||||
);
|
||||
|
||||
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap for
|
||||
// java 9+ compat. if present, prepend its patches to the classpath,
|
||||
// override the main class to use RFB's bootstrap, and add the required
|
||||
// --add-opens and system classloader flags.
|
||||
let (lwjgl3ify_jvm_args, main_class) = if matches!(config.loader, ModLoader::Forge) {
|
||||
let (jvm_args, override_main) = apply_lwjgl3ify_patches(&minecraft_dir, &mut classpath);
|
||||
(jvm_args, override_main.unwrap_or(main_class))
|
||||
// apply loader-specific patches (lwjgl3ify for old forge on java 9+)
|
||||
let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) {
|
||||
match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await {
|
||||
Some(p) => (p.jvm_args, p.main_class, p.extra_args),
|
||||
None => (Vec::new(), main_class, Vec::new()),
|
||||
}
|
||||
} else {
|
||||
(Vec::new(), main_class)
|
||||
(Vec::new(), main_class, Vec::new())
|
||||
};
|
||||
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
@@ -227,40 +273,52 @@ pub async fn launch(
|
||||
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")),
|
||||
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")),
|
||||
];
|
||||
jvm.extend(lwjgl3ify_jvm_args);
|
||||
jvm.extend(patch_jvm_args);
|
||||
jvm.extend(config.jvm_args.clone());
|
||||
|
||||
// resolve auth credentials, refreshing the microsoft token if needed.
|
||||
// falls back to a generic offline player if no account is configured.
|
||||
let mut account_store = crate::auth::AccountStore::load();
|
||||
let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store
|
||||
.active_account()
|
||||
.cloned()
|
||||
{
|
||||
Some(acc) => {
|
||||
let (token, new_refresh) = match acc.account_type {
|
||||
crate::auth::AccountType::Microsoft => {
|
||||
match crate::auth::refresh_and_get_token(&acc).await {
|
||||
Ok(pair) => pair,
|
||||
Err(e) => {
|
||||
return Err(LaunchError::Auth(format!("Authentication failed: {e}")));
|
||||
}
|
||||
if !account_can_launch(account_store.has_microsoft_account(), &acc) {
|
||||
return Err(LaunchError::Auth(
|
||||
"Offline accounts require a Microsoft account that owns Minecraft".to_owned(),
|
||||
));
|
||||
}
|
||||
let (token, new_refresh, new_expires) = match acc.account_type {
|
||||
AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await {
|
||||
Ok(triple) => triple,
|
||||
Err(e) => {
|
||||
return Err(LaunchError::Auth(format!("Authentication failed: {e}")));
|
||||
}
|
||||
}
|
||||
crate::auth::AccountType::Offline => ("0".to_string(), None),
|
||||
},
|
||||
AccountType::Offline => ("0".to_string(), None, None),
|
||||
};
|
||||
if let Some(new_rt) = new_refresh
|
||||
&& let Some(stored) = account_store
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.uuid == acc.uuid)
|
||||
{
|
||||
if let Some(stored) = account_store
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.uuid == acc.uuid)
|
||||
{
|
||||
let mut changed = false;
|
||||
if let Some(new_rt) = new_refresh {
|
||||
stored.refresh_token = Some(new_rt);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(expires) = new_expires {
|
||||
stored.cached_mc_token = Some(token.clone());
|
||||
stored.cached_mc_token_expires_at = Some(expires);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
account_store.save();
|
||||
}
|
||||
}
|
||||
let user_type = match acc.account_type {
|
||||
crate::auth::AccountType::Microsoft => "msa",
|
||||
crate::auth::AccountType::Offline => "legacy",
|
||||
AccountType::Microsoft => "msa",
|
||||
AccountType::Offline => "legacy",
|
||||
};
|
||||
(
|
||||
acc.username.clone(),
|
||||
@@ -269,33 +327,22 @@ pub async fn launch(
|
||||
user_type.to_string(),
|
||||
)
|
||||
}
|
||||
None => (
|
||||
"Player".to_string(),
|
||||
"00000000-0000-0000-0000-000000000000".to_string(),
|
||||
"0".to_string(),
|
||||
"legacy".to_string(),
|
||||
),
|
||||
None => return Err(LaunchError::Auth("No account selected".to_owned())),
|
||||
};
|
||||
|
||||
let mut game_args = vec![
|
||||
"--username".to_string(),
|
||||
mc_username,
|
||||
"--version".to_string(),
|
||||
config.game_version.clone(),
|
||||
"--gameDir".to_string(),
|
||||
minecraft_dir.to_string_lossy().into_owned(),
|
||||
"--assetsDir".to_string(),
|
||||
meta_dir.join("assets").to_string_lossy().into_owned(),
|
||||
"--assetIndex".to_string(),
|
||||
meta.asset_index.id.clone(),
|
||||
"--uuid".to_string(),
|
||||
mc_uuid,
|
||||
"--accessToken".to_string(),
|
||||
mc_token,
|
||||
"--userType".to_string(),
|
||||
mc_user_type,
|
||||
];
|
||||
game_args.extend(loader_game_args);
|
||||
let game_args = build_game_args(
|
||||
config,
|
||||
&minecraft_dir,
|
||||
meta_dir,
|
||||
&meta.asset_index.id,
|
||||
GameAuth {
|
||||
username: mc_username,
|
||||
uuid: mc_uuid,
|
||||
token: mc_token,
|
||||
user_type: mc_user_type,
|
||||
},
|
||||
loader_game_args,
|
||||
);
|
||||
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
crate::running::register_kill(&name, kill_tx);
|
||||
@@ -307,10 +354,24 @@ pub async fn launch(
|
||||
config.loader
|
||||
);
|
||||
|
||||
tracing::info!("[{}] Java: {}", name, java);
|
||||
tracing::info!("[{}] JVM args: {:?}", name, jvm);
|
||||
tracing::info!(
|
||||
"[{}] Classpath:\n{}",
|
||||
name,
|
||||
classpath
|
||||
.iter()
|
||||
.map(|p| p.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
tracing::info!("[{}] Main class: {}", name, main_class);
|
||||
|
||||
let mut cmd = tokio::process::Command::new(&java);
|
||||
cmd.args(&jvm);
|
||||
cmd.arg("-cp").arg(&cp_str);
|
||||
cmd.arg(&main_class);
|
||||
cmd.args(&extra_args);
|
||||
cmd.args(&game_args);
|
||||
cmd.current_dir(&minecraft_dir);
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
@@ -353,9 +414,10 @@ pub async fn launch(
|
||||
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut() {
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -369,9 +431,10 @@ pub async fn launch(
|
||||
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut() {
|
||||
let _ = writeln!(f, "[STDERR] {}", line);
|
||||
}
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "[STDERR] {}", line);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -411,99 +474,88 @@ pub async fn launch(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// lwjgl3ify (used by GTNH and other old forge modpacks) bundles a
|
||||
// forgePatches.zip with patched launchwrapper classes that fix the
|
||||
// URLClassLoader cast on java 9+. if we find it, extract the patches
|
||||
// and prepend them to the classpath so they shadow the vanilla classes.
|
||||
// also parses Add-Opens from the zip's manifest for the required
|
||||
// --add-opens flags.
|
||||
fn apply_lwjgl3ify_patches(
|
||||
minecraft_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> (Vec<String>, Option<String>) {
|
||||
let mods_dir = minecraft_dir.join("mods");
|
||||
let lwjgl3ify_jar = match find_lwjgl3ify_jar(&mods_dir) {
|
||||
Some(p) => p,
|
||||
None => return (Vec::new(), None),
|
||||
};
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::{Account, AccountType};
|
||||
use chrono::Utc;
|
||||
|
||||
let patches_dest = minecraft_dir.join(".forge-patches.zip");
|
||||
|
||||
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
|
||||
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
|
||||
// prepend so patched classes shadow vanilla launchwrapper
|
||||
classpath.insert(0, patches_dest.clone());
|
||||
|
||||
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
|
||||
|
||||
// RFB requires its own classloader to be the system classloader, and
|
||||
// its Main class handles bootstrapping into launchwrapper.
|
||||
// the other flags match lwjgl3ify's java9args.txt.
|
||||
jvm_args.extend([
|
||||
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader".to_string(),
|
||||
"-Dfile.encoding=UTF-8".to_string(),
|
||||
"--enable-native-access".to_string(),
|
||||
"ALL-UNNAMED".to_string(),
|
||||
]);
|
||||
|
||||
// also prepend the lwjgl3ify jar itself so RFB can find its plugin classes
|
||||
classpath.insert(1, lwjgl3ify_jar);
|
||||
|
||||
let main_class = "com.gtnewhorizons.retrofuturabootstrap.Main".to_string();
|
||||
|
||||
(jvm_args, Some(main_class))
|
||||
}
|
||||
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(mods_dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
|
||||
return Some(entry.path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let mut entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
std::fs::write(dest, &buf)
|
||||
}
|
||||
|
||||
fn parse_add_opens(patches_zip: &Path) -> Option<Vec<String>> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(patches_zip).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||
let mut manifest = String::new();
|
||||
entry.read_to_string(&mut manifest).ok()?;
|
||||
|
||||
// manifest continuation lines start with a single space
|
||||
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
|
||||
|
||||
let mut args = Vec::new();
|
||||
for line in manifest.lines() {
|
||||
if let Some(value) = line.strip_prefix("Add-Opens: ") {
|
||||
for module_package in value.split_whitespace() {
|
||||
args.push("--add-opens".to_string());
|
||||
args.push(format!("{module_package}=ALL-UNNAMED"));
|
||||
}
|
||||
fn test_config() -> InstanceConfig {
|
||||
InstanceConfig {
|
||||
name: "test".to_owned(),
|
||||
game_version: "1.7.10".to_owned(),
|
||||
loader: ModLoader::Forge,
|
||||
loader_version: Some("10.13.4.1614".to_owned()),
|
||||
created: Utc::now(),
|
||||
last_played: None,
|
||||
java_path: None,
|
||||
memory_max: None,
|
||||
memory_min: None,
|
||||
jvm_args: Vec::new(),
|
||||
resolution: None,
|
||||
}
|
||||
}
|
||||
|
||||
Some(args)
|
||||
fn test_account(account_type: AccountType) -> Account {
|
||||
Account {
|
||||
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
|
||||
username: "TestPlayer".to_owned(),
|
||||
account_type,
|
||||
active: true,
|
||||
refresh_token: Some("refresh".to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn game_args_include_empty_user_properties() {
|
||||
let args = build_game_args(
|
||||
&test_config(),
|
||||
Path::new("/instances/test/.minecraft"),
|
||||
Path::new("/meta"),
|
||||
"legacy",
|
||||
GameAuth {
|
||||
username: "TestPlayer".to_owned(),
|
||||
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
||||
token: "token".to_owned(),
|
||||
user_type: "msa".to_owned(),
|
||||
},
|
||||
vec![
|
||||
"--tweakClass".to_owned(),
|
||||
"cpw.mods.fml.common.launcher.FMLTweaker".to_owned(),
|
||||
],
|
||||
);
|
||||
|
||||
let position = args
|
||||
.iter()
|
||||
.position(|arg| arg == "--userProperties")
|
||||
.expect("game args should include --userProperties");
|
||||
assert_eq!(args.get(position + 1).map(String::as_str), Some("{}"));
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--tweakClass", "cpw.mods.fml.common.launcher.FMLTweaker"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_account_cannot_launch_without_microsoft_account() {
|
||||
let offline = test_account(AccountType::Offline);
|
||||
|
||||
assert!(!account_can_launch(false, &offline));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_account_can_launch_with_microsoft_account() {
|
||||
let offline = test_account(AccountType::Offline);
|
||||
|
||||
assert!(account_can_launch(true, &offline));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn microsoft_account_can_launch_without_offline_gate() {
|
||||
let microsoft = test_account(AccountType::Microsoft);
|
||||
|
||||
assert!(account_can_launch(false, µsoft));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
// classpath and jvm patches for legacy forge on java 9+.
|
||||
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that
|
||||
// replace the old URLClassLoader-based launcher with one that works on
|
||||
// modern java. this module handles extracting those patches, building
|
||||
// the right --add-opens flags, and swapping out the broken log4j jars.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j";
|
||||
|
||||
pub struct LwjglifyPatches {
|
||||
pub jvm_args: Vec<String>,
|
||||
pub main_class: String,
|
||||
// extra args inserted before game args (used by the shim to pass
|
||||
// the real main class name)
|
||||
pub extra_args: Vec<String>,
|
||||
}
|
||||
|
||||
// checks if lwjgl3ify is present in the mods folder, and if so:
|
||||
// 1. extracts forge patches from the lwjgl3ify jar
|
||||
// 2. prepends them to the classpath so they shadow vanilla launchwrapper
|
||||
// 3. parses --add-opens from the patches manifest
|
||||
// 4. replaces log4j 2.0-beta9 with prism's patched builds
|
||||
// 5. returns the jvm args and overridden main class
|
||||
pub async fn apply(
|
||||
minecraft_dir: &Path,
|
||||
lib_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> Option<LwjglifyPatches> {
|
||||
let mods_dir = minecraft_dir.join("mods");
|
||||
let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?;
|
||||
|
||||
// rfb only scans jars for plugin metadata. keeping the extracted
|
||||
// forgePatches payload as a zip makes it skip rfb-asm-safety and
|
||||
// rfb-modern-java, which GTNH needs on modern Java.
|
||||
let patches_dest = minecraft_dir.join(".forge-patches.jar");
|
||||
|
||||
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
|
||||
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
|
||||
return None;
|
||||
}
|
||||
|
||||
// prepend so patched classes shadow vanilla launchwrapper
|
||||
classpath.insert(0, patches_dest.clone());
|
||||
|
||||
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
|
||||
|
||||
// RFB requires its own classloader to be the system classloader, and
|
||||
// its Main class handles bootstrapping into launchwrapper.
|
||||
// the other flags match lwjgl3ify's java9args.txt.
|
||||
jvm_args.extend([
|
||||
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader"
|
||||
.to_string(),
|
||||
"-Dfile.encoding=UTF-8".to_string(),
|
||||
]);
|
||||
|
||||
// forge patches replace launchwrapper, asm, and old lwjgl2.
|
||||
// lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3
|
||||
// must be on the classpath (matching what prism does).
|
||||
strip_replaced_libs(classpath);
|
||||
add_lwjgl3(lib_dir, classpath);
|
||||
|
||||
replace_log4j_fixed(lib_dir, classpath).await;
|
||||
|
||||
// on java 24+, SecurityManager.getClassContext() was reimplemented to use
|
||||
// StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to
|
||||
// resolve stack frames, but StackWalker triggers class loading through
|
||||
// LaunchClassLoader, which debug-logs failures, which creates another
|
||||
// ThrowableProxy... infinite recursion. we break the loop by providing a
|
||||
// log4j config that sets the root level to INFO, so the debug() call in
|
||||
// LaunchClassLoader is a no-op and never creates a ThrowableProxy.
|
||||
write_log4j_config(minecraft_dir, &mut jvm_args);
|
||||
|
||||
// RfbSystemClassLoader discovers plugins differently depending on whether
|
||||
// the main class is loaded by the JVM directly or through the system
|
||||
// classloader's loadClass(). direct invocation misses the rfb-asm-safety
|
||||
// and rfb-modern-java plugins from forgePatches, causing
|
||||
// ClassCircularityErrors. we use a tiny shim jar that loads the real main
|
||||
// class through ClassLoader.getSystemClassLoader().loadClass(), matching
|
||||
// how prism's EntryPoint does it.
|
||||
let shim_path = deploy_shim(minecraft_dir);
|
||||
classpath.insert(0, shim_path);
|
||||
|
||||
Some(LwjglifyPatches {
|
||||
jvm_args,
|
||||
main_class: "MclShim".to_string(),
|
||||
extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()],
|
||||
})
|
||||
}
|
||||
|
||||
const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mcl-shim.jar"));
|
||||
|
||||
fn deploy_shim(minecraft_dir: &Path) -> PathBuf {
|
||||
let dest = minecraft_dir.join(".mcl-shim.jar");
|
||||
if let Err(e) = std::fs::write(&dest, SHIM_JAR) {
|
||||
tracing::warn!("Failed to write mcl-shim.jar: {e}");
|
||||
}
|
||||
dest
|
||||
}
|
||||
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(mods_dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
|
||||
return Some(entry.path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let mut entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
std::fs::write(dest, &buf)
|
||||
}
|
||||
|
||||
fn parse_add_opens(patches_archive: &Path) -> Option<Vec<String>> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(patches_archive).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||
let mut manifest = String::new();
|
||||
entry.read_to_string(&mut manifest).ok()?;
|
||||
|
||||
// manifest continuation lines start with a single space
|
||||
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
|
||||
|
||||
let mut args = Vec::new();
|
||||
for line in manifest.lines() {
|
||||
if let Some(value) = line.strip_prefix("Add-Opens: ") {
|
||||
for module_package in value.split_whitespace() {
|
||||
args.push("--add-opens".to_string());
|
||||
args.push(format!("{module_package}=ALL-UNNAMED"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(args)
|
||||
}
|
||||
|
||||
// strips libraries from the classpath that are replaced by forge patches
|
||||
// or not needed with lwjgl3ify. matches what prism's component system does:
|
||||
// no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs.
|
||||
fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||
let replaced = [
|
||||
"launchwrapper-",
|
||||
"asm-all-",
|
||||
"lwjgl-2.",
|
||||
"lwjgl_util-",
|
||||
"commons-compress-",
|
||||
"commons-io-",
|
||||
"guava-15.",
|
||||
];
|
||||
|
||||
classpath.retain(|entry| {
|
||||
let name = entry
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
let dominated = replaced.iter().any(|prefix| name.starts_with(prefix));
|
||||
if dominated {
|
||||
tracing::info!("Stripping {name} from classpath (replaced by forge-patches)");
|
||||
}
|
||||
!dominated
|
||||
});
|
||||
}
|
||||
|
||||
// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls
|
||||
// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system
|
||||
// classpath for this to work. prism includes these via its org.lwjgl3
|
||||
// component; we add them from the meta library cache.
|
||||
fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec<PathBuf>) {
|
||||
let lwjgl3_modules = [
|
||||
"lwjgl",
|
||||
"lwjgl-freetype",
|
||||
"lwjgl-glfw",
|
||||
"lwjgl-jemalloc",
|
||||
"lwjgl-openal",
|
||||
"lwjgl-opengl",
|
||||
"lwjgl-stb",
|
||||
"lwjgl-tinyfd",
|
||||
];
|
||||
|
||||
let os_classifier = match std::env::consts::OS {
|
||||
"macos" => "natives-macos",
|
||||
"windows" => "natives-windows",
|
||||
_ => "natives-linux",
|
||||
};
|
||||
|
||||
// insert lwjgl3 jars right after forge patches (position 1+)
|
||||
let mut insert_pos = 1.min(classpath.len());
|
||||
for module in &lwjgl3_modules {
|
||||
let base = if *module == "lwjgl" {
|
||||
lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
|
||||
} else {
|
||||
lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module))
|
||||
};
|
||||
if base.exists() {
|
||||
classpath.insert(insert_pos, base);
|
||||
insert_pos += 1;
|
||||
}
|
||||
|
||||
// natives
|
||||
let natives = if *module == "lwjgl" {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar"
|
||||
))
|
||||
} else {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar",
|
||||
module, os_classifier
|
||||
))
|
||||
};
|
||||
if natives.exists() {
|
||||
classpath.insert(insert_pos, natives);
|
||||
insert_pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1);
|
||||
}
|
||||
|
||||
// writes a log4j2.xml config that sets the root logger to INFO. this
|
||||
// prevents LaunchClassLoader's debug() call from ever firing, which
|
||||
// avoids the ThrowableProxy -> SecurityManager -> StackWalker infinite
|
||||
// recursion on java 24+. the config is written to .minecraft/ and
|
||||
// pointed to via -Dlog4j.configurationFile.
|
||||
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
let config_path = minecraft_dir.join(".mcl-log4j2.xml");
|
||||
let config = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<Console name="SysOut" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level] [%logger]: %msg%n"/>
|
||||
</Console>
|
||||
<Queue name="ServerGuiConsole">
|
||||
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
|
||||
</Queue>
|
||||
<RollingRandomAccessFile name="File" fileName="logs/latest.log"
|
||||
filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy/>
|
||||
<OnStartupTriggeringPolicy/>
|
||||
</Policies>
|
||||
</RollingRandomAccessFile>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="info">
|
||||
<AppenderRef ref="SysOut"/>
|
||||
<AppenderRef ref="File"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
"#;
|
||||
|
||||
if let Err(e) = std::fs::write(&config_path, config) {
|
||||
tracing::warn!("Failed to write log4j2 config: {e}");
|
||||
return;
|
||||
}
|
||||
|
||||
jvm_args.push(format!(
|
||||
"-Dlog4j.configurationFile={}",
|
||||
config_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
// replaces log4j-api and log4j-core 2.0-beta9 in the classpath with
|
||||
// prism's patched "-fixed" builds. the vanilla 2.0-beta9 has a bug
|
||||
// where ThrowableProxy calls SecurityManager.getClassContext() which
|
||||
// on java 24+ uses StackWalker internally, triggering class loading
|
||||
// through LaunchClassLoader, which triggers more logging, infinite
|
||||
// recursion, stack overflow. the fixed builds patch this out.
|
||||
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
let replacements = [
|
||||
(
|
||||
"log4j-api-2.0-beta9.jar",
|
||||
"org/apache/logging/log4j/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar",
|
||||
format!("{LOG4J_FIXED_BASE}/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar"),
|
||||
),
|
||||
(
|
||||
"log4j-core-2.0-beta9.jar",
|
||||
"org/apache/logging/log4j/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar",
|
||||
format!("{LOG4J_FIXED_BASE}/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar"),
|
||||
),
|
||||
];
|
||||
|
||||
for (old_name, fixed_rel, url) in &replacements {
|
||||
let fixed_path = lib_dir.join(fixed_rel);
|
||||
|
||||
if !fixed_path.exists() {
|
||||
tracing::info!("Downloading patched {old_name}...");
|
||||
if let Some(parent) = fixed_path.parent() {
|
||||
let _ = tokio::fs::create_dir_all(parent).await;
|
||||
}
|
||||
let client = crate::net::HttpClient::new();
|
||||
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
|
||||
tracing::error!(
|
||||
"Failed to download patched {old_name}: {e}, continuing with unpatched version"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for entry in classpath.iter_mut() {
|
||||
if entry
|
||||
.file_name()
|
||||
.is_some_and(|n| n.to_string_lossy() == *old_name)
|
||||
{
|
||||
tracing::info!("Replacing {old_name} with patched version");
|
||||
*entry = fixed_path.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{fabric as fabric_api, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, fabric as fabric_api};
|
||||
|
||||
pub struct FabricInstaller;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{forge as forge_api, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, forge as forge_api};
|
||||
|
||||
pub struct ForgeInstaller;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{neoforge as neoforge_api, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
|
||||
|
||||
pub struct NeoForgeInstaller;
|
||||
|
||||
@@ -65,7 +65,11 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
fn save_neoforge_profile(instance_dir: &Path, meta_dir: &Path, loader_version: &str) -> Result<(), NetError> {
|
||||
fn save_neoforge_profile(
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
loader_version: &str,
|
||||
) -> Result<(), NetError> {
|
||||
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)
|
||||
|
||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{quilt as quilt_api, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, quilt as quilt_api};
|
||||
|
||||
pub struct QuiltInstaller;
|
||||
|
||||
@@ -41,8 +41,7 @@ impl ModLoaderInstaller for QuiltInstaller {
|
||||
_instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let profile =
|
||||
quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
|
||||
let profile = quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
|
||||
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
|
||||
|
||||
super::save_profile_json(
|
||||
|
||||
@@ -8,7 +8,7 @@ use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{mojang, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, mojang};
|
||||
|
||||
pub struct VanillaInstaller;
|
||||
|
||||
|
||||
+37
-10
@@ -137,8 +137,7 @@ impl InstanceManager {
|
||||
}
|
||||
}
|
||||
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
|
||||
.await?;
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
@@ -217,15 +216,16 @@ impl InstanceManager {
|
||||
|
||||
let config_path = new_dir.join("instance.json");
|
||||
if let Ok(data) = std::fs::read_to_string(&config_path)
|
||||
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data) {
|
||||
config.name = new_name.to_string();
|
||||
if let Ok(json) = serde_json::to_string_pretty(&config) {
|
||||
let _ = std::fs::write(&config_path, json);
|
||||
}
|
||||
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
||||
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
||||
}
|
||||
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data)
|
||||
{
|
||||
config.name = new_name.to_string();
|
||||
if let Ok(json) = serde_json::to_string_pretty(&config) {
|
||||
let _ = std::fs::write(&config_path, json);
|
||||
}
|
||||
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
||||
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -387,6 +387,33 @@ mod tests {
|
||||
std::fs::remove_dir_all(&tmp).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_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();
|
||||
std::fs::write(
|
||||
instance_dir.join("instance.json"),
|
||||
r#"{
|
||||
"name": "test-memory",
|
||||
"game_version": "1.7.10",
|
||||
"loader": "forge",
|
||||
"loader_version": "10.13.4.1614",
|
||||
"created": "2026-04-20T18:04:25.567993893Z",
|
||||
"memory_max": 8,
|
||||
"memory_min": 512
|
||||
}"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
let all = manager.load_all();
|
||||
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();
|
||||
|
||||
+9
-3
@@ -10,8 +10,14 @@ pub mod manager;
|
||||
pub mod models;
|
||||
pub mod screenshots;
|
||||
|
||||
pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, scan_shaders, scan_worlds};
|
||||
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,
|
||||
};
|
||||
pub use launch::LaunchError;
|
||||
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
|
||||
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
|
||||
pub use manager::{InstanceError, InstanceManager};
|
||||
pub use models::{InstanceConfig, ModLoader};
|
||||
pub use models::{InstanceConfig, ModLoader, normalize_memory_value};
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -34,14 +35,90 @@ pub struct InstanceConfig {
|
||||
pub loader: ModLoader,
|
||||
pub loader_version: Option<String>,
|
||||
pub created: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub last_played: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub java_path: Option<String>,
|
||||
#[serde(default, deserialize_with = "deserialize_optional_memory")]
|
||||
pub memory_max: Option<String>,
|
||||
#[serde(default, deserialize_with = "deserialize_optional_memory")]
|
||||
pub memory_min: Option<String>,
|
||||
#[serde(default)]
|
||||
pub jvm_args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub resolution: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
pub fn normalize_memory_value(raw: &str) -> Option<String> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (digits, suffix) = match trimmed.chars().last() {
|
||||
Some(c) if c.is_ascii_alphabetic() => (&trimmed[..trimmed.len() - c.len_utf8()], Some(c)),
|
||||
Some(_) => (trimmed, None),
|
||||
None => return None,
|
||||
};
|
||||
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value = digits.parse::<u64>().ok()?;
|
||||
if value == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
match suffix.map(|c| c.to_ascii_uppercase()) {
|
||||
Some(unit @ ('K' | 'M' | 'G')) => Some(format!("{value}{unit}")),
|
||||
Some(_) => None,
|
||||
None => memory_number_to_string(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = Option::<Value>::deserialize(deserializer)?;
|
||||
match value {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(raw)) => Ok(normalize_memory_value(&raw)),
|
||||
Some(Value::Number(number)) => {
|
||||
let number = if let Some(value) = number.as_u64() {
|
||||
value
|
||||
} else if let Some(value) = number.as_i64() {
|
||||
let Ok(value) = u64::try_from(value) else {
|
||||
return Ok(None);
|
||||
};
|
||||
value
|
||||
} else {
|
||||
let Some(value) = number.as_f64() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !value.is_finite() || value.fract() != 0.0 || value < 0.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
value as u64
|
||||
};
|
||||
Ok(memory_number_to_string(number))
|
||||
}
|
||||
Some(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_number_to_string(value: u64) -> Option<String> {
|
||||
if value == 0 {
|
||||
return None;
|
||||
}
|
||||
if value < 128 {
|
||||
Some(format!("{value}G"))
|
||||
} else {
|
||||
Some(format!("{value}M"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -68,4 +145,58 @@ mod tests {
|
||||
assert_eq!(parsed.loader, config.loader);
|
||||
assert_eq!(parsed.resolution, config.resolution);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_config_accepts_numeric_memory() {
|
||||
let json = r#"
|
||||
{
|
||||
"name": "test",
|
||||
"game_version": "1.7.10",
|
||||
"loader": "forge",
|
||||
"loader_version": "10.13.4.1614",
|
||||
"created": "2026-04-20T18:04:25.567993893Z",
|
||||
"memory_max": 8,
|
||||
"memory_min": 512
|
||||
}
|
||||
"#;
|
||||
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
|
||||
assert_eq!(parsed.memory_max.as_deref(), Some("8G"));
|
||||
assert_eq!(parsed.memory_min.as_deref(), Some("512M"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_memory_value_handles_bare_numbers() {
|
||||
assert_eq!(normalize_memory_value("8").as_deref(), Some("8G"));
|
||||
assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M"));
|
||||
assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G"));
|
||||
assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M"));
|
||||
assert_eq!(normalize_memory_value(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_config_ignores_invalid_memory_values() {
|
||||
let json = r#"
|
||||
{
|
||||
"name": "test",
|
||||
"game_version": "1.7.10",
|
||||
"loader": "forge",
|
||||
"loader_version": "10.13.4.1614",
|
||||
"created": "2026-04-20T18:04:25.567993893Z",
|
||||
"memory_max": ["8G"],
|
||||
"memory_min": "8GB"
|
||||
}
|
||||
"#;
|
||||
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
|
||||
assert_eq!(parsed.memory_max, None);
|
||||
assert_eq!(parsed.memory_min, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_memory_value_rejects_invalid_values() {
|
||||
assert_eq!(normalize_memory_value("0"), None);
|
||||
assert_eq!(normalize_memory_value("-1"), None);
|
||||
assert_eq!(normalize_memory_value("1.5G"), None);
|
||||
assert_eq!(normalize_memory_value("8GB"), None);
|
||||
assert_eq!(normalize_memory_value("banana"), None);
|
||||
}
|
||||
}
|
||||
@@ -76,9 +76,11 @@ mod tests {
|
||||
}
|
||||
let lines = get_all(name);
|
||||
assert_eq!(lines.len(), MAX_LINES);
|
||||
assert!(lines
|
||||
.last()
|
||||
.unwrap()
|
||||
.contains(&format!("{}", MAX_LINES + 99)));
|
||||
assert!(
|
||||
lines
|
||||
.last()
|
||||
.unwrap()
|
||||
.contains(&format!("{}", MAX_LINES + 99))
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -6,7 +6,7 @@ use std::path::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::instance::loader::GameVersion;
|
||||
use crate::net::{download_file, HttpClient, NetError};
|
||||
use crate::net::{HttpClient, NetError, download_file};
|
||||
use crate::tui::progress::set_sub_action;
|
||||
|
||||
const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2";
|
||||
@@ -152,5 +152,4 @@ mod tests {
|
||||
Err(e) => panic!("fetch_fabric_game_versions failed: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+20
-23
@@ -87,10 +87,7 @@ 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,
|
||||
);
|
||||
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
|
||||
match download_file(client, &url, dest, |downloaded, total| {
|
||||
crate::tui::progress::set_progress(downloaded, total);
|
||||
})
|
||||
@@ -179,25 +176,23 @@ pub(crate) async fn install_forge_from_profile(
|
||||
set_action("Installing legacy Forge from profile...");
|
||||
|
||||
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 mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| NetError::Parse(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}"))
|
||||
})?;
|
||||
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| NetError::Parse(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 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")
|
||||
@@ -221,9 +216,11 @@ pub(crate) async fn install_forge_from_profile(
|
||||
.ok_or_else(|| NetError::Parse("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!("Invalid maven coord in install.path: {install_path_coord}"))
|
||||
let universal_maven_path =
|
||||
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
|
||||
NetError::Parse(format!(
|
||||
"Invalid maven coord in install.path: {install_path_coord}"
|
||||
))
|
||||
})?;
|
||||
|
||||
set_sub_action("Extracting universal JAR...");
|
||||
@@ -234,7 +231,9 @@ pub(crate) async fn install_forge_from_profile(
|
||||
|
||||
{
|
||||
let mut entry = archive.by_name(file_path).map_err(|e| {
|
||||
NetError::Parse(format!("Universal JAR '{file_path}' not found in installer: {e}"))
|
||||
NetError::Parse(format!(
|
||||
"Universal JAR '{file_path}' not found in installer: {e}"
|
||||
))
|
||||
})?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
@@ -252,9 +251,7 @@ 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(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+6
-1
@@ -90,7 +90,12 @@ pub async fn download_file(
|
||||
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);
|
||||
tracing::warn!(
|
||||
"retrying download (attempt {}/{}): {}",
|
||||
attempt + 1,
|
||||
MAX_RETRIES + 1,
|
||||
url
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
|
||||
}
|
||||
|
||||
|
||||
+9
-3
@@ -55,7 +55,9 @@ use crate::instance::models::ModLoader;
|
||||
|
||||
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
|
||||
// checks in priority order and returns the first match.
|
||||
pub fn loader_from_dependencies(deps: &HashMap<String, String>) -> (Option<ModLoader>, Option<String>) {
|
||||
pub fn loader_from_dependencies(
|
||||
deps: &HashMap<String, String>,
|
||||
) -> (Option<ModLoader>, Option<String>) {
|
||||
let loaders = [
|
||||
("fabric-loader", ModLoader::Fabric),
|
||||
("forge", ModLoader::Forge),
|
||||
@@ -108,7 +110,8 @@ pub async fn fetch_versions(
|
||||
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||
let url = format!(
|
||||
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
|
||||
API_BASE, url_encode(slug_or_id)
|
||||
API_BASE,
|
||||
url_encode(slug_or_id)
|
||||
);
|
||||
client.get_json(&url).await
|
||||
}
|
||||
@@ -187,7 +190,10 @@ mod tests {
|
||||
fn game_version_from_deps() {
|
||||
let mut deps = HashMap::new();
|
||||
deps.insert("minecraft".to_string(), "1.21.4".to_string());
|
||||
assert_eq!(game_version_from_dependencies(&deps), Some("1.21.4".to_string()));
|
||||
assert_eq!(
|
||||
game_version_from_dependencies(&deps),
|
||||
Some("1.21.4".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+5
-4
@@ -78,10 +78,11 @@ pub fn register_kill(name: &str, tx: tokio::sync::oneshot::Sender<()>) {
|
||||
|
||||
pub fn send_kill(name: &str) -> bool {
|
||||
if let Ok(mut map) = KILL_SENDERS.lock()
|
||||
&& let Some(tx) = map.remove(name) {
|
||||
let _ = tx.send(());
|
||||
return true;
|
||||
}
|
||||
&& let Some(tx) = map.remove(name)
|
||||
{
|
||||
let _ = tx.send(());
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
+70
-18
@@ -3,9 +3,9 @@ use crossterm::event::{self, Event};
|
||||
use ratatui::crossterm::event::KeyEventKind;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::Tui;
|
||||
use super::app::{App, PENDING_INSTANCES};
|
||||
use super::widgets::{self, popups::import_modpack, popups::new_instance};
|
||||
use super::Tui;
|
||||
use crate::instance::InstanceManager;
|
||||
use crate::tui::error_buffer;
|
||||
use crate::tui::progress;
|
||||
@@ -31,13 +31,13 @@ impl App {
|
||||
self.drain_pending_instances();
|
||||
self.drain_pending_last_played();
|
||||
self.mods_state.drain_pending();
|
||||
self.mods_state.try_rescan();
|
||||
self.mods_state.drain_watcher();
|
||||
self.resource_packs_state.drain_pending();
|
||||
self.resource_packs_state.try_rescan();
|
||||
self.resource_packs_state.drain_watcher();
|
||||
self.shaders_state.drain_pending();
|
||||
self.shaders_state.try_rescan();
|
||||
self.shaders_state.drain_watcher();
|
||||
self.worlds_state.drain_pending();
|
||||
self.worlds_state.try_rescan();
|
||||
self.worlds_state.drain_watcher();
|
||||
self.logs_state.drain_pending();
|
||||
self.logs_state.try_rescan();
|
||||
self.account_state.drain_auth_result();
|
||||
@@ -54,8 +54,10 @@ impl App {
|
||||
terminal.draw(|frame| self.render_frame(frame))?;
|
||||
self.handle_events().wrap_err("handle events failed")?;
|
||||
|
||||
if let Some(path) = self.pending_editor.take() {
|
||||
Self::run_editor(terminal, &path);
|
||||
if let Some(path) = self.pending_editor.take()
|
||||
&& Self::run_editor(terminal, &path)
|
||||
{
|
||||
self.reload_edited_config(&path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -149,12 +151,12 @@ impl App {
|
||||
// spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc)
|
||||
// gotta leave the alternate screen and restore it after, otherwise the
|
||||
// editor fights with ratatui for the terminal. GUI editors just get spawned detached.
|
||||
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
|
||||
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool {
|
||||
use ratatui::crossterm::{
|
||||
terminal::{
|
||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||
},
|
||||
ExecutableCommand,
|
||||
terminal::{
|
||||
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
|
||||
},
|
||||
};
|
||||
use std::io::stdout;
|
||||
|
||||
@@ -199,20 +201,70 @@ impl App {
|
||||
|
||||
if let Err(e) = result {
|
||||
tracing::error!("Failed to open editor: {}", e);
|
||||
return false;
|
||||
}
|
||||
} else { if let Err(e) = std::process::Command::new(&editor)
|
||||
.arg(path)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn() {
|
||||
tracing::error!("Failed to open editor: {}", e);
|
||||
}}
|
||||
true
|
||||
} else {
|
||||
if let Err(e) = std::process::Command::new(&editor)
|
||||
.arg(path)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
tracing::error!("Failed to open editor: {}", e);
|
||||
return false;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn reload_edited_config(&mut self, path: &std::path::Path) {
|
||||
if path.file_name().and_then(|n| n.to_str()) != Some("instance.json") {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(name) = path
|
||||
.parent()
|
||||
.and_then(|p| p.file_name())
|
||||
.and_then(|n| n.to_str())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
match self.instance_manager.load_one(name) {
|
||||
Ok(config) => {
|
||||
self.instances_state.replace_instance(name, config);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to reload edited instance '{}': {}", name, e);
|
||||
error_buffer::push_error(error_buffer::ErrorEvent {
|
||||
id: 0,
|
||||
level: tracing::Level::ERROR,
|
||||
message: format!("Failed to reload edited instance '{name}': {e}"),
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
|
||||
use crate::instance::launch;
|
||||
use crate::running;
|
||||
|
||||
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,
|
||||
message: format!("Failed to load instance '{}': {e}", instance.name),
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
running::set_state(&instance.name, running::RunState::Authenticating);
|
||||
|
||||
let instances_dir = self.instance_manager.instances_dir.clone();
|
||||
|
||||
+14
-6
@@ -6,7 +6,9 @@
|
||||
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use super::app::{App, FocusedArea};
|
||||
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, WidgetKey};
|
||||
use super::widgets::{
|
||||
self, WidgetKey, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
|
||||
};
|
||||
use crate::tui::error_buffer;
|
||||
|
||||
impl App {
|
||||
@@ -15,6 +17,9 @@ impl App {
|
||||
if self.focused == FocusedArea::OverviewExpanded {
|
||||
if self.log_overlay_search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
self.log_overlay_search.confirm();
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.log_overlay_search.deactivate();
|
||||
}
|
||||
@@ -103,7 +108,8 @@ impl App {
|
||||
return Ok(());
|
||||
}
|
||||
} else if self.content_tab == widgets::content::ContentTab::Worlds {
|
||||
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
|
||||
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
@@ -116,9 +122,10 @@ impl App {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(state) = state
|
||||
&& widgets::content::list::handle_key(&key_event, state) {
|
||||
return Ok(());
|
||||
}
|
||||
&& widgets::content::list::handle_key(&key_event, state)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,7 +185,8 @@ impl App {
|
||||
import_modpack::handle_key(&key_event, &mut self.instances_state);
|
||||
}
|
||||
_ => {
|
||||
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some() {
|
||||
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some()
|
||||
{
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
let new_name = self.instances_state.renaming.take().unwrap_or_default();
|
||||
|
||||
+8
-6
@@ -34,10 +34,10 @@ fn push_app_log(line: String) {
|
||||
}
|
||||
}
|
||||
|
||||
// returns a WorkerGuard that must be held alive for the duration of the
|
||||
// program, otherwise the file logging thread gets dropped immediately.
|
||||
// yes, you will spend 30 minutes debugging "why aren't my logs writing"
|
||||
// before you remember this. ask me how i know.
|
||||
// returns a WorkerGuard that must be held alive for the duration of the
|
||||
// program, otherwise the file logging thread gets dropped immediately.
|
||||
// yes, you will spend 30 minutes debugging "why aren't my logs writing"
|
||||
// before you remember this. ask me how i know.
|
||||
pub fn init() -> WorkerGuard {
|
||||
let log_dir = match dirs_next::cache_dir() {
|
||||
Some(d) => d.join("mcl"),
|
||||
@@ -54,12 +54,14 @@ pub fn init() -> WorkerGuard {
|
||||
}
|
||||
}
|
||||
|
||||
let file_appender = tracing_appender::rolling::daily(&log_dir, "mcl.log");
|
||||
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
|
||||
let file_appender = tracing_appender::rolling::never(&log_dir, format!("mcl_{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();
|
||||
.from_env_lossy()
|
||||
.add_directive("mc_instance=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") {
|
||||
|
||||
@@ -12,6 +12,18 @@ pub mod widgets;
|
||||
pub type Tui = ratatui::DefaultTerminal;
|
||||
|
||||
pub async fn show() -> color_eyre::Result<()> {
|
||||
// restore the terminal before printing a panic. without this, a panic
|
||||
// leaves raw mode + alternate screen active and looks like a freeze
|
||||
let default_hook = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let _ = crossterm::execute!(
|
||||
std::io::stdout(),
|
||||
crossterm::event::PopKeyboardEnhancementFlags
|
||||
);
|
||||
ratatui::restore();
|
||||
default_hook(info);
|
||||
}));
|
||||
|
||||
let mut terminal = ratatui::init();
|
||||
|
||||
// opt into enhanced keyboard protocol to distinguish key press vs release
|
||||
|
||||
+34
-15
@@ -4,22 +4,24 @@
|
||||
// popups and error toasts render on top of everything.
|
||||
|
||||
use ratatui::{
|
||||
layout::{Constraint, Direction, Layout},
|
||||
Frame,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
};
|
||||
use tachyonfx::{fx, EffectRenderer, Interpolation, Motion};
|
||||
use tachyonfx::{EffectRenderer, Interpolation, Motion, fx};
|
||||
|
||||
use super::app::{App, ErrorEffectState, FocusedArea};
|
||||
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance};
|
||||
use super::widgets::{
|
||||
self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
|
||||
};
|
||||
use crate::tui::error_buffer;
|
||||
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
|
||||
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
|
||||
use crate::tui::widgets::popups::confirm::{ConfirmPopup, confirm_popup_area};
|
||||
use crate::tui::widgets::popups::error::{ErrorPopup, popup_area};
|
||||
|
||||
impl App {
|
||||
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
|
||||
use crate::config::theme::THEME;
|
||||
use ratatui::widgets::Block;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::widgets::Block;
|
||||
|
||||
let theme = THEME.as_ref();
|
||||
frame.render_widget(
|
||||
@@ -29,10 +31,7 @@ impl App {
|
||||
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage(20),
|
||||
Constraint::Percentage(80),
|
||||
])
|
||||
.constraints([Constraint::Percentage(20), Constraint::Percentage(80)])
|
||||
.split(frame.area());
|
||||
|
||||
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
|
||||
@@ -136,7 +135,7 @@ impl App {
|
||||
// full-screen log viewer with search highlighting and auto-scroll.
|
||||
// auto-sticks to the bottom unless the user scrolled up manually
|
||||
fn render_log_overlay(&mut self, frame: &mut Frame) {
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::tui::logging::get_app_logs;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Margin},
|
||||
@@ -247,7 +246,13 @@ impl App {
|
||||
for event in events {
|
||||
self.error_effects.entry(event.id).or_insert_with(|| {
|
||||
ErrorEffectState::SlidingIn(
|
||||
fx::slide_in(Motion::RightToLeft, 4, 0, bg, (250, Interpolation::CubicOut)),
|
||||
fx::slide_in(
|
||||
Motion::RightToLeft,
|
||||
4,
|
||||
0,
|
||||
bg,
|
||||
(250, Interpolation::CubicOut),
|
||||
),
|
||||
std::time::Instant::now(),
|
||||
)
|
||||
});
|
||||
@@ -278,7 +283,13 @@ impl App {
|
||||
.or_insert(ErrorEffectState::Idle);
|
||||
if !matches!(entry, ErrorEffectState::FadingOut(..)) {
|
||||
*entry = ErrorEffectState::FadingOut(
|
||||
fx::slide_out(Motion::LeftToRight, 4, 0, bg, (fly_out_ms as u32, Interpolation::CubicIn)),
|
||||
fx::slide_out(
|
||||
Motion::LeftToRight,
|
||||
4,
|
||||
0,
|
||||
bg,
|
||||
(fly_out_ms as u32, Interpolation::CubicIn),
|
||||
),
|
||||
std::time::Instant::now(),
|
||||
);
|
||||
}
|
||||
@@ -289,7 +300,11 @@ impl App {
|
||||
ErrorEffectState::SlidingIn(effect, started) => {
|
||||
let dt = started.elapsed().as_millis() as u32;
|
||||
if effect.running() {
|
||||
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
|
||||
frame.render_effect(
|
||||
effect,
|
||||
area,
|
||||
tachyonfx::Duration::from_millis(dt.min(32)),
|
||||
);
|
||||
*started = std::time::Instant::now();
|
||||
} else {
|
||||
*effect_state = ErrorEffectState::Idle;
|
||||
@@ -299,7 +314,11 @@ impl App {
|
||||
ErrorEffectState::FadingOut(effect, started) => {
|
||||
let dt = started.elapsed().as_millis() as u32;
|
||||
if effect.running() {
|
||||
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
|
||||
frame.render_effect(
|
||||
effect,
|
||||
area,
|
||||
tachyonfx::Duration::from_millis(dt.min(32)),
|
||||
);
|
||||
*started = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
+78
-38
@@ -6,17 +6,17 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph, Widget},
|
||||
Frame,
|
||||
};
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::tui::app::FocusedArea;
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
|
||||
use super::styled_title;
|
||||
|
||||
@@ -26,6 +26,7 @@ pub enum AddMode {
|
||||
None,
|
||||
ChooseType,
|
||||
OfflineNameInput(String),
|
||||
OfflineBlocked,
|
||||
ConfirmDelete(usize),
|
||||
DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo,
|
||||
@@ -59,11 +60,10 @@ impl AccountState {
|
||||
// can't block on it because the TUI needs to keep rendering
|
||||
pub fn drain_auth_result(&mut self) {
|
||||
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
|
||||
let result = match pending.lock() { Ok(mut slot) => {
|
||||
slot.take()
|
||||
} _ => {
|
||||
None
|
||||
}};
|
||||
let result = match pending.lock() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(result) = result {
|
||||
match result {
|
||||
@@ -99,7 +99,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
true
|
||||
}
|
||||
KeyCode::Char('o') | KeyCode::Char('2') => {
|
||||
state.add_mode = AddMode::OfflineNameInput(String::new());
|
||||
state.add_mode = if state.store.has_microsoft_account() {
|
||||
AddMode::OfflineNameInput(String::new())
|
||||
} else {
|
||||
AddMode::OfflineBlocked
|
||||
};
|
||||
true
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
@@ -112,13 +116,19 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
KeyCode::Enter => {
|
||||
let trimmed = name.trim().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
let account = auth::create_offline_account(&trimmed);
|
||||
state.store.add(account);
|
||||
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() {
|
||||
state.list_state.selected = Some(0);
|
||||
if state.store.has_microsoft_account() {
|
||||
let account = auth::create_offline_account(&trimmed);
|
||||
state.store.add(account);
|
||||
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() {
|
||||
state.list_state.selected = Some(0);
|
||||
}
|
||||
state.add_mode = AddMode::None;
|
||||
} else {
|
||||
state.add_mode = AddMode::OfflineBlocked;
|
||||
}
|
||||
} else {
|
||||
state.add_mode = AddMode::None;
|
||||
}
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
@@ -139,6 +149,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
AddMode::OfflineBlocked => match key_event.code {
|
||||
KeyCode::Enter | KeyCode::Esc => {
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
AddMode::DeviceCodeWaiting { .. } => match key_event.code {
|
||||
KeyCode::Esc => {
|
||||
state.add_mode = AddMode::None;
|
||||
@@ -210,11 +227,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
pub fn drain_device_code(state: &mut AccountState) {
|
||||
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
|
||||
&& info.user_code.is_empty()
|
||||
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
|
||||
&& let Some(dc_info) = slot.take() {
|
||||
info.user_code = dc_info.user_code;
|
||||
info.verification_uri = dc_info.verification_uri;
|
||||
}
|
||||
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
|
||||
&& let Some(dc_info) = slot.take()
|
||||
{
|
||||
info.user_code = dc_info.user_code;
|
||||
info.verification_uri = dc_info.verification_uri;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut AccountState) {
|
||||
@@ -246,8 +264,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
|
||||
|
||||
if state.store.accounts.is_empty() {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No accounts.")
|
||||
.style(Style::default().fg(theme.text_dim())),
|
||||
Paragraph::new("No accounts.").style(Style::default().fg(theme.text_dim())),
|
||||
inner,
|
||||
);
|
||||
} else {
|
||||
@@ -258,6 +275,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
|
||||
match &state.add_mode {
|
||||
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 => {}
|
||||
@@ -299,7 +317,9 @@ fn render_account_list(
|
||||
let active_marker = if *is_active { "\u{25b8} " } else { " " };
|
||||
|
||||
let style = if show_selected {
|
||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
||||
Style::default()
|
||||
.fg(theme.accent())
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else if *is_active {
|
||||
Style::default()
|
||||
.fg(theme.text())
|
||||
@@ -315,7 +335,9 @@ fn render_account_list(
|
||||
|
||||
if *acc_type == AccountType::Offline {
|
||||
let offline_style = if show_selected {
|
||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
||||
Style::default()
|
||||
.fg(theme.accent())
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.text_dim())
|
||||
};
|
||||
@@ -372,10 +394,7 @@ fn render_choose_popup(frame: &mut Frame) {
|
||||
.fg(accent_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
"Microsoft Account",
|
||||
Style::default().fg(text_color),
|
||||
),
|
||||
Span::styled("Microsoft Account", Style::default().fg(text_color)),
|
||||
]),
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
@@ -384,10 +403,7 @@ fn render_choose_popup(frame: &mut Frame) {
|
||||
.fg(accent_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
"Offline Account",
|
||||
Style::default().fg(text_color),
|
||||
),
|
||||
Span::styled("Offline Account", Style::default().fg(text_color)),
|
||||
]),
|
||||
];
|
||||
Paragraph::new(text).render(inner, buf);
|
||||
@@ -422,10 +438,7 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
|
||||
content: Box::new(move |inner, buf| {
|
||||
let line = if name.is_empty() {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
"Username...",
|
||||
Style::default().fg(dim_color),
|
||||
),
|
||||
Span::styled("Username...", Style::default().fg(dim_color)),
|
||||
Span::styled(
|
||||
"\u{2588}",
|
||||
Style::default()
|
||||
@@ -450,6 +463,36 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
|
||||
fn render_offline_blocked_popup(frame: &mut Frame) {
|
||||
use super::popups::{base::PopupFrame, keybind_line};
|
||||
let theme = THEME.as_ref();
|
||||
let area = popup_area(frame, 58, 5);
|
||||
|
||||
let border_color = theme.text_dim();
|
||||
let bg_color = theme.surface();
|
||||
let text_color = theme.text();
|
||||
|
||||
PopupFrame {
|
||||
title: Line::from(Span::styled(
|
||||
" Offline Account ",
|
||||
Style::default()
|
||||
.fg(border_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
))
|
||||
.centered(),
|
||||
border_color,
|
||||
bg: Some(bg_color),
|
||||
keybinds: Some(keybind_line(&[("Enter", " close")])),
|
||||
search_line: None,
|
||||
content: Box::new(move |inner, buf| {
|
||||
Paragraph::new("Add a Microsoft account that owns Minecraft first.")
|
||||
.style(Style::default().fg(text_color))
|
||||
.render(inner, buf);
|
||||
}),
|
||||
}
|
||||
.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();
|
||||
@@ -534,10 +577,7 @@ fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
|
||||
)),
|
||||
Line::from(""),
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
"Enter code: ",
|
||||
Style::default().fg(dim_color),
|
||||
),
|
||||
Span::styled("Enter code: ", Style::default().fg(dim_color)),
|
||||
Span::styled(
|
||||
code.as_str(),
|
||||
Style::default()
|
||||
|
||||
+337
-78
@@ -6,7 +6,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
@@ -21,14 +21,21 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
use crate::config::theme::THEME;
|
||||
use crate::instance::content::mods::{ContentEntry, IconCell};
|
||||
|
||||
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
|
||||
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
|
||||
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
|
||||
|
||||
struct CachedList {
|
||||
entries: Vec<ContentEntry>,
|
||||
selected: Option<usize>,
|
||||
}
|
||||
|
||||
// result from the notify-triggered background diff
|
||||
struct WatcherDiff {
|
||||
toggled: Vec<(String, bool, std::path::PathBuf)>,
|
||||
removed: Vec<String>,
|
||||
added: Vec<ContentEntry>,
|
||||
}
|
||||
|
||||
pub struct ContentListState {
|
||||
pub entries: Vec<ContentEntry>,
|
||||
pub list_state: TuiListState,
|
||||
@@ -37,10 +44,16 @@ pub struct ContentListState {
|
||||
pub loading: bool,
|
||||
pub search: crate::tui::widgets::search::SearchState,
|
||||
cache: HashMap<String, CachedList>,
|
||||
pending: PendingContent,
|
||||
check_counter: u16,
|
||||
// streaming: individual entries arrive here during initial load
|
||||
stream_rx: Option<mpsc::Receiver<ContentEntry>>,
|
||||
// file watcher: notify callback spawns background work,
|
||||
// precomputed diff lands here for the UI to pick up
|
||||
watcher_diff: Arc<Mutex<Option<WatcherDiff>>>,
|
||||
_watcher: Option<notify::RecommendedWatcher>,
|
||||
watched_dir: Option<std::path::PathBuf>,
|
||||
last_dir_mtime: Option<std::time::SystemTime>,
|
||||
// stored for the watcher to scan individual new files
|
||||
scan_one_fn: Option<ScanOneFn>,
|
||||
content_ext: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl Default for ContentListState {
|
||||
@@ -53,41 +66,229 @@ impl Default for ContentListState {
|
||||
loading: false,
|
||||
search: crate::tui::widgets::search::SearchState::default(),
|
||||
cache: HashMap::new(),
|
||||
pending: Arc::new(Mutex::new(None)),
|
||||
check_counter: 0,
|
||||
stream_rx: None,
|
||||
watcher_diff: Arc::new(Mutex::new(None)),
|
||||
_watcher: None,
|
||||
watched_dir: None,
|
||||
last_dir_mtime: None,
|
||||
scan_one_fn: None,
|
||||
content_ext: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContentListState {
|
||||
// poll the content directory for changes every ~120 ticks.
|
||||
// if the dir's mtime changed, invalidate the cache to pick up
|
||||
// mods/packs the user dropped in from outside the launcher
|
||||
pub fn try_rescan(&mut self) {
|
||||
self.check_counter = self.check_counter.wrapping_add(1);
|
||||
if !self.check_counter.is_multiple_of(120) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(dir) = &self.watched_dir else {
|
||||
// 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) {
|
||||
let Some(rx) = &self.stream_rx else {
|
||||
return;
|
||||
};
|
||||
|
||||
let current_mtime = std::fs::metadata(dir).ok().and_then(|m| m.modified().ok());
|
||||
|
||||
if current_mtime != self.last_dir_mtime {
|
||||
self.last_dir_mtime = current_mtime;
|
||||
if let Some(name) = &self.loaded_for {
|
||||
self.cache.remove(name);
|
||||
self.loaded_for = None;
|
||||
let mut received = false;
|
||||
let mut finished = false;
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(entry) => {
|
||||
received = true;
|
||||
let pos = self
|
||||
.entries
|
||||
.binary_search_by(|e| {
|
||||
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
|
||||
})
|
||||
.unwrap_or_else(|i| i);
|
||||
self.entries.insert(pos, entry);
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => break,
|
||||
Err(mpsc::TryRecvError::Disconnected) => {
|
||||
self.stream_rx = None;
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if received || finished {
|
||||
self.loading = false;
|
||||
if self.list_state.selected.is_none() && !self.entries.is_empty() {
|
||||
self.list_state.selected = Some(0);
|
||||
}
|
||||
self.update_scrollbar();
|
||||
}
|
||||
}
|
||||
|
||||
// pick up the precomputed diff from the notify watcher callback.
|
||||
// skip while streaming is in progress to avoid duplicate entries.
|
||||
pub fn drain_watcher(&mut self) {
|
||||
if self.stream_rx.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let diff = match self.watcher_diff.lock() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let Some(diff) = diff else {
|
||||
return;
|
||||
};
|
||||
|
||||
// apply toggles (enabled/path changes)
|
||||
for (stem, enabled, path) in &diff.toggled {
|
||||
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
|
||||
entry.enabled = *enabled;
|
||||
entry.path = path.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// apply removals
|
||||
if !diff.removed.is_empty() {
|
||||
self.entries
|
||||
.retain(|e| !diff.removed.contains(&e.file_stem));
|
||||
}
|
||||
|
||||
// insert new entries in sorted position
|
||||
for entry in diff.added {
|
||||
let pos = self
|
||||
.entries
|
||||
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
|
||||
.unwrap_or_else(|i| i);
|
||||
self.entries.insert(pos, entry);
|
||||
}
|
||||
|
||||
// clamp selected
|
||||
if let Some(sel) = self.list_state.selected {
|
||||
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.update_scrollbar();
|
||||
}
|
||||
|
||||
// starts a notify file watcher on the given directory. changes trigger
|
||||
// a background diff that lands in watcher_diff for drain_watcher to apply.
|
||||
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
|
||||
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok());
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
// drop previous watcher
|
||||
self._watcher = None;
|
||||
|
||||
let watcher_diff = self.watcher_diff.clone();
|
||||
let ext: &'static str = self.content_ext.unwrap_or(".jar");
|
||||
let scan_one = self.scan_one_fn;
|
||||
|
||||
let dirty = Arc::new(AtomicBool::new(false));
|
||||
let running = Arc::new(AtomicBool::new(false));
|
||||
let dirty_cb = dirty.clone();
|
||||
let running_cb = running.clone();
|
||||
|
||||
// initialize known stems from the current directory state so existing
|
||||
// files are not treated as "new" on the first notify event
|
||||
let known_stems = Arc::new(Mutex::new(read_dir_stems(&dir, ext)));
|
||||
|
||||
let watch_dir = dir.clone();
|
||||
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
|
||||
if res.is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
// mark dirty. if a thread is already running it will loop to
|
||||
// pick up the change after its current diff
|
||||
dirty_cb.store(true, Ordering::Relaxed);
|
||||
|
||||
if running_cb.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let dir = watch_dir.clone();
|
||||
let diff_slot = watcher_diff.clone();
|
||||
let dirty = dirty_cb.clone();
|
||||
let running = running_cb.clone();
|
||||
let known = known_stems.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
// always clear `running` even if we panic
|
||||
struct ResetOnDrop(Arc<AtomicBool>);
|
||||
impl Drop for ResetOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let _guard = ResetOnDrop(running);
|
||||
|
||||
loop {
|
||||
dirty.store(false, Ordering::Relaxed);
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
let result = (|| {
|
||||
let on_disk = read_dir_stems(&dir, ext);
|
||||
let mut known_map = known.lock().ok()?;
|
||||
|
||||
let mut toggled = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
|
||||
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(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
removed.push(stem.clone());
|
||||
}
|
||||
}
|
||||
|
||||
for (stem, (path, enabled)) in &on_disk {
|
||||
if !known_map.contains_key(stem)
|
||||
&& let Some(scan_one) = scan_one
|
||||
{
|
||||
added.push(scan_one(path, stem, *enabled));
|
||||
}
|
||||
}
|
||||
|
||||
*known_map = on_disk;
|
||||
|
||||
Some(WatcherDiff {
|
||||
toggled,
|
||||
removed,
|
||||
added,
|
||||
})
|
||||
})();
|
||||
|
||||
if let Some(diff) = result
|
||||
&& let Ok(mut slot) = diff_slot.lock()
|
||||
{
|
||||
*slot = Some(diff);
|
||||
}
|
||||
|
||||
if !dirty.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
match watcher {
|
||||
Ok(mut w) => {
|
||||
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
|
||||
tracing::warn!("Failed to watch {}: {e}", dir.display());
|
||||
} else {
|
||||
self._watcher = Some(w);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to create file watcher: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
self.watched_dir = Some(dir);
|
||||
}
|
||||
|
||||
@@ -103,11 +304,19 @@ impl ContentListState {
|
||||
|
||||
impl ContentListState {
|
||||
// saves current entries to cache before loading new ones, and restores
|
||||
// from cache if this instance was seen before (avoids re-scanning)
|
||||
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
|
||||
where
|
||||
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
|
||||
{
|
||||
// from cache if this instance was seen before (avoids re-scanning).
|
||||
// content_dir is the actual directory to scan (e.g. .minecraft/mods).
|
||||
pub fn start_load(
|
||||
&mut self,
|
||||
content_dir: &Path,
|
||||
instance_name: &str,
|
||||
scan_one_fn: ScanOneFn,
|
||||
ext: &'static str,
|
||||
) {
|
||||
self.scan_one_fn = Some(scan_one_fn);
|
||||
self.content_ext = Some(ext);
|
||||
|
||||
// save current entries to cache
|
||||
if let Some(prev) = self.loaded_for.take()
|
||||
&& !self.entries.is_empty()
|
||||
{
|
||||
@@ -120,68 +329,64 @@ impl ContentListState {
|
||||
);
|
||||
}
|
||||
|
||||
// try cache first
|
||||
if let Some(cached) = self.cache.remove(instance_name) {
|
||||
self.entries = cached.entries;
|
||||
self.list_state.selected = cached.selected;
|
||||
self.loading = false;
|
||||
} else {
|
||||
self.entries.clear();
|
||||
self.list_state = TuiListState::default();
|
||||
self.loading = true;
|
||||
self.stream_rx = None;
|
||||
self.loaded_for = Some(instance_name.to_string());
|
||||
self.update_scrollbar();
|
||||
return;
|
||||
}
|
||||
|
||||
// no cache, stream entries one by one as each file is scanned
|
||||
self.entries.clear();
|
||||
self.list_state = TuiListState::default();
|
||||
self.loading = true;
|
||||
self.loaded_for = Some(instance_name.to_string());
|
||||
self.update_scrollbar();
|
||||
|
||||
let dir = instances_dir.to_path_buf();
|
||||
let tag = instance_name.to_string();
|
||||
let pending = self.pending.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.stream_rx = Some(rx);
|
||||
|
||||
let dir = content_dir.to_path_buf();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let scan_dir = dir.clone();
|
||||
let scan_name = tag.clone();
|
||||
let entries = tokio::task::spawn_blocking(move || scan_fn(&scan_dir, &scan_name))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let read_dir = match std::fs::read_dir(&dir) {
|
||||
Ok(rd) => rd,
|
||||
Err(_) => return,
|
||||
};
|
||||
let disabled_ext = format!("{ext}.disabled");
|
||||
|
||||
if let Ok(mut slot) = pending.lock() {
|
||||
*slot = Some((tag, entries));
|
||||
}
|
||||
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 {
|
||||
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 entry = scan_one_fn(&path, &file_stem, enabled);
|
||||
if tx.send(entry).is_err() {
|
||||
break; // receiver dropped (instance switched)
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
pub fn drain_pending(&mut self) {
|
||||
let taken = match self.pending.lock() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some((instance_name, entries)) = taken
|
||||
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty())
|
||||
{
|
||||
let selected_name = self
|
||||
.list_state
|
||||
.selected
|
||||
.and_then(|i| self.entries.get(i))
|
||||
.map(|e| e.name.clone());
|
||||
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
|
||||
if !self.entries.is_empty() {
|
||||
let new_index = selected_name
|
||||
.and_then(|name| self.entries.iter().position(|e| e.name == name))
|
||||
.or(self.list_state.selected)
|
||||
.map(|i| i.min(self.entries.len().saturating_sub(1)))
|
||||
.unwrap_or(0);
|
||||
self.list_state.selected = Some(new_index);
|
||||
} else {
|
||||
self.list_state.selected = None;
|
||||
}
|
||||
self.update_scrollbar();
|
||||
}
|
||||
}
|
||||
|
||||
fn update_scrollbar(&mut self) {
|
||||
let count = self.entries.len();
|
||||
let max = count.saturating_sub(1);
|
||||
@@ -233,6 +438,11 @@ impl ContentListState {
|
||||
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
|
||||
if state.search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
state.search.confirm();
|
||||
state.list_state.selected = Some(0);
|
||||
state.update_scrollbar();
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.search.deactivate();
|
||||
state.list_state.selected = Some(0);
|
||||
@@ -360,6 +570,7 @@ pub fn render(
|
||||
let filtered = state.filtered_indices();
|
||||
|
||||
if filtered.is_empty() {
|
||||
state.list_state.selected = None;
|
||||
frame.render_widget(
|
||||
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
|
||||
area,
|
||||
@@ -369,6 +580,13 @@ pub fn render(
|
||||
|
||||
let count = filtered.len();
|
||||
|
||||
// clamp selected so the ListView builder never gets an out-of-bounds index
|
||||
if let Some(sel) = state.list_state.selected
|
||||
&& sel >= count
|
||||
{
|
||||
state.list_state.selected = Some(count.saturating_sub(1));
|
||||
}
|
||||
|
||||
let snapshot: Vec<SnapshotRow> = filtered
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
@@ -656,3 +874,44 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)> {
|
||||
let mut map = HashMap::new();
|
||||
let Ok(read_dir) = std::fs::read_dir(dir) else {
|
||||
return map;
|
||||
};
|
||||
let dirs_only = ext.is_empty();
|
||||
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 {
|
||||
continue;
|
||||
};
|
||||
if dirs_only {
|
||||
if !path.is_dir() && !fname.ends_with(".disabled") {
|
||||
continue;
|
||||
}
|
||||
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
|
||||
map.insert(stem, (path, enabled));
|
||||
continue;
|
||||
}
|
||||
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
|
||||
map.insert(stem.to_owned(), (path, false));
|
||||
} else if let Some(stem) = fname.strip_suffix(ext) {
|
||||
map.insert(stem.to_owned(), (path, true));
|
||||
} else if path.is_dir() {
|
||||
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
|
||||
map.insert(stem, (path, enabled));
|
||||
}
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
@@ -3,5 +3,5 @@
|
||||
pub mod list;
|
||||
pub mod tabs;
|
||||
|
||||
pub use tabs::{ContentTab, render, title};
|
||||
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
|
||||
pub use tabs::{ContentTab, render, title};
|
||||
@@ -3,16 +3,16 @@
|
||||
// also renders the instance name/version header with run state indicators.
|
||||
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Alignment, Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
use throbber_widgets_tui::{Throbber, ThrobberState};
|
||||
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::tui::app::FocusedArea;
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
|
||||
use crate::tui::widgets::styled_title;
|
||||
|
||||
@@ -200,7 +200,8 @@ pub fn render(
|
||||
};
|
||||
|
||||
if let Some(kb) = kb {
|
||||
let lines = crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
|
||||
let lines =
|
||||
crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
|
||||
for line in lines {
|
||||
block = block.title_bottom(line);
|
||||
}
|
||||
@@ -214,12 +215,9 @@ pub fn render(
|
||||
ContentTab::Mods => {
|
||||
if let Some(instance) = instance {
|
||||
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
mods_state.start_load(
|
||||
instances_dir,
|
||||
&instance.name,
|
||||
crate::instance::scan_mods,
|
||||
);
|
||||
mods_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("mods"));
|
||||
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(
|
||||
frame,
|
||||
@@ -240,12 +238,9 @@ pub fn render(
|
||||
ContentTab::ResourcePacks => {
|
||||
if let Some(instance) = instance {
|
||||
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
resource_packs_state.start_load(
|
||||
instances_dir,
|
||||
&instance.name,
|
||||
crate::instance::scan_resource_packs,
|
||||
);
|
||||
resource_packs_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks"));
|
||||
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(
|
||||
frame,
|
||||
@@ -266,12 +261,9 @@ pub fn render(
|
||||
ContentTab::Shaders => {
|
||||
if let Some(instance) = instance {
|
||||
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
shaders_state.start_load(
|
||||
instances_dir,
|
||||
&instance.name,
|
||||
crate::instance::scan_shaders,
|
||||
);
|
||||
shaders_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks"));
|
||||
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(
|
||||
frame,
|
||||
@@ -294,7 +286,12 @@ pub fn render(
|
||||
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
logs_state.start_load(instances_dir, &instance.name);
|
||||
}
|
||||
crate::tui::widgets::logs_viewer::render(frame, content_area, logs_state, is_focused);
|
||||
crate::tui::widgets::logs_viewer::render(
|
||||
frame,
|
||||
content_area,
|
||||
logs_state,
|
||||
is_focused,
|
||||
);
|
||||
} else {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No instance selected.")
|
||||
@@ -308,7 +305,12 @@ pub fn render(
|
||||
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
screenshots_state.start_load(instances_dir, &instance.name);
|
||||
}
|
||||
crate::tui::widgets::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
|
||||
crate::tui::widgets::screenshots_grid::render(
|
||||
frame,
|
||||
content_area,
|
||||
screenshots_state,
|
||||
is_focused,
|
||||
);
|
||||
} else {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No instance selected.")
|
||||
@@ -320,12 +322,9 @@ pub fn render(
|
||||
ContentTab::Worlds => {
|
||||
if let Some(instance) = instance {
|
||||
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
worlds_state.start_load(
|
||||
instances_dir,
|
||||
&instance.name,
|
||||
crate::instance::scan_worlds,
|
||||
);
|
||||
worlds_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("saves"));
|
||||
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(
|
||||
frame,
|
||||
@@ -374,8 +373,7 @@ pub fn title(
|
||||
match instance {
|
||||
None => {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No instance selected")
|
||||
.style(Style::default().fg(theme.text_dim())),
|
||||
Paragraph::new("No instance selected").style(Style::default().fg(theme.text_dim())),
|
||||
inner,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
// and provides keybinds to open config files in $EDITOR
|
||||
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::instance::models::InstanceConfig;
|
||||
use crate::tui::app::FocusedArea;
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
|
||||
use super::styled_title;
|
||||
|
||||
@@ -54,8 +54,7 @@ pub fn render(
|
||||
|
||||
let Some(inst) = instance else {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No instance selected.")
|
||||
.style(Style::default().fg(theme.text_dim())),
|
||||
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
|
||||
inner,
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -2,22 +2,22 @@
|
||||
// handles search/filter, scrollbar sync, and inline renaming.
|
||||
// each row shows instance name + "last played" or current run state.
|
||||
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crossterm::event::KeyCode;
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span, Text},
|
||||
widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
Frame,
|
||||
};
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
use crate::instance::models::InstanceConfig;
|
||||
use crate::running::{get as get_run_state, RunState};
|
||||
use crate::running::{RunState, get as get_run_state};
|
||||
use crate::tui::app::FocusedArea;
|
||||
|
||||
use super::{search::SearchState, styled_title, WidgetKey};
|
||||
use super::{WidgetKey, search::SearchState, styled_title};
|
||||
|
||||
// rough human-friendly time delta. not trying to be precise here,
|
||||
// "2 months ago" is close enough when months are ~30 days
|
||||
@@ -149,12 +149,30 @@ impl State {
|
||||
self.instances.push(instance);
|
||||
self.update_scrollbar();
|
||||
}
|
||||
|
||||
pub fn replace_instance(&mut self, old_name: &str, instance: InstanceConfig) {
|
||||
if let Some(existing) = self
|
||||
.instances
|
||||
.iter_mut()
|
||||
.find(|i| i.name == old_name || i.name == instance.name)
|
||||
{
|
||||
*existing = instance;
|
||||
} else {
|
||||
self.instances.push(instance);
|
||||
}
|
||||
self.update_scrollbar();
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetKey for State {
|
||||
fn handle_key(&mut self, key_event: &crossterm::event::KeyEvent) {
|
||||
if self.search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
self.search.confirm();
|
||||
self.list_state.selected = Some(0);
|
||||
self.update_scrollbar();
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.search.deactivate();
|
||||
self.list_state.selected = Some(0);
|
||||
@@ -237,7 +255,9 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
|
||||
let (name_style, meta_style, bg) = if context.is_selected {
|
||||
(
|
||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
|
||||
Style::default()
|
||||
.fg(theme.accent())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
Style::default().fg(theme.text_dim()),
|
||||
stripe_bg,
|
||||
)
|
||||
@@ -282,14 +302,16 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
"Authenticating".to_string(),
|
||||
Style::default().fg(theme.success()),
|
||||
),
|
||||
Some(RunState::Running) | Some(RunState::Starting) => (
|
||||
"Playing".to_string(),
|
||||
Style::default().fg(theme.success()),
|
||||
),
|
||||
Some(RunState::Running) | Some(RunState::Starting) => {
|
||||
("Playing".to_string(), Style::default().fg(theme.success()))
|
||||
}
|
||||
_ => (format_last_played(instance.last_played), meta_style),
|
||||
};
|
||||
|
||||
let meta_line = Line::from(vec![selector.clone(), Span::styled(meta_text, meta_text_style)]);
|
||||
let meta_line = Line::from(vec![
|
||||
selector.clone(),
|
||||
Span::styled(meta_text, meta_text_style),
|
||||
]);
|
||||
|
||||
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
|
||||
(item, 2)
|
||||
|
||||
@@ -8,16 +8,16 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
Frame,
|
||||
};
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
use crate::instance::log_files::{read_log_file, scan_log_files, LogFileEntry};
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
|
||||
|
||||
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
|
||||
|
||||
@@ -38,6 +38,7 @@ pub struct LogsState {
|
||||
pending: PendingLogs,
|
||||
rescan_counter: u8,
|
||||
instances_dir_cache: Option<std::path::PathBuf>,
|
||||
was_live: bool,
|
||||
}
|
||||
|
||||
impl Default for LogsState {
|
||||
@@ -59,6 +60,7 @@ impl Default for LogsState {
|
||||
pending: Arc::new(Mutex::new(None)),
|
||||
rescan_counter: 0,
|
||||
instances_dir_cache: None,
|
||||
was_live: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,29 +96,39 @@ impl LogsState {
|
||||
}
|
||||
|
||||
pub fn drain_pending(&mut self) {
|
||||
let taken = match self.pending.lock() { Ok(mut slot) => {
|
||||
slot.take()
|
||||
} _ => {
|
||||
None
|
||||
}};
|
||||
// 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() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some((instance_name, entries)) = taken
|
||||
&& self.loaded_for.as_deref() == Some(&instance_name) {
|
||||
let prev_selected = self.list_state.selected;
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
&& self.loaded_for.as_deref() == Some(&instance_name)
|
||||
{
|
||||
let prev_selected = self.list_state.selected;
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
|
||||
let display_count = self.display_count();
|
||||
let display_count = self.display_count();
|
||||
|
||||
if display_count > 0 && prev_selected.is_none() {
|
||||
self.list_state.selected = Some(0);
|
||||
self.load_selected_content();
|
||||
} else if let Some(sel) = prev_selected
|
||||
&& sel >= display_count && display_count > 0 {
|
||||
self.list_state.selected = Some(display_count - 1);
|
||||
}
|
||||
self.update_scrollbar();
|
||||
if display_count > 0 && prev_selected.is_none() {
|
||||
self.list_state.selected = Some(0);
|
||||
self.load_selected_content();
|
||||
} else if let Some(sel) = prev_selected
|
||||
&& sel >= display_count
|
||||
&& display_count > 0
|
||||
{
|
||||
self.list_state.selected = Some(display_count - 1);
|
||||
}
|
||||
self.update_scrollbar();
|
||||
}
|
||||
}
|
||||
|
||||
// periodically re-scan log files in case new ones appeared while playing.
|
||||
@@ -225,6 +237,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
|
||||
if state.viewer_focused {
|
||||
if state.viewer_search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
state.viewer_search.confirm();
|
||||
state.viewer_scroll = 0;
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.viewer_search.deactivate();
|
||||
state.viewer_scroll = 0;
|
||||
@@ -288,6 +304,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
|
||||
} else {
|
||||
if state.search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
state.search.confirm();
|
||||
state.list_state.selected = Some(0);
|
||||
state.update_scrollbar();
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.search.deactivate();
|
||||
state.list_state.selected = Some(0);
|
||||
@@ -408,7 +429,12 @@ fn render_list(
|
||||
let entries_snapshot: Vec<(String, bool)> = {
|
||||
let mut v = Vec::new();
|
||||
if has_live {
|
||||
v.push(("\u{25cf} Live".to_string(), true));
|
||||
let live_name = state
|
||||
.entries
|
||||
.first()
|
||||
.map(|e| e.name.trim_end_matches(".log"))
|
||||
.unwrap_or("Live");
|
||||
v.push((live_name.to_string(), true));
|
||||
}
|
||||
for e in &state.entries {
|
||||
v.push((e.name.trim_end_matches(".log").to_string(), false));
|
||||
@@ -421,11 +447,15 @@ fn render_list(
|
||||
let show_selected = list_focused && context.is_selected;
|
||||
|
||||
let style = if *is_live && show_selected {
|
||||
Style::default().fg(theme.success()).add_modifier(Modifier::BOLD)
|
||||
Style::default()
|
||||
.fg(theme.success())
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else if *is_live {
|
||||
Style::default().fg(theme.success())
|
||||
} else if show_selected {
|
||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
||||
Style::default()
|
||||
.fg(theme.accent())
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.text())
|
||||
};
|
||||
@@ -441,8 +471,11 @@ fn render_list(
|
||||
} else {
|
||||
Span::raw(" ")
|
||||
};
|
||||
let item = ratatui::text::Text::from(Line::from(vec![selector, Span::styled(name.clone(), style)]))
|
||||
.style(Style::default().bg(bg));
|
||||
let item = ratatui::text::Text::from(Line::from(vec![
|
||||
selector,
|
||||
Span::styled(name.clone(), style),
|
||||
]))
|
||||
.style(Style::default().bg(bg));
|
||||
(item, 1)
|
||||
});
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ use ratatui::{
|
||||
pub mod account;
|
||||
pub mod content;
|
||||
pub mod details;
|
||||
pub mod instances;
|
||||
pub mod logs_viewer;
|
||||
pub mod popups;
|
||||
pub mod instances;
|
||||
pub mod screenshots_grid;
|
||||
pub mod search;
|
||||
pub mod status;
|
||||
|
||||
@@ -14,7 +14,8 @@ use ratatui::{
|
||||
|
||||
use crate::config::theme::THEME;
|
||||
|
||||
static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> = LazyLock::new(|| Mutex::new(ConfirmState::default()));
|
||||
static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
|
||||
LazyLock::new(|| Mutex::new(ConfirmState::default()));
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ConfirmState {
|
||||
|
||||
@@ -12,8 +12,8 @@ use tracing::Level;
|
||||
|
||||
use super::base::PopupFrame;
|
||||
use crate::config::SETTINGS;
|
||||
use crate::tui::error_buffer::ErrorEvent;
|
||||
use crate::config::theme::THEME;
|
||||
use crate::tui::error_buffer::ErrorEvent;
|
||||
|
||||
pub struct ErrorPopup {
|
||||
pub event: ErrorEvent,
|
||||
|
||||
@@ -2,4 +2,4 @@ mod render;
|
||||
mod state;
|
||||
|
||||
pub use render::{popup_rect, render};
|
||||
pub use state::{handle_key, take_result, ImportResult, ImportStep, ImportWizardState};
|
||||
pub use state::{ImportResult, ImportStep, ImportWizardState, handle_key, take_result};
|
||||
@@ -3,15 +3,15 @@
|
||||
|
||||
use super::super::base::PopupFrame;
|
||||
use super::super::new_instance::LoadState;
|
||||
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE};
|
||||
use crate::tui::app::FocusedArea;
|
||||
use super::state::{IMPORT_STATE, ImportStep, ImportWizardState};
|
||||
use crate::config::theme::THEME;
|
||||
use crate::tui::app::FocusedArea;
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
|
||||
Frame,
|
||||
};
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
|
||||
@@ -85,11 +85,7 @@ pub fn popup_rect(frame_area: Rect) -> Rect {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_input_step(
|
||||
state: &ImportWizardState,
|
||||
area: Rect,
|
||||
buf: &mut ratatui::buffer::Buffer,
|
||||
) {
|
||||
fn render_input_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
|
||||
let theme = THEME.as_ref();
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
@@ -115,10 +111,7 @@ fn render_input_step(
|
||||
])
|
||||
} else {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
state.input.clone(),
|
||||
Style::default().fg(theme.text()),
|
||||
),
|
||||
Span::styled(state.input.clone(), Style::default().fg(theme.text())),
|
||||
Span::styled(
|
||||
"\u{2588}",
|
||||
Style::default()
|
||||
@@ -137,11 +130,7 @@ fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
|
||||
.render(area, buf);
|
||||
}
|
||||
|
||||
fn render_version_step(
|
||||
state: &ImportWizardState,
|
||||
area: Rect,
|
||||
buf: &mut ratatui::buffer::Buffer,
|
||||
) {
|
||||
fn render_version_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
|
||||
let theme = THEME.as_ref();
|
||||
match &state.versions {
|
||||
LoadState::Idle | LoadState::Loading => {
|
||||
@@ -182,11 +171,7 @@ fn render_version_step(
|
||||
}
|
||||
}
|
||||
|
||||
fn render_confirm_step(
|
||||
state: &ImportWizardState,
|
||||
area: Rect,
|
||||
buf: &mut ratatui::buffer::Buffer,
|
||||
) {
|
||||
fn render_confirm_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
|
||||
let theme = THEME.as_ref();
|
||||
let summary = match &state.summary {
|
||||
Some(s) => s,
|
||||
@@ -247,11 +232,9 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
|
||||
match state.step {
|
||||
ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
|
||||
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
|
||||
ImportStep::Version => keybind_line(&[
|
||||
("/", " search"),
|
||||
("h", " back"),
|
||||
("Enter", " select"),
|
||||
]),
|
||||
ImportStep::Version => {
|
||||
keybind_line(&[("/", " search"), ("h", " back"), ("Enter", " select")])
|
||||
}
|
||||
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
// local files skip straight to the confirm step.
|
||||
|
||||
use super::super::new_instance::LoadState;
|
||||
use crate::instance::import::{parse_import_input, ImportInput, ImportSummary};
|
||||
use crate::instance::import::{ImportInput, ImportSummary, parse_import_input};
|
||||
use crate::net::modrinth::{self, VersionInfo};
|
||||
use crate::tui::widgets::instances;
|
||||
use crate::tui::widgets::search::SearchState;
|
||||
@@ -164,10 +164,8 @@ fn handle_version_key(
|
||||
state.version_idx = 0;
|
||||
state.version_search.deactivate();
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
if visible_count > 0 {
|
||||
state.version_idx = (state.version_idx + 1).min(visible_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down if visible_count > 0 => {
|
||||
state.version_idx = (state.version_idx + 1).min(visible_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
state.version_idx = state.version_idx.saturating_sub(1);
|
||||
@@ -309,21 +307,19 @@ async fn resolve_version_id(
|
||||
}
|
||||
|
||||
match modrinth::download_mrpack(client, &version, &tmp_dir).await {
|
||||
Ok(mrpack_path) => {
|
||||
match crate::instance::import::build_summary(&mrpack_path) {
|
||||
Ok(summary) => {
|
||||
if let Ok(mut s) = state_arc.lock() {
|
||||
s.summary = Some(summary);
|
||||
s.step = ImportStep::Confirm;
|
||||
}
|
||||
Ok(mrpack_path) => match crate::instance::import::build_summary(&mrpack_path) {
|
||||
Ok(summary) => {
|
||||
if let Ok(mut s) = state_arc.lock() {
|
||||
s.summary = Some(summary);
|
||||
s.step = ImportStep::Confirm;
|
||||
}
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to build summary: {}", e),
|
||||
ImportStep::Input,
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to build summary: {}", e),
|
||||
ImportStep::Input,
|
||||
),
|
||||
},
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to download mrpack: {}", e),
|
||||
@@ -383,21 +379,19 @@ fn start_version_download(state: &mut ImportWizardState) {
|
||||
}
|
||||
|
||||
match modrinth::download_mrpack(&client, &version, &tmp_dir).await {
|
||||
Ok(mrpack_path) => {
|
||||
match crate::instance::import::build_summary(&mrpack_path) {
|
||||
Ok(summary) => {
|
||||
if let Ok(mut s) = state_arc.lock() {
|
||||
s.summary = Some(summary);
|
||||
s.step = ImportStep::Confirm;
|
||||
}
|
||||
Ok(mrpack_path) => match crate::instance::import::build_summary(&mrpack_path) {
|
||||
Ok(summary) => {
|
||||
if let Ok(mut s) = state_arc.lock() {
|
||||
s.summary = Some(summary);
|
||||
s.step = ImportStep::Confirm;
|
||||
}
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to build summary: {}", e),
|
||||
ImportStep::Version,
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to build summary: {}", e),
|
||||
ImportStep::Version,
|
||||
),
|
||||
},
|
||||
Err(e) => set_error_and_back(
|
||||
&state_arc,
|
||||
format!("Failed to download mrpack: {}", e),
|
||||
|
||||
@@ -2,4 +2,4 @@ mod render;
|
||||
mod state;
|
||||
|
||||
pub use render::{popup_rect, render};
|
||||
pub use state::{handle_key, take_result, LoadState, WizardParams, WizardStep, WizardState};
|
||||
pub use state::{LoadState, WizardParams, WizardState, WizardStep, handle_key, take_result};
|
||||
@@ -2,21 +2,21 @@
|
||||
// and the popup resizes itself based on which step is active.
|
||||
|
||||
use super::state::{
|
||||
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded,
|
||||
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE,
|
||||
LoadState, WIZARD_STATE, WizardState, WizardStep, clamp_loader_version_index,
|
||||
clamp_version_index, ensure_loader_versions_loaded, ensure_versions_loaded, visible_versions,
|
||||
};
|
||||
use crate::config::theme::THEME;
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::tui::app::FocusedArea;
|
||||
use crate::config::theme::THEME;
|
||||
use crate::tui::widgets::popups::base::PopupFrame;
|
||||
use tui_prompts::State as PromptState;
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
|
||||
Frame,
|
||||
};
|
||||
use tui_prompts::State as PromptState;
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
|
||||
// grab the lock, kick off any lazy-loading, then clone and release.
|
||||
@@ -140,10 +140,7 @@ fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::
|
||||
// \u{2588} is the full block char used as a fake blinking cursor
|
||||
let line = if value.is_empty() {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
"Instance name...",
|
||||
Style::default().fg(theme.text_dim()),
|
||||
),
|
||||
Span::styled("Instance name...", Style::default().fg(theme.text_dim())),
|
||||
Span::styled(
|
||||
"\u{2588}",
|
||||
Style::default()
|
||||
|
||||
@@ -202,10 +202,8 @@ fn handle_version_key(
|
||||
KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
|
||||
state.step = WizardStep::Loader;
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
if visible_count > 0 {
|
||||
state.version_idx = (state.version_idx + 1).min(visible_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down if visible_count > 0 => {
|
||||
state.version_idx = (state.version_idx + 1).min(visible_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
state.version_idx = state.version_idx.saturating_sub(1);
|
||||
@@ -286,11 +284,9 @@ fn handle_loader_version_key(
|
||||
match key_event.code {
|
||||
KeyCode::Esc => close_popup(state, instances_state),
|
||||
KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Version,
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
if version_count > 0 {
|
||||
state.loader_version_idx =
|
||||
(state.loader_version_idx + 1).min(version_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down if version_count > 0 => {
|
||||
state.loader_version_idx =
|
||||
(state.loader_version_idx + 1).min(version_count.saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
state.loader_version_idx = state.loader_version_idx.saturating_sub(1);
|
||||
|
||||
@@ -8,16 +8,16 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::Span,
|
||||
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
Frame,
|
||||
};
|
||||
use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
|
||||
use ratatui_image::{Resize, StatefulImage, protocol::StatefulProtocol};
|
||||
|
||||
use crate::instance::screenshots::ScreenshotEntry;
|
||||
use crate::config::theme::THEME;
|
||||
use crate::instance::screenshots::ScreenshotEntry;
|
||||
|
||||
// grid cell sizing constraints in terminal columns.
|
||||
// the grid auto-fits columns within these bounds depending on terminal width
|
||||
@@ -97,27 +97,26 @@ impl ScreenshotsState {
|
||||
}
|
||||
|
||||
pub fn drain_pending_entries(&mut self) {
|
||||
let taken = match self.pending_entries.lock() { Ok(mut slot) => {
|
||||
slot.take()
|
||||
} _ => {
|
||||
None
|
||||
}};
|
||||
let taken = match self.pending_entries.lock() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some((instance_name, entries)) = taken
|
||||
&& self.loaded_for.as_deref() == Some(&instance_name) {
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
self.selected = 0;
|
||||
self.scroll_row = 0;
|
||||
}
|
||||
&& self.loaded_for.as_deref() == Some(&instance_name)
|
||||
{
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
self.selected = 0;
|
||||
self.scroll_row = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_pending_images(&mut self) -> Vec<(usize, image::DynamicImage)> {
|
||||
match self.pending_images.lock() { Ok(mut slot) => {
|
||||
std::mem::take(&mut *slot)
|
||||
} _ => {
|
||||
Vec::new()
|
||||
}}
|
||||
match self.pending_images.lock() {
|
||||
Ok(mut slot) => std::mem::take(&mut *slot),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_protocol(&mut self, idx: usize, proto: StatefulProtocol) {
|
||||
@@ -146,20 +145,17 @@ impl ScreenshotsState {
|
||||
.unwrap_or(None);
|
||||
|
||||
if let Some(img) = img
|
||||
&& let Ok(mut slot) = pending.lock() {
|
||||
slot.push((idx, img));
|
||||
}
|
||||
&& let Ok(mut slot) = pending.lock()
|
||||
{
|
||||
slot.push((idx, img));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_visible(&mut self) {
|
||||
let row = if self.cols > 0 {
|
||||
self.selected / self.cols
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let row = self.selected.checked_div(self.cols).unwrap_or(0);
|
||||
|
||||
if row < self.scroll_row {
|
||||
self.scroll_row = row;
|
||||
@@ -182,6 +178,10 @@ impl ScreenshotsState {
|
||||
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
|
||||
if state.search.active {
|
||||
match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
state.search.confirm();
|
||||
state.selected = 0;
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.search.deactivate();
|
||||
state.selected = 0;
|
||||
@@ -225,16 +225,18 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
|
||||
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||
if let Some(entry) = state.entries.get(state.selected)
|
||||
&& let Some(dir) = entry.path.parent()
|
||||
&& let Err(e) = open::that(dir) {
|
||||
tracing::error!("Failed to open directory: {}", e);
|
||||
}
|
||||
&& let Err(e) = open::that(dir)
|
||||
{
|
||||
tracing::error!("Failed to open directory: {}", e);
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some(entry) = state.entries.get(state.selected)
|
||||
&& let Err(e) = open::that(&entry.path) {
|
||||
tracing::error!("Failed to open file: {}", e);
|
||||
}
|
||||
&& let Err(e) = open::that(&entry.path)
|
||||
{
|
||||
tracing::error!("Failed to open file: {}", e);
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Char('L') | KeyCode::Right
|
||||
@@ -272,8 +274,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
|
||||
let theme = THEME.as_ref();
|
||||
if state.loading {
|
||||
frame.render_widget(
|
||||
Paragraph::new("Loading screenshots...")
|
||||
.style(Style::default().fg(theme.text_dim())),
|
||||
Paragraph::new("Loading screenshots...").style(Style::default().fg(theme.text_dim())),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
@@ -281,8 +282,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
|
||||
|
||||
if state.entries.is_empty() {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No screenshots.")
|
||||
.style(Style::default().fg(theme.text_dim())),
|
||||
Paragraph::new("No screenshots.").style(Style::default().fg(theme.text_dim())),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -24,6 +24,12 @@ impl SearchState {
|
||||
self.query.clear();
|
||||
}
|
||||
|
||||
// exit search mode but keep the filter active so the user can
|
||||
// navigate the filtered results
|
||||
pub fn confirm(&mut self) {
|
||||
self.active = false;
|
||||
}
|
||||
|
||||
pub fn push(&mut self, c: char) {
|
||||
self.query.push(c);
|
||||
}
|
||||
@@ -103,3 +109,47 @@ impl SearchState {
|
||||
Some(Line::from(spans).right_aligned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirm_keeps_query_but_deactivates() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('a');
|
||||
s.push('b');
|
||||
s.confirm();
|
||||
assert!(!s.active);
|
||||
assert_eq!(s.query, "ab");
|
||||
// filter should still match
|
||||
assert!(s.matches("abc"));
|
||||
assert!(!s.matches("xyz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deactivate_clears_query() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('x');
|
||||
s.deactivate();
|
||||
assert!(!s.active);
|
||||
assert!(s.query.is_empty());
|
||||
// with empty query, everything matches
|
||||
assert!(s.matches("anything"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirm_then_reactivate_preserves_query() {
|
||||
let mut s = SearchState::default();
|
||||
s.activate();
|
||||
s.push('t');
|
||||
s.push('e');
|
||||
s.confirm();
|
||||
// user presses search key again to edit
|
||||
s.activate();
|
||||
assert!(s.active);
|
||||
assert_eq!(s.query, "te");
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,17 @@
|
||||
// shows a gauge when the total is known, or a spinner when it's not.
|
||||
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::Span,
|
||||
widgets::{Block, Borders, Gauge, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
use throbber_widgets_tui::{Throbber, ThrobberState};
|
||||
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::tui::app::FocusedArea;
|
||||
use crate::tui::progress::PROGRESS;
|
||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
||||
|
||||
use super::styled_title;
|
||||
|
||||
@@ -39,11 +39,8 @@ pub fn render(
|
||||
Ok(s) => s.clone(),
|
||||
Err(_) => {
|
||||
frame.render_widget(
|
||||
Paragraph::new(Span::styled(
|
||||
"Ready",
|
||||
Style::default().fg(theme.text_dim()),
|
||||
))
|
||||
.block(block),
|
||||
Paragraph::new(Span::styled("Ready", Style::default().fg(theme.text_dim())))
|
||||
.block(block),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
@@ -52,11 +49,8 @@ pub fn render(
|
||||
|
||||
if state.current_action.is_none() {
|
||||
frame.render_widget(
|
||||
Paragraph::new(Span::styled(
|
||||
"Ready",
|
||||
Style::default().fg(theme.text_dim()),
|
||||
))
|
||||
.block(block),
|
||||
Paragraph::new(Span::styled("Ready", Style::default().fg(theme.text_dim())))
|
||||
.block(block),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
<?xml version='1.0' encoding='windows-1252'?>
|
||||
<!--
|
||||
Copyright (C) 2017 Christopher R. Field.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-->
|
||||
|
||||
<!--
|
||||
The "cargo wix" subcommand provides a variety of predefined variables available
|
||||
for customization of this template. The values for each variable are set at
|
||||
installer creation time. The following variables are available:
|
||||
|
||||
TargetTriple = The rustc target triple name.
|
||||
TargetEnv = The rustc target environment. This is typically either
|
||||
"msvc" or "gnu" depending on the toolchain downloaded and
|
||||
installed.
|
||||
TargetVendor = The rustc target vendor. This is typically "pc", but Rust
|
||||
does support other vendors, like "uwp".
|
||||
CargoTargetBinDir = The complete path to the directory containing the
|
||||
binaries (exes) to include. The default would be
|
||||
"target\release\". If an explicit rustc target triple is
|
||||
used, i.e. cross-compiling, then the default path would
|
||||
be "target\<CARGO_TARGET>\<CARGO_PROFILE>",
|
||||
where "<CARGO_TARGET>" is replaced with the "CargoTarget"
|
||||
variable value and "<CARGO_PROFILE>" is replaced with the
|
||||
value from the "CargoProfile" variable. This can also
|
||||
be overridden manually with the "target-bin-dir" flag.
|
||||
CargoTargetDir = The path to the directory for the build artifacts, i.e.
|
||||
"target".
|
||||
CargoProfile = The cargo profile used to build the binaries
|
||||
(usually "debug" or "release").
|
||||
Version = The version for the installer. The default is the
|
||||
"Major.Minor.Fix" semantic versioning number of the Rust
|
||||
package.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Please do not remove these pre-processor If-Else blocks. These are used with
|
||||
the `cargo wix` subcommand to automatically determine the installation
|
||||
destination for 32-bit versus 64-bit installers. Removal of these lines will
|
||||
cause installation errors.
|
||||
-->
|
||||
<?if $(sys.BUILDARCH) = x64 or $(sys.BUILDARCH) = arm64 ?>
|
||||
<?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
|
||||
<?else ?>
|
||||
<?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
|
||||
<?endif ?>
|
||||
|
||||
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
|
||||
|
||||
<Product
|
||||
Id='*'
|
||||
Name='mcl-launcher'
|
||||
UpgradeCode='BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE'
|
||||
Manufacturer='objz'
|
||||
Language='1033'
|
||||
Codepage='1252'
|
||||
Version='$(var.Version)'>
|
||||
|
||||
<Package Id='*'
|
||||
Keywords='Installer'
|
||||
Description='A fully featured Minecraft launcher TUI'
|
||||
Manufacturer='objz'
|
||||
InstallerVersion='450'
|
||||
Languages='1033'
|
||||
Compressed='yes'
|
||||
InstallScope='perMachine'
|
||||
SummaryCodepage='1252'
|
||||
/>
|
||||
|
||||
<MajorUpgrade
|
||||
Schedule='afterInstallInitialize'
|
||||
DowngradeErrorMessage='A newer version of [ProductName] is already installed. Setup will now exit.'/>
|
||||
|
||||
<Media Id='1' Cabinet='media1.cab' EmbedCab='yes' DiskPrompt='CD-ROM #1'/>
|
||||
<Property Id='DiskPrompt' Value='mcl-launcher Installation'/>
|
||||
|
||||
<Directory Id='TARGETDIR' Name='SourceDir'>
|
||||
<Directory Id='$(var.PlatformProgramFilesFolder)' Name='PFiles'>
|
||||
<Directory Id='APPLICATIONFOLDER' Name='mcl-launcher'>
|
||||
|
||||
<!--
|
||||
Enabling the license sidecar file in the installer is a four step process:
|
||||
|
||||
1. Uncomment the `Component` tag and its contents.
|
||||
2. Change the value for the `Source` attribute in the `File` tag to a path
|
||||
to the file that should be included as the license sidecar file. The path
|
||||
can, and probably should be, relative to this file.
|
||||
3. Change the value for the `Name` attribute in the `File` tag to the
|
||||
desired name for the file when it is installed alongside the `bin` folder
|
||||
in the installation directory. This can be omitted if the desired name is
|
||||
the same as the file name.
|
||||
4. Uncomment the `ComponentRef` tag with the Id attribute value of "License"
|
||||
further down in this file.
|
||||
-->
|
||||
<!--
|
||||
<Component Id='License' Guid='*'>
|
||||
<File Id='LicenseFile' Name='ChangeMe' DiskId='1' Source='C:\Path\To\File' KeyPath='yes'/>
|
||||
</Component>
|
||||
-->
|
||||
|
||||
<Directory Id='Bin' Name='bin'>
|
||||
<Component Id='Path' Guid='E5863AC2-13FC-45C8-B79D-55338F371A8A' KeyPath='yes'>
|
||||
<Environment
|
||||
Id='PATH'
|
||||
Name='PATH'
|
||||
Value='[Bin]'
|
||||
Permanent='no'
|
||||
Part='last'
|
||||
Action='set'
|
||||
System='yes'/>
|
||||
</Component>
|
||||
<Component Id='binary0' Guid='*'>
|
||||
<File
|
||||
Id='exe0'
|
||||
Name='mcl.exe'
|
||||
DiskId='1'
|
||||
Source='$(var.CargoTargetBinDir)\mcl.exe'
|
||||
KeyPath='yes'/>
|
||||
</Component>
|
||||
</Directory>
|
||||
</Directory>
|
||||
</Directory>
|
||||
</Directory>
|
||||
|
||||
<Feature
|
||||
Id='Binaries'
|
||||
Title='Application'
|
||||
Description='Installs all binaries and the license.'
|
||||
Level='1'
|
||||
ConfigurableDirectory='APPLICATIONFOLDER'
|
||||
AllowAdvertise='no'
|
||||
Display='expand'
|
||||
Absent='disallow'>
|
||||
|
||||
<!--
|
||||
Uncomment the following `ComponentRef` tag to add the license
|
||||
sidecar file to the installer.
|
||||
-->
|
||||
<!--<ComponentRef Id='License'/>-->
|
||||
|
||||
<ComponentRef Id='binary0'/>
|
||||
|
||||
<Feature
|
||||
Id='Environment'
|
||||
Title='PATH Environment Variable'
|
||||
Description='Add the install location of the [ProductName] executable to the PATH system environment variable. This allows the [ProductName] executable to be called from any location.'
|
||||
Level='1'
|
||||
Absent='allow'>
|
||||
<ComponentRef Id='Path'/>
|
||||
</Feature>
|
||||
</Feature>
|
||||
|
||||
<SetProperty Id='ARPINSTALLLOCATION' Value='[APPLICATIONFOLDER]' After='CostFinalize'/>
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the following `Icon` and `Property` tags to change the product icon.
|
||||
|
||||
The product icon is the graphic that appears in the Add/Remove
|
||||
Programs control panel for the application.
|
||||
-->
|
||||
<!--<Icon Id='ProductICO' SourceFile='wix\Product.ico'/>-->
|
||||
<!--<Property Id='ARPPRODUCTICON' Value='ProductICO' />-->
|
||||
|
||||
<Property Id='ARPHELPLINK' Value='https://github.com/objz/mcl'/>
|
||||
|
||||
<UI>
|
||||
<UIRef Id='WixUI_FeatureTree'/>
|
||||
|
||||
<!--
|
||||
Enabling the EULA dialog in the installer is a three step process:
|
||||
|
||||
1. Comment out or remove the two `Publish` tags that follow the
|
||||
`WixVariable` tag.
|
||||
2. Uncomment the `<WixVariable Id='WixUILicenseRtf' Value='Path\to\Eula.rft'>` tag further down
|
||||
3. Replace the `Value` attribute of the `WixVariable` tag with
|
||||
the path to a RTF file that will be used as the EULA and
|
||||
displayed in the license agreement dialog.
|
||||
-->
|
||||
<Publish Dialog='WelcomeDlg' Control='Next' Event='NewDialog' Value='CustomizeDlg' Order='99'>1</Publish>
|
||||
<Publish Dialog='CustomizeDlg' Control='Back' Event='NewDialog' Value='WelcomeDlg' Order='99'>1</Publish>
|
||||
|
||||
</UI>
|
||||
|
||||
|
||||
<!--
|
||||
Enabling the EULA dialog in the installer requires uncommenting
|
||||
the following `WixUILicenseRTF` tag and changing the `Value`
|
||||
attribute.
|
||||
-->
|
||||
<!-- <WixVariable Id='WixUILicenseRtf' Value='Relative\Path\to\Eula.rtf'/> -->
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the next `WixVariable` tag to customize the installer's
|
||||
Graphical User Interface (GUI) and add a custom banner image across
|
||||
the top of each screen. See the WiX Toolset documentation for details
|
||||
about customization.
|
||||
|
||||
The banner BMP dimensions are 493 x 58 pixels.
|
||||
-->
|
||||
<!--<WixVariable Id='WixUIBannerBmp' Value='wix\Banner.bmp'/>-->
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the next `WixVariable` tag to customize the installer's
|
||||
Graphical User Interface (GUI) and add a custom image to the first
|
||||
dialog, or screen. See the WiX Toolset documentation for details about
|
||||
customization.
|
||||
|
||||
The dialog BMP dimensions are 493 x 312 pixels.
|
||||
-->
|
||||
<!--<WixVariable Id='WixUIDialogBmp' Value='wix\Dialog.bmp'/>-->
|
||||
|
||||
</Product>
|
||||
|
||||
</Wix>
|
||||
Reference in new issue
Block a user