Update to v0.1.4-alpha
- Remove internal test plugin. - Add Quilt mod loader support. - Add support for pretty output (To use it, enable the plugin "PrettyLog") - Add launch/progress_log apis. - Update some missing translations. CoreLib update to 0.1.7
This commit is contained in:
1 parent
8316722169
commit
01c488d471
30 files changed
+826
-99
No files matched your search
@@ -153,7 +153,7 @@ refresh tokens, and sign-in codes before sharing logs.
|
|||||||
|
|
||||||
### TODO
|
### TODO
|
||||||
|
|
||||||
- [ ] Add support for installing Forge/Neoforge mod loader.
|
- [X] Add support for installing Forge/Neoforge (even Quilt) mod loader.
|
||||||
- [ ] Design the home page.
|
- [ ] Design the home page.
|
||||||
- [ ] Add more custom settings.
|
- [ ] Add more custom settings.
|
||||||
- [ ] Add a usage guide.
|
- [ ] Add a usage guide.
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
LAUNCHER_VERSION = "0.1.3-alpha"
|
LAUNCHER_VERSION = "0.1.4-alpha"
|
||||||
LAUNCHER_NAME = "TapLauncher"
|
LAUNCHER_NAME = "TapLauncher"
|
||||||
LAUNCHER_DIR_NAME = "TapLauncher"
|
LAUNCHER_DIR_NAME = "TapLauncher"
|
||||||
MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/"
|
MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
__version__ = '0.1.6'
|
__version__ = '0.1.7'
|
||||||
__description__ = """
|
__description__ = """
|
||||||
A library for Python-based block game launcher.
|
A library for Python-based block game launcher.
|
||||||
|
|
||||||
|
|||||||
@@ -397,7 +397,8 @@ def generate_feature_placeholders(maps: ArgumentMappings):
|
|||||||
|
|
||||||
def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_path: str, full_args: dict | str
|
def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_path: str, full_args: dict | str
|
||||||
, features: dict | None = None, user_jvm_args: list[str] | None | str = None,
|
, features: dict | None = None, user_jvm_args: list[str] | None | str = None,
|
||||||
strict_placeholders=False) -> list[str]:
|
strict_placeholders=False, *, extra_jvm_args: list[str] | None = None,
|
||||||
|
extra_game_args: list[str] | None = None) -> list[str]:
|
||||||
cmd = [java_path]
|
cmd = [java_path]
|
||||||
game_args, jvm_args = find_game_and_jvm_args(full_args)
|
game_args, jvm_args = find_game_and_jvm_args(full_args)
|
||||||
|
|
||||||
@@ -457,8 +458,10 @@ def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_pa
|
|||||||
parsed_jvm_args[index] = prefix + ",".join(ignored)
|
parsed_jvm_args[index] = prefix + ",".join(ignored)
|
||||||
|
|
||||||
cmd.extend(parsed_jvm_args)
|
cmd.extend(parsed_jvm_args)
|
||||||
|
cmd.extend(extra_jvm_args or [])
|
||||||
cmd.append(main_class)
|
cmd.append(main_class)
|
||||||
cmd.extend(parsed_game_args)
|
cmd.extend(parsed_game_args)
|
||||||
|
cmd.extend(extra_game_args or [])
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+20
-10
@@ -13,12 +13,13 @@ FABRIC_META_LOADER_VERSION_ENDPOINT_V2 = "https://meta.fabricmc.net/v2/versions/
|
|||||||
FABRIC_META_LOADER_MANIFEST_ENDPOINT_V2 = "https://meta.fabricmc.net/v2/versions/loader/{}/{}/profile/json"
|
FABRIC_META_LOADER_MANIFEST_ENDPOINT_V2 = "https://meta.fabricmc.net/v2/versions/loader/{}/{}/profile/json"
|
||||||
FABRIC_MAVEN_URL = "https://maven.fabricmc.net/"
|
FABRIC_MAVEN_URL = "https://maven.fabricmc.net/"
|
||||||
|
|
||||||
def get_full_version_string(version: str, loader_version: str) -> str:
|
def get_full_version_string(version: str, loader_version: str, loader_name="fabric") -> str:
|
||||||
return f"fabric-loader-{loader_version}-{version}"
|
return f"{loader_name}-loader-{loader_version}-{version}"
|
||||||
|
|
||||||
def fetch_fabric_versions(version_manifest_url: str=FABRIC_META_VERSION_ENDPOINT_V2, timeout: int=5) -> list[dict]:
|
def fetch_fabric_versions(version_manifest_url: str=FABRIC_META_VERSION_ENDPOINT_V2, timeout: int=5) -> list[dict]:
|
||||||
try:
|
try:
|
||||||
r = requests.get(version_manifest_url, timeout=timeout)
|
r = requests.get(version_manifest_url, timeout=timeout)
|
||||||
|
r.raise_for_status()
|
||||||
except requests.exceptions.Timeout:
|
except requests.exceptions.Timeout:
|
||||||
raise VersionManifestFetchException(
|
raise VersionManifestFetchException(
|
||||||
"Timeout while fetch from {}".format(version_manifest_url)
|
"Timeout while fetch from {}".format(version_manifest_url)
|
||||||
@@ -43,11 +44,15 @@ def fetch_fabric_versions(version_manifest_url: str=FABRIC_META_VERSION_ENDPOINT
|
|||||||
"JSON decode error while fetch from {}: {}".format(version_manifest_url, e)
|
"JSON decode error while fetch from {}: {}".format(version_manifest_url, e)
|
||||||
)
|
)
|
||||||
|
|
||||||
versions = data.get("versions")
|
# /versions returns an object; /versions/game returns the array directly.
|
||||||
|
versions = data.get("game") if isinstance(data, dict) else data
|
||||||
|
|
||||||
if not versions:
|
if (not isinstance(versions, list) or not versions
|
||||||
|
or any(not isinstance(item, dict)
|
||||||
|
or not isinstance(item.get("version"), str)
|
||||||
|
or not item["version"] for item in versions)):
|
||||||
raise VersionManifestFetchException(
|
raise VersionManifestFetchException(
|
||||||
"Version this is empty or not set yet in mod version manifest"
|
"Game version list is missing, empty or invalid in {}".format(version_manifest_url)
|
||||||
)
|
)
|
||||||
|
|
||||||
return versions
|
return versions
|
||||||
@@ -65,7 +70,7 @@ def is_version_supported_and_stable(fabric_version_list: list[dict], target_vers
|
|||||||
|
|
||||||
return False, None
|
return False, None
|
||||||
|
|
||||||
def get_version_support_loader_list(target_version: str, loader_version_url: str=FABRIC_META_LOADER_VERSION_ENDPOINT_V2, timeout: int=5)\
|
def get_version_support_loader_list(target_version: str, loader_version_url: str=FABRIC_META_LOADER_VERSION_ENDPOINT_V2, timeout: int=5, *, loader_name: str="fabric")\
|
||||||
-> list[dict]:
|
-> list[dict]:
|
||||||
try:
|
try:
|
||||||
r = requests.get(loader_version_url.format(target_version), timeout=timeout)
|
r = requests.get(loader_version_url.format(target_version), timeout=timeout)
|
||||||
@@ -80,7 +85,7 @@ def get_version_support_loader_list(target_version: str, loader_version_url: str
|
|||||||
)
|
)
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
if e.response.status_code == 404 or e.response.status_code == 400:
|
if e.response.status_code == 404 or e.response.status_code == 400:
|
||||||
raise LoaderUnsupportedSpecificVersion("fabric", target_version) from e
|
raise LoaderUnsupportedSpecificVersion(loader_name, target_version) from e
|
||||||
else:
|
else:
|
||||||
raise VersionManifestFetchException(
|
raise VersionManifestFetchException(
|
||||||
"HTTP error while fetch from {}: HTTP Status: {}".format(loader_version_url, e.response.status_code)
|
"HTTP error while fetch from {}: HTTP Status: {}".format(loader_version_url, e.response.status_code)
|
||||||
@@ -97,18 +102,23 @@ def get_version_support_loader_list(target_version: str, loader_version_url: str
|
|||||||
"JSON decode error while fetch from {}: {}".format(loader_version_url, e)
|
"JSON decode error while fetch from {}: {}".format(loader_version_url, e)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if not isinstance(versions, list):
|
||||||
|
raise VersionManifestFetchException(
|
||||||
|
"Invalid loader version list in {}".format(loader_version_url)
|
||||||
|
)
|
||||||
|
|
||||||
loaders = []
|
loaders = []
|
||||||
|
|
||||||
for version in versions:
|
for version in versions:
|
||||||
loader = version.get("loader", None)
|
loader = version.get("loader") if isinstance(version, dict) else None
|
||||||
if not loader:
|
if not isinstance(loader, dict) or not isinstance(loader.get("version"), str) or not loader["version"]:
|
||||||
logger.warning("Found corrupted or unsupported loader manifest")
|
logger.warning("Found corrupted or unsupported loader manifest")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
loaders.append(loader)
|
loaders.append(loader)
|
||||||
|
|
||||||
if not loaders:
|
if not loaders:
|
||||||
raise LoaderUnsupportedSpecificVersion("fabric", target_version)
|
raise LoaderUnsupportedSpecificVersion(loader_name, target_version)
|
||||||
|
|
||||||
return loaders
|
return loaders
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ from core_lib.game.library import (
|
|||||||
generate_filename_from_maven_coordinate, generate_repo_path,
|
generate_filename_from_maven_coordinate, generate_repo_path,
|
||||||
filter_platform_libraries,
|
filter_platform_libraries,
|
||||||
)
|
)
|
||||||
|
from core_lib.game.libraryx import normalize_library_to_common_struct
|
||||||
from core_lib.game.mod.rules import FORGE_LIKE_LOADERS, MOD_LOADER_RULES
|
from core_lib.game.mod.rules import FORGE_LIKE_LOADERS, MOD_LOADER_RULES
|
||||||
|
|
||||||
FORGE_MAVEN_URL = "https://maven.minecraftforge.net/"
|
FORGE_MAVEN_URL = "https://maven.minecraftforge.net/"
|
||||||
@@ -302,6 +303,20 @@ def parse_installer_metadata(extracted_dir: Path, *,
|
|||||||
version_manifest = _read_json_object(manifest_path)
|
version_manifest = _read_json_object(manifest_path)
|
||||||
elif isinstance(profile.get("versionInfo"), dict):
|
elif isinstance(profile.get("versionInfo"), dict):
|
||||||
version_manifest = dict(profile["versionInfo"])
|
version_manifest = dict(profile["versionInfo"])
|
||||||
|
# Legacy installers declare Maven coordinates instead of downloads.
|
||||||
|
# Normalize before URL-less entries can be mistaken for generated files.
|
||||||
|
legacy_install = profile.get("install")
|
||||||
|
embedded_coordinate = legacy_install.get("path") if isinstance(legacy_install, dict) else None
|
||||||
|
libraries = version_manifest.get("libraries")
|
||||||
|
if isinstance(libraries, list):
|
||||||
|
normalized = []
|
||||||
|
for library in libraries:
|
||||||
|
if isinstance(library, dict) and "downloads" not in library:
|
||||||
|
library = normalize_library_to_common_struct(library)
|
||||||
|
if isinstance(library, dict) and library.get("name") == embedded_coordinate:
|
||||||
|
library = dict(library, ignoreMissingURL=True)
|
||||||
|
normalized.append(library)
|
||||||
|
version_manifest["libraries"] = normalized
|
||||||
else:
|
else:
|
||||||
raise ValueError("Unsupported installer: no version JSON or versionInfo found")
|
raise ValueError("Unsupported installer: no version JSON or versionInfo found")
|
||||||
|
|
||||||
@@ -701,6 +716,10 @@ def collect_install_dependencies(install_plan: LoaderInstallPlan, libraries_dir:
|
|||||||
if ignore_missing_url:
|
if ignore_missing_url:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Legacy name/url entries have no downloads field. Explicitly
|
||||||
|
# malformed modern metadata must still fail validation below.
|
||||||
|
if "downloads" not in library:
|
||||||
|
library = normalize_library_to_common_struct(library)
|
||||||
downloads = library.get("downloads")
|
downloads = library.get("downloads")
|
||||||
if not isinstance(downloads, dict):
|
if not isinstance(downloads, dict):
|
||||||
raise ValueError("Library downloads must be an object")
|
raise ValueError("Library downloads must be an object")
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from packaging.version import Version
|
||||||
|
|
||||||
|
from core_lib.game.mod.fabric import (fetch_fabric_versions,
|
||||||
|
is_version_supported_and_stable as is_fabric_version_supported_and_stable,
|
||||||
|
get_version_support_loader_list as get_fabric_version_support_loader_list,
|
||||||
|
get_loader_manifest_from_loader_data as get_fabric_loader_manifest_from_loader_data)
|
||||||
|
|
||||||
|
QUILT_META_VERSION_ENDPOINT = "https://meta.quiltmc.org/v3/versions"
|
||||||
|
QUILT_META_GAME_VERSION_ENDPOINT = "https://meta.quiltmc.org/v3/versions/game"
|
||||||
|
QUILT_META_LOADER_VERSION_ENDPOINT = "https://meta.quiltmc.org/v3/versions/loader/{}"
|
||||||
|
QUILT_META_LOADER_MANIFEST_ENDPOINT = (
|
||||||
|
"https://meta.quiltmc.org/v3/versions/loader/{}/{}/profile/json"
|
||||||
|
)
|
||||||
|
QUILT_MAVEN_URL = "https://maven.quiltmc.org/repository/release/"
|
||||||
|
|
||||||
|
def get_full_version_string(version: str, loader_version: str, loader_name="quilt") -> str:
|
||||||
|
return f"{loader_name}-loader-{loader_version}-{version}"
|
||||||
|
|
||||||
|
def fetch_quilt_versions(version_manifest_url: str=QUILT_META_VERSION_ENDPOINT, timeout: int=5) -> list[dict]:
|
||||||
|
return fetch_fabric_versions(version_manifest_url, timeout)
|
||||||
|
|
||||||
|
is_version_supported_and_stable = is_fabric_version_supported_and_stable
|
||||||
|
|
||||||
|
def get_version_support_loader_list(target_version: str, loader_version_url: str=QUILT_META_LOADER_VERSION_ENDPOINT, timeout: int=5):
|
||||||
|
loaders = get_fabric_version_support_loader_list(
|
||||||
|
target_version, loader_version_url, timeout, loader_name="quilt",
|
||||||
|
)
|
||||||
|
# Quilt Meta lists older loaders first; show the newest release first.
|
||||||
|
return sorted(loaders, key=lambda loader: Version(loader["version"]), reverse=True)
|
||||||
|
|
||||||
|
def get_loader_manifest_from_loader_data(target_version: str, loader_data: dict,
|
||||||
|
loader_manifest_url: str=QUILT_META_LOADER_MANIFEST_ENDPOINT) -> dict:
|
||||||
|
return get_fabric_loader_manifest_from_loader_data(target_version, loader_data, loader_manifest_url)
|
||||||
@@ -339,7 +339,9 @@ def find_useful_part_in_specific_version_manifest(spec_version_manifest: dict,
|
|||||||
if failback_java_version is None:
|
if failback_java_version is None:
|
||||||
failback_java_version = default_java_version()
|
failback_java_version = default_java_version()
|
||||||
|
|
||||||
java_version = spec_version_manifest.get("javaVersion", failback_java_version)
|
java_version = spec_version_manifest.get("javaVersion")
|
||||||
|
if java_version is None:
|
||||||
|
java_version = failback_java_version
|
||||||
|
|
||||||
if not arguments and not legacy_game_args:
|
if not arguments and not legacy_game_args:
|
||||||
raise VersionDataKeyNotFoundException(
|
raise VersionDataKeyNotFoundException(
|
||||||
|
|||||||
+49
-9
@@ -27,7 +27,8 @@ from core_lib.game.mod.mod_core import merge_manifest, PREFER_MOD_LIBRARY, detec
|
|||||||
from core_lib.game.mod.rules import MOD_LOADER_RULES
|
from core_lib.game.mod.rules import MOD_LOADER_RULES
|
||||||
from core_lib.game.version_info import fetch_and_save_version_manifest, get_specific_version_manifest_url_and_hash, \
|
from core_lib.game.version_info import fetch_and_save_version_manifest, get_specific_version_manifest_url_and_hash, \
|
||||||
save_version_manifest, find_useful_part_in_specific_version_manifest, download_core_file, get_latest_version, \
|
save_version_manifest, find_useful_part_in_specific_version_manifest, download_core_file, get_latest_version, \
|
||||||
LATEST_VERSION_ALIASES, check_core_file_exists_and_verify, validate_version_manifest, validate_minecraft_version
|
LATEST_VERSION_ALIASES, check_core_file_exists_and_verify, validate_version_manifest, validate_minecraft_version, \
|
||||||
|
default_java_version
|
||||||
from core_lib.runtime.java import find_java_installations, get_java_version
|
from core_lib.runtime.java import find_java_installations, get_java_version
|
||||||
from core_lib.runtime.mojang import download_java_runtimes, fetch_runtime_manifest, get_current_platform_runtime_key
|
from core_lib.runtime.mojang import download_java_runtimes, fetch_runtime_manifest, get_current_platform_runtime_key
|
||||||
from manager.account import AccountManager, LaunchAccount
|
from manager.account import AccountManager, LaunchAccount
|
||||||
@@ -779,7 +780,9 @@ class JavaManager:
|
|||||||
|
|
||||||
def resolve_runtime(self, *, manifest: dict | None = None, major_version: int | None = None,
|
def resolve_runtime(self, *, manifest: dict | None = None, major_version: int | None = None,
|
||||||
preferred_runtime_id: str | None = None) -> JavaRuntime | None:
|
preferred_runtime_id: str | None = None) -> JavaRuntime | None:
|
||||||
java_requirement = (manifest or {}).get("javaVersion", {})
|
java_requirement = (manifest or {}).get("javaVersion")
|
||||||
|
if java_requirement is None:
|
||||||
|
java_requirement = default_java_version() if manifest is not None else {}
|
||||||
required_major = major_version or java_requirement.get("majorVersion")
|
required_major = major_version or java_requirement.get("majorVersion")
|
||||||
|
|
||||||
if required_major is None:
|
if required_major is None:
|
||||||
@@ -839,7 +842,9 @@ class JavaManager:
|
|||||||
if runtime:
|
if runtime:
|
||||||
return runtime
|
return runtime
|
||||||
|
|
||||||
requirement = manifest.get("javaVersion") or {}
|
requirement = manifest.get("javaVersion")
|
||||||
|
if requirement is None:
|
||||||
|
requirement = default_java_version()
|
||||||
component = requirement.get("component")
|
component = requirement.get("component")
|
||||||
major = requirement.get("majorVersion")
|
major = requirement.get("majorVersion")
|
||||||
|
|
||||||
@@ -1291,6 +1296,25 @@ class LaunchManager:
|
|||||||
class LaunchSignal(QObject):
|
class LaunchSignal(QObject):
|
||||||
finished = Signal(object, object) # LaunchProfile, LaunchResult > LaunchProfilePage.launch_finished()
|
finished = Signal(object, object) # LaunchProfile, LaunchResult > LaunchProfilePage.launch_finished()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extra_arguments(profile: LaunchProfile, version_manifest: dict) -> dict[str, list[str]]:
|
||||||
|
"""Wheel hook: return additional JVM and game arguments for this launch."""
|
||||||
|
return {"jvm": [], "game": []}
|
||||||
|
|
||||||
|
def generate_command(self, profile: LaunchProfile, version_manifest: dict, **kwargs) -> list[str]:
|
||||||
|
plugin_manager = getattr(self.app, "plugin_manager", None)
|
||||||
|
callback = (plugin_manager.get_api("launcher.game.launch.extra_arguments")
|
||||||
|
if plugin_manager is not None else self.extra_arguments)
|
||||||
|
extras = callback(profile, version_manifest)
|
||||||
|
if not isinstance(extras, dict) or set(extras) != {"jvm", "game"}:
|
||||||
|
raise TypeError('Launch extra arguments must be a dictionary with "jvm" and "game" keys.')
|
||||||
|
for arguments in extras.values():
|
||||||
|
if not isinstance(arguments, list) or not all(isinstance(arg, str) for arg in arguments):
|
||||||
|
raise TypeError("Launch extra arguments must be lists of strings.")
|
||||||
|
return generate_launch_command(
|
||||||
|
**kwargs, extra_jvm_args=extras["jvm"], extra_game_args=extras["game"],
|
||||||
|
)
|
||||||
|
|
||||||
def launch(self, profile: LaunchProfile) -> LaunchResult:
|
def launch(self, profile: LaunchProfile) -> LaunchResult:
|
||||||
result = LaunchResult()
|
result = LaunchResult()
|
||||||
|
|
||||||
@@ -1523,7 +1547,9 @@ class LaunchManager:
|
|||||||
"has_custom_resolution": profile.resolution is not None,
|
"has_custom_resolution": profile.resolution is not None,
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd = generate_launch_command(
|
cmd = self.generate_command(
|
||||||
|
profile=profile,
|
||||||
|
version_manifest=version_manifest,
|
||||||
arg_maps=arg_maps,
|
arg_maps=arg_maps,
|
||||||
main_class=main_class,
|
main_class=main_class,
|
||||||
java_path=java_path,
|
java_path=java_path,
|
||||||
@@ -1571,7 +1597,18 @@ class LaunchManager:
|
|||||||
|
|
||||||
def start_launch_task(self, profile: LaunchProfile) -> Thread | None:
|
def start_launch_task(self, profile: LaunchProfile) -> Thread | None:
|
||||||
def worker():
|
def worker():
|
||||||
result = self.launch(profile)
|
try:
|
||||||
|
plugin_manager = getattr(self.app, "plugin_manager", None)
|
||||||
|
callback = (plugin_manager.get_api("launcher.game.launch")
|
||||||
|
if plugin_manager is not None else self.launch)
|
||||||
|
result = callback(profile)
|
||||||
|
if not isinstance(result, LaunchResult):
|
||||||
|
raise TypeError("Launch hook must return a LaunchResult.")
|
||||||
|
if not result.success:
|
||||||
|
self.profile_failed(profile.profile_id)
|
||||||
|
except Exception as exc:
|
||||||
|
self.profile_failed(profile.profile_id)
|
||||||
|
result = LaunchResult().fail(f"Unable to launch game: {exc}")
|
||||||
self.signal.finished.emit(profile, result)
|
self.signal.finished.emit(profile, result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -1603,10 +1640,7 @@ class LaunchManager:
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
self.launching_profiles.discard(profile_id)
|
||||||
self.launching_profiles.remove(profile_id)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
f"Profile {profile_id} exited."
|
f"Profile {profile_id} exited."
|
||||||
@@ -1641,6 +1675,12 @@ class GameManager(QObject):
|
|||||||
self.java, self.game_file, self.account_manager, self.profile_mgr)
|
self.java, self.game_file, self.account_manager, self.profile_mgr)
|
||||||
|
|
||||||
def register_plugin_apis(self, plugin_manager):
|
def register_plugin_apis(self, plugin_manager):
|
||||||
|
from pages.process_log import process_log_output, create_process_log_widget
|
||||||
|
|
||||||
plugin_manager.register_api("launcher.game.versions.list", self.manifest.list_available_profile_versions)
|
plugin_manager.register_api("launcher.game.versions.list", self.manifest.list_available_profile_versions)
|
||||||
plugin_manager.register_api("launcher.game.java.list", self.java.list_runtimes)
|
plugin_manager.register_api("launcher.game.java.list", self.java.list_runtimes)
|
||||||
plugin_manager.register_api("launcher.game.is_profile_running", self.launch.is_profile_running)
|
plugin_manager.register_api("launcher.game.is_profile_running", self.launch.is_profile_running)
|
||||||
|
plugin_manager.register_api("launcher.game.launch", self.launch.launch)
|
||||||
|
plugin_manager.register_api("launcher.game.launch.extra_arguments", self.launch.extra_arguments)
|
||||||
|
plugin_manager.register_api("launcher.process_log.output", process_log_output)
|
||||||
|
plugin_manager.register_api("launcher.process_log.create_widget", create_process_log_widget)
|
||||||
@@ -49,7 +49,6 @@ class CreateProfileRequest:
|
|||||||
java_args: str = ""
|
java_args: str = ""
|
||||||
icon: str = ""
|
icon: str = ""
|
||||||
resolution: tuple[int, int] | None = None
|
resolution: tuple[int, int] | None = None
|
||||||
|
|
||||||
class _Profile_UnsetType:
|
class _Profile_UnsetType:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
+252
-25
@@ -1,15 +1,16 @@
|
|||||||
import threading
|
import threading
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
from PySide6.QtCore import QSize, Qt, QObject, Signal, Slot, QTimer
|
from PySide6.QtCore import QSize, Qt, QObject, Signal, Slot, QTimer
|
||||||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QComboBox, QListWidget, QPushButton, QLabel, QHBoxLayout, \
|
from PySide6.QtWidgets import QWidget, QVBoxLayout, QComboBox, QListWidget, QPushButton, QLabel, QHBoxLayout, \
|
||||||
QSizePolicy, QListWidgetItem, QInputDialog
|
QSizePolicy, QListWidgetItem, QDialog, QLineEdit, QCheckBox, QDialogButtonBox
|
||||||
|
|
||||||
from core_lib.common.exception import (
|
from core_lib.common.exception import (
|
||||||
VersionManifestFetchException, VersionManifestException, LoaderUnsupportedSpecificVersion,
|
VersionManifestFetchException, VersionManifestException, LoaderUnsupportedSpecificVersion,
|
||||||
)
|
)
|
||||||
from core_lib.game.mod import fabric, forge_like
|
from core_lib.game.mod import fabric, forge_like, quilt
|
||||||
from core_lib.game.mod.mod_core import find_useful_part_in_mod_version_manifest
|
from core_lib.game.mod.mod_core import find_useful_part_in_mod_version_manifest
|
||||||
from core_lib.game.version_info import get_all_versions, get_available_version_types
|
from core_lib.game.version_info import get_all_versions, get_available_version_types
|
||||||
from manager.game import ManifestManager, GameManager
|
from manager.game import ManifestManager, GameManager
|
||||||
@@ -150,7 +151,13 @@ class CreateProfilePage(QWidget):
|
|||||||
self.signals.clean_list.connect(self.clean_list)
|
self.signals.clean_list.connect(self.clean_list)
|
||||||
|
|
||||||
# Button event
|
# Button event
|
||||||
self.create_profile_button.clicked.connect(self.create_profile)
|
self.create_profile_button.clicked.connect(
|
||||||
|
lambda _checked=False: self.create_profile(
|
||||||
|
profile_prefix=self.loader_list.get(
|
||||||
|
self.mod_loader_dropdown.currentData(), {}
|
||||||
|
).get("profilePrefix", "Minecraft"),
|
||||||
|
)
|
||||||
|
)
|
||||||
self.install_java_button.clicked.connect(self.create_install_jvm_dialog)
|
self.install_java_button.clicked.connect(self.create_install_jvm_dialog)
|
||||||
|
|
||||||
# Update version list while current type is changed
|
# Update version list while current type is changed
|
||||||
@@ -167,7 +174,7 @@ class CreateProfilePage(QWidget):
|
|||||||
)
|
)
|
||||||
|
|
||||||
self.mod_loader_dropdown.currentTextChanged.connect(
|
self.mod_loader_dropdown.currentTextChanged.connect(
|
||||||
self.update_mod_loader_icon
|
lambda _text: self.update_mod_loader_icon(self.mod_loader_dropdown.currentData())
|
||||||
)
|
)
|
||||||
|
|
||||||
self.loader_list = {
|
self.loader_list = {
|
||||||
@@ -179,21 +186,31 @@ class CreateProfilePage(QWidget):
|
|||||||
},
|
},
|
||||||
"Fabric": {
|
"Fabric": {
|
||||||
"type": "modded",
|
"type": "modded",
|
||||||
|
"profilePrefix": "Fabric",
|
||||||
"icon": Path(self.app.icon_dir, "modLoader", "fabric.png"),
|
"icon": Path(self.app.icon_dir, "modLoader", "fabric.png"),
|
||||||
"loadVersionMethod": getattr(self, "load_fabric_version_list", None),
|
"loadVersionMethod": getattr(self, "load_fabric_version_list", None),
|
||||||
"profileCreateHandler": self.handle_fabric_profile_create,
|
"profileCreateHandler": self.handle_fabric_profile_create,
|
||||||
},
|
},
|
||||||
"NeoForge": {
|
"NeoForge": {
|
||||||
"type": "modded",
|
"type": "modded",
|
||||||
|
"profilePrefix": "NeoForge",
|
||||||
"icon": Path(self.app.icon_dir, "modLoader", "neoforged.ico"),
|
"icon": Path(self.app.icon_dir, "modLoader", "neoforged.ico"),
|
||||||
"loadVersionMethod": getattr(self, "load_neoforge_version_list", None),
|
"loadVersionMethod": getattr(self, "load_neoforge_version_list", None),
|
||||||
"profileCreateHandler": self.handle_neoforge_profile_create,
|
"profileCreateHandler": self.handle_neoforge_profile_create,
|
||||||
},
|
},
|
||||||
"Forge": {
|
"Forge": {
|
||||||
"type": "modded",
|
"type": "modded",
|
||||||
|
"profilePrefix": "Forge",
|
||||||
"icon": Path(self.app.icon_dir, "modLoader", "forge.png"),
|
"icon": Path(self.app.icon_dir, "modLoader", "forge.png"),
|
||||||
"loadVersionMethod": getattr(self, "load_forge_version_list", None),
|
"loadVersionMethod": getattr(self, "load_forge_version_list", None),
|
||||||
"profileCreateHandler": self.handle_forge_profile_create,
|
"profileCreateHandler": self.handle_forge_profile_create,
|
||||||
|
},
|
||||||
|
"Quilt": {
|
||||||
|
"type": "modded",
|
||||||
|
"profilePrefix": "Quilt",
|
||||||
|
"icon": Path(self.app.icon_dir, "modLoader", "quilt.png"),
|
||||||
|
"loadVersionMethod": getattr(self, "load_quilt_version_list", None),
|
||||||
|
"profileCreateHandler": self.handle_quilt_profile_create,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.init_all()
|
self.init_all()
|
||||||
@@ -246,7 +263,10 @@ class CreateProfilePage(QWidget):
|
|||||||
handler = request.custom_handler
|
handler = request.custom_handler
|
||||||
handler(request)
|
handler(request)
|
||||||
else:
|
else:
|
||||||
target_list.addItems(items)
|
if isinstance(target_list, QComboBox):
|
||||||
|
self.add_dropdown_items(target_list, items)
|
||||||
|
else:
|
||||||
|
target_list.addItems(items)
|
||||||
|
|
||||||
index = request.current_index
|
index = request.current_index
|
||||||
if index is None:
|
if index is None:
|
||||||
@@ -329,7 +349,9 @@ class CreateProfilePage(QWidget):
|
|||||||
target = request.target_list
|
target = request.target_list
|
||||||
|
|
||||||
if isinstance(target, QComboBox):
|
if isinstance(target, QComboBox):
|
||||||
selected_text = target.currentText()
|
selected_text = target.currentData()
|
||||||
|
if selected_text is None:
|
||||||
|
selected_text = target.currentText()
|
||||||
elif isinstance(target, QListWidget):
|
elif isinstance(target, QListWidget):
|
||||||
item = target.currentItem()
|
item = target.currentItem()
|
||||||
if isinstance(item, self.DisplayListItem):
|
if isinstance(item, self.DisplayListItem):
|
||||||
@@ -346,13 +368,27 @@ class CreateProfilePage(QWidget):
|
|||||||
|
|
||||||
request.wait_event.set()
|
request.wait_event.set()
|
||||||
|
|
||||||
|
def add_dropdown_items(self, target: QComboBox, items: list[str]):
|
||||||
|
labels = {}
|
||||||
|
if target is self.mod_loader_dropdown:
|
||||||
|
labels = {"Don't Install": self.app.tr_text("Don't Install")}
|
||||||
|
elif target is self.version_type_dropdown:
|
||||||
|
labels = {
|
||||||
|
"release": self.app.tr_text("Release"),
|
||||||
|
"snapshot": self.app.tr_text("Snapshot"),
|
||||||
|
"old_beta": self.app.tr_text("Old Beta"),
|
||||||
|
"old_alpha": self.app.tr_text("Old Alpha"),
|
||||||
|
}
|
||||||
|
for value in items:
|
||||||
|
target.addItem(labels.get(value, value), value)
|
||||||
|
|
||||||
def update_type_dropdown(self, types: list):
|
def update_type_dropdown(self, types: list):
|
||||||
# Move release to top
|
# Move release to top
|
||||||
if "release" in types:
|
if "release" in types:
|
||||||
types.pop(types.index("release"))
|
types.pop(types.index("release"))
|
||||||
types.insert(0, "release")
|
types.insert(0, "release")
|
||||||
|
|
||||||
self.version_type_dropdown.addItems(types)
|
self.add_dropdown_items(self.version_type_dropdown, types)
|
||||||
|
|
||||||
if len(self.version_type_dropdown.currentText()) == 0:
|
if len(self.version_type_dropdown.currentText()) == 0:
|
||||||
self.version_type_dropdown.setCurrentIndex(0)
|
self.version_type_dropdown.setCurrentIndex(0)
|
||||||
@@ -377,7 +413,8 @@ class CreateProfilePage(QWidget):
|
|||||||
display_text = ver_id
|
display_text = ver_id
|
||||||
|
|
||||||
if stable is not None and isinstance(stable, bool):
|
if stable is not None and isinstance(stable, bool):
|
||||||
display_text = f"{ver_id}" + (" (stable)" if stable else "")
|
if stable:
|
||||||
|
display_text = self.app.tr_text("{version} (stable)", version=ver_id)
|
||||||
|
|
||||||
item = self.DisplayListItem(
|
item = self.DisplayListItem(
|
||||||
parent=request.target_list,
|
parent=request.target_list,
|
||||||
@@ -414,10 +451,38 @@ class CreateProfilePage(QWidget):
|
|||||||
thread = threading.Thread(target=self.load_mod_loader_version)
|
thread = threading.Thread(target=self.load_mod_loader_version)
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
class AskProfileInfoDialog(QDialog):
|
||||||
|
def __init__(self, app, title: str, default_profile_name: str, parent=None,):
|
||||||
|
super().__init__(parent)
|
||||||
|
tr_text = app.tr_text
|
||||||
|
self.setWindowTitle(title)
|
||||||
|
layout = QVBoxLayout()
|
||||||
|
|
||||||
|
self.profile_name_label = QLabel(tr_text("Profile name:"))
|
||||||
|
self.profile_name_input = QLineEdit(default_profile_name)
|
||||||
|
self.use_profile_isolation = QCheckBox(tr_text("Use profile isolation"))
|
||||||
|
layout.addWidget(self.profile_name_label)
|
||||||
|
layout.addWidget(self.profile_name_input)
|
||||||
|
layout.addWidget(self.use_profile_isolation)
|
||||||
|
buttons = QDialogButtonBox(
|
||||||
|
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel,
|
||||||
|
)
|
||||||
|
buttons.button(QDialogButtonBox.StandardButton.Ok).setText(tr_text("OK"))
|
||||||
|
buttons.button(QDialogButtonBox.StandardButton.Cancel).setText(tr_text("Cancel"))
|
||||||
|
buttons.accepted.connect(self.accept)
|
||||||
|
buttons.rejected.connect(self.reject)
|
||||||
|
buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(bool(default_profile_name.strip()))
|
||||||
|
self.profile_name_input.textChanged.connect(
|
||||||
|
lambda text: buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(bool(text.strip()))
|
||||||
|
)
|
||||||
|
layout.addWidget(buttons)
|
||||||
|
|
||||||
|
self.setLayout(layout)
|
||||||
|
|
||||||
#
|
#
|
||||||
# Processor
|
# Processor
|
||||||
#
|
#
|
||||||
def create_profile(self):
|
def create_profile(self, profile_prefix="Minecraft"):
|
||||||
request = self.GetSelectedItem(
|
request = self.GetSelectedItem(
|
||||||
target_list=self.version_list,
|
target_list=self.version_list,
|
||||||
)
|
)
|
||||||
@@ -457,7 +522,7 @@ class CreateProfilePage(QWidget):
|
|||||||
return
|
return
|
||||||
|
|
||||||
loader = self.loader_list[loader_name]
|
loader = self.loader_list[loader_name]
|
||||||
profile_create_handler: Callable[[str, str, str | None], None] = loader.get("profileCreateHandler", None)
|
profile_create_handler: Callable[..., None] = loader.get("profileCreateHandler", None)
|
||||||
|
|
||||||
if profile_create_handler is None:
|
if profile_create_handler is None:
|
||||||
self.widget_mgr.signal.show_warning_message.emit(
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
@@ -484,17 +549,17 @@ class CreateProfilePage(QWidget):
|
|||||||
if not loader_version and loader_version is not None:
|
if not loader_version and loader_version is not None:
|
||||||
loader_version = None
|
loader_version = None
|
||||||
|
|
||||||
profile_name, accepted = QInputDialog.getText(
|
dialog = self.AskProfileInfoDialog(
|
||||||
self,
|
self.app,
|
||||||
self.app.tr_text("Create Profile"),
|
self.app.tr_text("Create Profile"),
|
||||||
self.app.tr_text("Profile name:"),
|
f"{profile_prefix} {minecraft_version}",
|
||||||
text=f"Minecraft {minecraft_version}",
|
parent=self,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not accepted:
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||||
return
|
return
|
||||||
|
|
||||||
profile_name = profile_name.strip()
|
profile_name = dialog.profile_name_input.text().strip()
|
||||||
if not profile_name:
|
if not profile_name:
|
||||||
self.widget_mgr.signal.show_warning_message.emit(
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
self.app.tr_text("Profile name cannot be empty."),
|
self.app.tr_text("Profile name cannot be empty."),
|
||||||
@@ -502,11 +567,15 @@ class CreateProfilePage(QWidget):
|
|||||||
return
|
return
|
||||||
|
|
||||||
# Call handler
|
# Call handler
|
||||||
|
profile_dir = (
|
||||||
|
(Path(self.app.work_dir) / "profiles" / uuid4().hex).resolve()
|
||||||
|
if dialog.use_profile_isolation.isChecked() else None
|
||||||
|
)
|
||||||
if callable(profile_create_handler):
|
if callable(profile_create_handler):
|
||||||
profile_create_handler(profile_name, minecraft_version, loader_version)
|
profile_create_handler(profile_name, minecraft_version, loader_version, profile_dir=profile_dir)
|
||||||
|
|
||||||
def handle_vanilla_profile_create(self, profile_name: str, version: str, loader_version: None = None,
|
def handle_vanilla_profile_create(self, profile_name: str, version: str, loader_version: None = None,
|
||||||
switch_to_current=False):
|
switch_to_current=False, *, profile_dir: Path | None = None):
|
||||||
"""
|
"""
|
||||||
Handle vanilla profile creation.
|
Handle vanilla profile creation.
|
||||||
:param profile_name:
|
:param profile_name:
|
||||||
@@ -526,7 +595,7 @@ class CreateProfilePage(QWidget):
|
|||||||
version_id: str = manifest.get("id")
|
version_id: str = manifest.get("id")
|
||||||
version_type = manifest.get(
|
version_type = manifest.get(
|
||||||
"type",
|
"type",
|
||||||
self.version_type_dropdown.currentText() or "custom",
|
self.version_type_dropdown.currentData() or "custom",
|
||||||
)
|
)
|
||||||
|
|
||||||
if version_id is None:
|
if version_id is None:
|
||||||
@@ -537,6 +606,7 @@ class CreateProfilePage(QWidget):
|
|||||||
|
|
||||||
request = CreateProfileRequest(
|
request = CreateProfileRequest(
|
||||||
name=profile_name,
|
name=profile_name,
|
||||||
|
game_dir=profile_dir,
|
||||||
version_id=version_id,
|
version_id=version_id,
|
||||||
version_type=version_type,
|
version_type=version_type,
|
||||||
)
|
)
|
||||||
@@ -556,7 +626,7 @@ class CreateProfilePage(QWidget):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def handle_fabric_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
def handle_fabric_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
||||||
switch_to_current=False):
|
switch_to_current=False, *, profile_dir: Path | None = None):
|
||||||
"""
|
"""
|
||||||
Handle fabric profile creation.
|
Handle fabric profile creation.
|
||||||
:param profile_name:
|
:param profile_name:
|
||||||
@@ -624,12 +694,13 @@ class CreateProfilePage(QWidget):
|
|||||||
|
|
||||||
request = CreateProfileRequest(
|
request = CreateProfileRequest(
|
||||||
name=profile_name,
|
name=profile_name,
|
||||||
|
game_dir=profile_dir,
|
||||||
version_id=version_id,
|
version_id=version_id,
|
||||||
version_type=loader_info["type"] or vanilla_manifest["type"] or "custom",
|
version_type=loader_info["type"] or vanilla_manifest["type"] or "custom",
|
||||||
)
|
)
|
||||||
|
|
||||||
profile_id = self.app.profile_manager.create_profile(
|
profile_id = self.app.profile_manager.create_profile(
|
||||||
request
|
request,
|
||||||
)
|
)
|
||||||
|
|
||||||
if profile_id is None:
|
if profile_id is None:
|
||||||
@@ -646,8 +717,100 @@ class CreateProfilePage(QWidget):
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def handle_quilt_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
||||||
|
switch_to_current=False, *, profile_dir: Path | None = None):
|
||||||
|
"""
|
||||||
|
Handle quilt profile creation.
|
||||||
|
:param profile_name:
|
||||||
|
:param minecraft_version:
|
||||||
|
:param loader_version:
|
||||||
|
:param switch_to_current:
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
if not loader_version:
|
||||||
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
|
self.app.tr_text("Selected a quilt loader version before creating profile."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Create vanilla manifest
|
||||||
|
vanilla_manifest = self.manifest_mgr.get_cached_version_manifest(
|
||||||
|
minecraft_version
|
||||||
|
)
|
||||||
|
if not vanilla_manifest:
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text("Unable to create profile due to vanilla manifest fetch failure."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
version_id = quilt.get_full_version_string(version=minecraft_version, loader_version=loader_version)
|
||||||
|
|
||||||
|
def fetch_loader_manifest(_version_id: str, ) -> tuple[dict, None]:
|
||||||
|
manifest = quilt.get_loader_manifest_from_loader_data(
|
||||||
|
minecraft_version,
|
||||||
|
{"version": loader_version},
|
||||||
|
)
|
||||||
|
manifest["loader"] = "quilt"
|
||||||
|
return manifest, None
|
||||||
|
|
||||||
|
loader_manifest = self.manifest_mgr.get_cached_custom_version_manifest(
|
||||||
|
version_id, fetch_manifest_handler=fetch_loader_manifest, )
|
||||||
|
|
||||||
|
if not loader_manifest:
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text("Unable to create profile due to mod loader manifest fetch failure."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
loader_info = find_useful_part_in_mod_version_manifest(
|
||||||
|
loader_manifest
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check mod info
|
||||||
|
if loader_info["id"] != version_id:
|
||||||
|
self.app.logger.error(f"Quilt manifest ID mismatch: expected {version_id}, got {loader_info["id"]}.")
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text("Unable to create profile. Exising loader version ID mismatch."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if loader_info["inheritsFrom"] != minecraft_version:
|
||||||
|
self.app.logger.error(
|
||||||
|
f"Quilt manifest inherits from "
|
||||||
|
f'{loader_info["inheritsFrom"]}, not {minecraft_version}.'
|
||||||
|
)
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text("Unable to create profile. Inherits version is mismatched as expected."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
request = CreateProfileRequest(
|
||||||
|
name=profile_name,
|
||||||
|
game_dir=profile_dir,
|
||||||
|
version_id=version_id,
|
||||||
|
version_type=loader_info["type"] or vanilla_manifest["type"] or "custom",
|
||||||
|
)
|
||||||
|
|
||||||
|
profile_id = self.app.profile_manager.create_profile(
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
|
||||||
|
if profile_id is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if switch_to_current:
|
||||||
|
if not self.app.profile_manager.set_current_profile(profile_id):
|
||||||
|
return
|
||||||
|
|
||||||
|
self.widget_mgr.signal.show_info_message.emit(
|
||||||
|
self.app.tr_text(
|
||||||
|
"Profile {profile_id} with quilt loader successfully created.",
|
||||||
|
profile_id=profile_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
def handle_forge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
def handle_forge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
||||||
switch_to_current=False):
|
switch_to_current=False, *, profile_dir: Path | None = None):
|
||||||
"""
|
"""
|
||||||
Handle forge profile creation.
|
Handle forge profile creation.
|
||||||
:param profile_name:
|
:param profile_name:
|
||||||
@@ -658,10 +821,11 @@ class CreateProfilePage(QWidget):
|
|||||||
"""
|
"""
|
||||||
self._start_forge_like_profile_create(
|
self._start_forge_like_profile_create(
|
||||||
"forge", profile_name, minecraft_version, loader_version, switch_to_current,
|
"forge", profile_name, minecraft_version, loader_version, switch_to_current,
|
||||||
|
profile_dir=profile_dir,
|
||||||
)
|
)
|
||||||
|
|
||||||
def handle_neoforge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
def handle_neoforge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None,
|
||||||
switch_to_current=False):
|
switch_to_current=False, *, profile_dir: Path | None = None):
|
||||||
"""
|
"""
|
||||||
Handle neoforge profile creation.
|
Handle neoforge profile creation.
|
||||||
:param profile_name:
|
:param profile_name:
|
||||||
@@ -672,11 +836,12 @@ class CreateProfilePage(QWidget):
|
|||||||
"""
|
"""
|
||||||
self._start_forge_like_profile_create(
|
self._start_forge_like_profile_create(
|
||||||
"neoforge", profile_name, minecraft_version, loader_version, switch_to_current,
|
"neoforge", profile_name, minecraft_version, loader_version, switch_to_current,
|
||||||
|
profile_dir=profile_dir,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _start_forge_like_profile_create(self, loader_name: str, profile_name: str,
|
def _start_forge_like_profile_create(self, loader_name: str, profile_name: str,
|
||||||
minecraft_version: str, loader_version: str | None,
|
minecraft_version: str, loader_version: str | None,
|
||||||
switch_to_current: bool = False):
|
switch_to_current: bool = False, *, profile_dir: Path | None = None):
|
||||||
if not loader_version:
|
if not loader_version:
|
||||||
self.widget_mgr.signal.show_warning_message.emit(self.app.tr_text(
|
self.widget_mgr.signal.show_warning_message.emit(self.app.tr_text(
|
||||||
"Select a {loader} version before creating a profile.",
|
"Select a {loader} version before creating a profile.",
|
||||||
@@ -692,6 +857,7 @@ class CreateProfilePage(QWidget):
|
|||||||
dialog = ForgeProfileInstallDialog(
|
dialog = ForgeProfileInstallDialog(
|
||||||
self.app, loader_name, minecraft_version, loader_version,
|
self.app, loader_name, minecraft_version, loader_version,
|
||||||
profile_name, switch_to_current=switch_to_current, parent=self,
|
profile_name, switch_to_current=switch_to_current, parent=self,
|
||||||
|
profile_dir=profile_dir,
|
||||||
)
|
)
|
||||||
self._forge_install_dialog = dialog
|
self._forge_install_dialog = dialog
|
||||||
self.create_profile_button.setEnabled(False)
|
self.create_profile_button.setEnabled(False)
|
||||||
@@ -780,6 +946,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_error_message.emit(
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
self.app.tr_text("Timeout while waiting for selected version."),
|
self.app.tr_text("Timeout while waiting for selected version."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
selected_version = request.result()
|
selected_version = request.result()
|
||||||
|
|
||||||
@@ -787,6 +954,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_warning_message.emit(
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
self.app.tr_text("No version selected."),
|
self.app.tr_text("No version selected."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loaders = fabric.get_version_support_loader_list(
|
loaders = fabric.get_version_support_loader_list(
|
||||||
@@ -822,6 +990,61 @@ class CreateProfilePage(QWidget):
|
|||||||
)
|
)
|
||||||
self.signals.update_list.emit(request)
|
self.signals.update_list.emit(request)
|
||||||
|
|
||||||
|
def load_quilt_version_list(self):
|
||||||
|
self.signals.clean_list.emit(self.mod_loader_version_list)
|
||||||
|
request = self.GetSelectedItem(
|
||||||
|
target_list=self.version_list
|
||||||
|
)
|
||||||
|
self.signals.get_selected_item.emit(request)
|
||||||
|
|
||||||
|
if not request.wait(10):
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text("Timeout while waiting for selected version."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
selected_version = request.result()
|
||||||
|
|
||||||
|
if not selected_version:
|
||||||
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
|
self.app.tr_text("No version selected."),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
loaders = quilt.get_version_support_loader_list(
|
||||||
|
selected_version
|
||||||
|
)
|
||||||
|
except LoaderUnsupportedSpecificVersion as e:
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
format_unsupported_loader_version(e, self.app.tr_text)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
except (VersionManifestFetchException, VersionManifestException) as e:
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text(
|
||||||
|
"Failed to fetch version manifest: {error}", error=e.user_message
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
|
self.app.tr_text(
|
||||||
|
"An unexpected error occurred while fetching version manifest: {error}",
|
||||||
|
error=e,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
request = self.UpdateListRequest(
|
||||||
|
target_list=self.mod_loader_version_list,
|
||||||
|
items=loaders,
|
||||||
|
current_index=0,
|
||||||
|
custom_handler=self.update_version_list,
|
||||||
|
block_signals=True,
|
||||||
|
)
|
||||||
|
self.signals.update_list.emit(request)
|
||||||
|
|
||||||
def load_forge_version_list(self):
|
def load_forge_version_list(self):
|
||||||
self.signals.clean_list.emit(self.mod_loader_version_list)
|
self.signals.clean_list.emit(self.mod_loader_version_list)
|
||||||
request = self.GetSelectedItem(
|
request = self.GetSelectedItem(
|
||||||
@@ -833,6 +1056,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_error_message.emit(
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
self.app.tr_text("Timeout while waiting for selected version."),
|
self.app.tr_text("Timeout while waiting for selected version."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
selected_version = request.result()
|
selected_version = request.result()
|
||||||
|
|
||||||
@@ -840,6 +1064,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_warning_message.emit(
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
self.app.tr_text("No version selected."),
|
self.app.tr_text("No version selected."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loaders = forge_like.get_version_support_loader_list(selected_version)
|
loaders = forge_like.get_version_support_loader_list(selected_version)
|
||||||
@@ -884,6 +1109,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_error_message.emit(
|
self.widget_mgr.signal.show_error_message.emit(
|
||||||
self.app.tr_text("Timeout while waiting for selected version."),
|
self.app.tr_text("Timeout while waiting for selected version."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
selected_version = request.result()
|
selected_version = request.result()
|
||||||
|
|
||||||
@@ -891,6 +1117,7 @@ class CreateProfilePage(QWidget):
|
|||||||
self.widget_mgr.signal.show_warning_message.emit(
|
self.widget_mgr.signal.show_warning_message.emit(
|
||||||
self.app.tr_text("No version selected."),
|
self.app.tr_text("No version selected."),
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loaders = forge_like.get_version_support_loader_list(
|
loaders = forge_like.get_version_support_loader_list(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import math
|
import math
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from PySide6.QtCore import QObject, Qt, Signal, Slot
|
from PySide6.QtCore import QObject, Qt, Signal, Slot
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
@@ -39,13 +40,15 @@ class ForgeProfileInstallDialog(QDialog):
|
|||||||
installed = Signal(object, object)
|
installed = Signal(object, object)
|
||||||
|
|
||||||
def __init__(self, app, loader_name: str, minecraft_version: str, loader_version: str,
|
def __init__(self, app, loader_name: str, minecraft_version: str, loader_version: str,
|
||||||
profile_name: str | None = None, switch_to_current: bool = False, parent=None):
|
profile_name: str | None = None, switch_to_current: bool = False, parent=None,
|
||||||
|
*, profile_dir: Path | None = None):
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.app = app
|
self.app = app
|
||||||
self.loader_name = loader_name
|
self.loader_name = loader_name
|
||||||
self.minecraft_version = minecraft_version
|
self.minecraft_version = minecraft_version
|
||||||
self.loader_version = loader_version
|
self.loader_version = loader_version
|
||||||
self.profile_name = profile_name
|
self.profile_name = profile_name
|
||||||
|
self.profile_dir = profile_dir
|
||||||
self.switch_to_current = switch_to_current
|
self.switch_to_current = switch_to_current
|
||||||
self.is_running = True
|
self.is_running = True
|
||||||
self._started = False
|
self._started = False
|
||||||
@@ -171,8 +174,10 @@ class ForgeProfileInstallDialog(QDialog):
|
|||||||
self._stage_changed("creating the profile")
|
self._stage_changed("creating the profile")
|
||||||
request = CreateProfileRequest(
|
request = CreateProfileRequest(
|
||||||
name=self.profile_name, version_id=version_id,
|
name=self.profile_name, version_id=version_id,
|
||||||
|
game_dir=self.profile_dir,
|
||||||
version_type=manifest.get("type") or vanilla.get("type") or "custom",
|
version_type=manifest.get("type") or vanilla.get("type") or "custom",
|
||||||
)
|
)
|
||||||
|
|
||||||
profile_id = self.app.profile_manager.create_profile(request)
|
profile_id = self.app.profile_manager.create_profile(request)
|
||||||
if profile_id is None:
|
if profile_id is None:
|
||||||
raise RuntimeError(self.app.tr_text(
|
raise RuntimeError(self.app.tr_text(
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ def format_unsupported_loader_version(
|
|||||||
error: LoaderUnsupportedSpecificVersion, translate: Callable[..., str],
|
error: LoaderUnsupportedSpecificVersion, translate: Callable[..., str],
|
||||||
) -> str:
|
) -> str:
|
||||||
loader = {
|
loader = {
|
||||||
"fabric": "Fabric", "forge": "Forge", "neoforge": "NeoForge",
|
"fabric": "Fabric",
|
||||||
|
"forge": "Forge",
|
||||||
|
"neoforge": "NeoForge",
|
||||||
|
"quilt": "Quilt"
|
||||||
}.get(error.loader_name, error.loader_name)
|
}.get(error.loader_name, error.loader_name)
|
||||||
return translate(
|
return translate(
|
||||||
"{loader} does not support Minecraft {version}.",
|
"{loader} does not support Minecraft {version}.",
|
||||||
|
|||||||
@@ -203,6 +203,10 @@ class ManageProfilePage(QWidget):
|
|||||||
file_actions.addStretch()
|
file_actions.addStretch()
|
||||||
editor_layout.addLayout(file_actions)
|
editor_layout.addLayout(file_actions)
|
||||||
|
|
||||||
|
self.plugin_actions = QHBoxLayout()
|
||||||
|
self.plugin_actions.addStretch()
|
||||||
|
editor_layout.addLayout(self.plugin_actions)
|
||||||
|
|
||||||
actions = QHBoxLayout()
|
actions = QHBoxLayout()
|
||||||
duplicate_button = QPushButton(self.app.tr_text("Duplicate"))
|
duplicate_button = QPushButton(self.app.tr_text("Duplicate"))
|
||||||
duplicate_button.clicked.connect(self.duplicate_profile)
|
duplicate_button.clicked.connect(self.duplicate_profile)
|
||||||
@@ -560,6 +564,31 @@ class ManageProfilePage(QWidget):
|
|||||||
plugin_manager.register_api("launcher.manage_profile_page.add_page", self.add_page)
|
plugin_manager.register_api("launcher.manage_profile_page.add_page", self.add_page)
|
||||||
plugin_manager.register_api("launcher.manage_profile_page.remove_page", self.remove_page)
|
plugin_manager.register_api("launcher.manage_profile_page.remove_page", self.remove_page)
|
||||||
plugin_manager.register_api("launcher.manage_profile_page.subscribe_profile", self.subscribe_profile)
|
plugin_manager.register_api("launcher.manage_profile_page.subscribe_profile", self.subscribe_profile)
|
||||||
|
plugin_manager.register_api("launcher.manage_profile_page.add_action", self.add_plugin_action)
|
||||||
|
|
||||||
|
def add_plugin_action(self, text: str, callback: Callable) -> Callable[[], None]:
|
||||||
|
"""Add an editor action and return an idempotent cleanup callback."""
|
||||||
|
if not isinstance(text, str) or not text.strip():
|
||||||
|
raise ValueError("Invalid action text")
|
||||||
|
if not callable(callback):
|
||||||
|
raise TypeError("Action callback must be callable")
|
||||||
|
button = QPushButton(text, self.editor)
|
||||||
|
button.clicked.connect(lambda: callback())
|
||||||
|
self.plugin_actions.insertWidget(self.plugin_actions.count() - 1, button)
|
||||||
|
removed = False
|
||||||
|
|
||||||
|
def cleanup():
|
||||||
|
nonlocal removed
|
||||||
|
if removed:
|
||||||
|
return
|
||||||
|
removed = True
|
||||||
|
self.plugin_actions.removeWidget(button)
|
||||||
|
button.hide()
|
||||||
|
button.setEnabled(False)
|
||||||
|
button.clicked.disconnect()
|
||||||
|
button.deleteLater()
|
||||||
|
|
||||||
|
return cleanup
|
||||||
|
|
||||||
def subscribe_profile(self, callback: Callable) -> Callable[[], None]:
|
def subscribe_profile(self, callback: Callable) -> Callable[[], None]:
|
||||||
"""Send saved details for the editor selection, including the initial state."""
|
"""Send saved details for the editor selection, including the initial state."""
|
||||||
|
|||||||
+82
-9
@@ -5,7 +5,7 @@ from collections.abc import Callable
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PySide6.QtCore import QObject, Signal
|
from PySide6.QtCore import QObject, Signal, Slot
|
||||||
from PySide6.QtGui import QCloseEvent
|
from PySide6.QtGui import QCloseEvent
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QHBoxLayout,
|
QHBoxLayout,
|
||||||
@@ -22,8 +22,20 @@ from PySide6.QtWidgets import (
|
|||||||
from core_lib.qt import messagebox
|
from core_lib.qt import messagebox
|
||||||
|
|
||||||
|
|
||||||
|
def process_log_output(window: "ProcessLogWindow", source: str, text: str | None) -> list[tuple[str, str]]:
|
||||||
|
"""Default Wheel output hook. None marks EOF for the specified stream."""
|
||||||
|
if text is None:
|
||||||
|
return []
|
||||||
|
return [("error" if source == "stderr" else "normal", text)]
|
||||||
|
|
||||||
|
|
||||||
|
def create_process_log_widget(window: "ProcessLogWindow") -> QPlainTextEdit:
|
||||||
|
"""Wheel factory hook for a window's output widget."""
|
||||||
|
return QPlainTextEdit(window)
|
||||||
|
|
||||||
|
|
||||||
class _ProcessSignals(QObject):
|
class _ProcessSignals(QObject):
|
||||||
output = Signal(str, str)
|
output = Signal(str, object)
|
||||||
# Windows may return an unsigned 32-bit exit code (for example
|
# Windows may return an unsigned 32-bit exit code (for example
|
||||||
# 0xFFFFFFFF), which does not fit in Qt's signed Signal(int).
|
# 0xFFFFFFFF), which does not fit in Qt's signed Signal(int).
|
||||||
finished = Signal(object)
|
finished = Signal(object)
|
||||||
@@ -82,7 +94,14 @@ class ProcessLogWindow(QMainWindow):
|
|||||||
|
|
||||||
self.app.apply_qss(Path("process_log.qss"), self.setStyleSheet)
|
self.app.apply_qss(Path("process_log.qss"), self.setStyleSheet)
|
||||||
|
|
||||||
self._signals.output.connect(self._append_output)
|
plugin_manager = getattr(self.app, "plugin_manager", None)
|
||||||
|
if plugin_manager is not None:
|
||||||
|
try:
|
||||||
|
self.set_output_widget(plugin_manager.get_api("launcher.process_log.create_widget")(self))
|
||||||
|
except Exception:
|
||||||
|
self.app.logger.exception("Process log widget hook failed; keeping the default viewer.")
|
||||||
|
|
||||||
|
self._signals.output.connect(self._process_output)
|
||||||
self._signals.finished.connect(self._process_finished)
|
self._signals.finished.connect(self._process_finished)
|
||||||
self._signals.read_failed.connect(self._read_failed)
|
self._signals.read_failed.connect(self._read_failed)
|
||||||
|
|
||||||
@@ -110,6 +129,58 @@ class ProcessLogWindow(QMainWindow):
|
|||||||
def append_message(self, message: str) -> None:
|
def append_message(self, message: str) -> None:
|
||||||
self._append_output("launcher", message)
|
self._append_output("launcher", message)
|
||||||
|
|
||||||
|
def set_output_widget(self, widget: QPlainTextEdit) -> None:
|
||||||
|
"""Replace the viewer on the GUI thread, preserving stored output."""
|
||||||
|
if not isinstance(widget, QPlainTextEdit):
|
||||||
|
raise TypeError("Process log widget must be a QPlainTextEdit or subclass.")
|
||||||
|
if widget is self.log_output:
|
||||||
|
return
|
||||||
|
widget.setReadOnly(True)
|
||||||
|
widget.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
|
||||||
|
widget.setMaximumBlockCount(self.MAX_LOG_LINES)
|
||||||
|
widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
|
||||||
|
previous = self.log_output
|
||||||
|
self.centralWidget().layout().replaceWidget(previous, widget)
|
||||||
|
self.log_output = widget
|
||||||
|
self._rebuild_output()
|
||||||
|
previous.hide()
|
||||||
|
previous.deleteLater()
|
||||||
|
widget.show()
|
||||||
|
|
||||||
|
def _display_entry(self, line_type: str, message: str) -> None:
|
||||||
|
append = getattr(self.log_output, "append_log_entry", None)
|
||||||
|
if callable(append):
|
||||||
|
append(line_type, message)
|
||||||
|
else:
|
||||||
|
self.log_output.appendPlainText(message)
|
||||||
|
|
||||||
|
def _rebuild_output(self) -> None:
|
||||||
|
rebuild = getattr(self.log_output, "set_log_entries", None)
|
||||||
|
if callable(rebuild):
|
||||||
|
rebuild(self.lines)
|
||||||
|
else:
|
||||||
|
self.log_output.setPlainText("\n".join(message for _, message in self.lines))
|
||||||
|
|
||||||
|
@Slot(str, object)
|
||||||
|
def _process_output(self, source: str, text: str | None) -> None:
|
||||||
|
"""Run plugin parsing on the GUI thread before storing/displaying output."""
|
||||||
|
try:
|
||||||
|
plugin_manager = getattr(self.app, "plugin_manager", None)
|
||||||
|
callback = (plugin_manager.get_api("launcher.process_log.output")
|
||||||
|
if plugin_manager is not None else process_log_output)
|
||||||
|
events = callback(self, source, text)
|
||||||
|
if not isinstance(events, list) or not all(
|
||||||
|
isinstance(event, tuple) and len(event) == 2
|
||||||
|
and all(isinstance(value, str) for value in event)
|
||||||
|
for event in events
|
||||||
|
):
|
||||||
|
raise TypeError("Process log output hook must return a list of (type, message) tuples.")
|
||||||
|
except Exception:
|
||||||
|
self.app.logger.exception("Process log output hook failed; displaying raw output.")
|
||||||
|
events = process_log_output(self, source, text)
|
||||||
|
for line_type, message in events:
|
||||||
|
self._append_output(line_type, message)
|
||||||
|
|
||||||
def _append_output(self, line_type: str, message: str) -> None:
|
def _append_output(self, line_type: str, message: str) -> None:
|
||||||
"""Store and display one line, trimming old output in bounded chunks."""
|
"""Store and display one line, trimming old output in bounded chunks."""
|
||||||
if len(self.lines) >= self.MAX_LOG_LINES:
|
if len(self.lines) >= self.MAX_LOG_LINES:
|
||||||
@@ -132,12 +203,10 @@ class ProcessLogWindow(QMainWindow):
|
|||||||
self.lines.insert(0, ("truncated", marker))
|
self.lines.insert(0, ("truncated", marker))
|
||||||
|
|
||||||
# Keep the widget and the saved-log buffer identical after trimming.
|
# Keep the widget and the saved-log buffer identical after trimming.
|
||||||
self.log_output.setPlainText(
|
self._rebuild_output()
|
||||||
"\n".join(stored_message for _, stored_message in self.lines)
|
|
||||||
)
|
|
||||||
|
|
||||||
self.lines.append((line_type, message))
|
self.lines.append((line_type, message))
|
||||||
self.log_output.appendPlainText(message)
|
self._display_entry(line_type, message)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def last_error_message(self) -> str | None:
|
def last_error_message(self) -> str | None:
|
||||||
@@ -147,9 +216,11 @@ class ProcessLogWindow(QMainWindow):
|
|||||||
try:
|
try:
|
||||||
if self.process.stdout is not None:
|
if self.process.stdout is not None:
|
||||||
for line in self.process.stdout:
|
for line in self.process.stdout:
|
||||||
self._signals.output.emit("normal", line.rstrip("\r\n"))
|
self._signals.output.emit("stdout", line.rstrip("\r\n"))
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._signals.read_failed.emit(str(exc))
|
self._signals.read_failed.emit(str(exc))
|
||||||
|
finally:
|
||||||
|
self._signals.output.emit("stdout", None)
|
||||||
|
|
||||||
def _read_stderr(self) -> None:
|
def _read_stderr(self) -> None:
|
||||||
try:
|
try:
|
||||||
@@ -159,9 +230,11 @@ class ProcessLogWindow(QMainWindow):
|
|||||||
if message.strip():
|
if message.strip():
|
||||||
self._last_error_message = message.strip()
|
self._last_error_message = message.strip()
|
||||||
self._stderr_lines.append(message)
|
self._stderr_lines.append(message)
|
||||||
self._signals.output.emit("error", message)
|
self._signals.output.emit("stderr", message)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._signals.read_failed.emit(str(exc))
|
self._signals.read_failed.emit(str(exc))
|
||||||
|
finally:
|
||||||
|
self._signals.output.emit("stderr", None)
|
||||||
|
|
||||||
def _wait_for_process(self) -> None:
|
def _wait_for_process(self) -> None:
|
||||||
exit_code = self._normalize_exit_code(self.process.wait())
|
exit_code = self._normalize_exit_code(self.process.wait())
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "testlauncher"
|
name = "testlauncher"
|
||||||
version = "0.1.2a0"
|
version = "0.1.4a0"
|
||||||
description = "A lightweight Minecraft launcher."
|
description = "A lightweight Minecraft launcher."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from TapLauncher import PluginContext
|
||||||
|
from .log4j import Log4jPlugin
|
||||||
|
|
||||||
|
def entry(context: PluginContext) -> None:
|
||||||
|
plugin = Log4jPlugin(context)
|
||||||
|
context.on_cleanup(plugin.cleanup)
|
||||||
|
context.override_api("launcher.game.launch.extra_arguments", plugin.extra_arguments)
|
||||||
|
context.override_api("launcher.process_log.output", plugin.output)
|
||||||
|
context.override_api("launcher.process_log.create_widget", plugin.create_widget)
|
||||||
|
context.logger.info("Log4j hooks initialized")
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""Official Log4j configuration and streaming console XML support."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from weakref import WeakKeyDictionary, WeakSet
|
||||||
|
from xml.etree import ElementTree as ET
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
|
MAX_CONFIG_BYTES = 1024 * 1024
|
||||||
|
MAX_EVENT_CHARS = 1024 * 1024
|
||||||
|
EVENT_START = re.compile(r"<(?:log4j:)?Event\b")
|
||||||
|
EVENT_END = re.compile(r"</(?:log4j:)?Event\s*>|<!\[CDATA\[|<!--")
|
||||||
|
|
||||||
|
|
||||||
|
def _event_end(text: str) -> int | None:
|
||||||
|
"""Locate the closing tag without treating CDATA/message text as markup."""
|
||||||
|
offset = 0
|
||||||
|
while match := EVENT_END.search(text, offset):
|
||||||
|
if match.group().startswith("</"):
|
||||||
|
return match.end()
|
||||||
|
terminator = "]]>" if match.group() == "<![CDATA[" else "-->"
|
||||||
|
end = text.find(terminator, match.end())
|
||||||
|
if end < 0:
|
||||||
|
return None
|
||||||
|
offset = end + len(terminator)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _local_name(tag: str) -> str:
|
||||||
|
return tag.rsplit("}", 1)[-1]
|
||||||
|
|
||||||
|
|
||||||
|
def _format_event(xml: str) -> list[tuple[str, str]]:
|
||||||
|
# Minecraft's LegacyXMLLayout emits log4j-prefixed fragments without a root.
|
||||||
|
if "<!DOCTYPE" in xml.upper() or "<!ENTITY" in xml.upper():
|
||||||
|
raise ValueError("Unsupported XML declaration in log event")
|
||||||
|
root = ET.fromstring('<root xmlns:log4j="http://jakarta.apache.org/log4j/">' + xml + "</root>")
|
||||||
|
event = root[0]
|
||||||
|
level = event.get("level", "INFO").upper()
|
||||||
|
thread = event.get("thread", "unknown")
|
||||||
|
logger = event.get("logger", event.get("loggerName", ""))
|
||||||
|
timestamp = event.get("timestamp", event.get("timeMillis"))
|
||||||
|
time_text = ""
|
||||||
|
if timestamp is not None:
|
||||||
|
try:
|
||||||
|
time_text = "[" + datetime.fromtimestamp(int(timestamp) / 1000).strftime("%H:%M:%S") + "] "
|
||||||
|
except (ValueError, OverflowError, OSError):
|
||||||
|
pass
|
||||||
|
prefix = f"{time_text}[{thread}/{level}] "
|
||||||
|
if logger:
|
||||||
|
prefix += f"[{logger}] "
|
||||||
|
messages = []
|
||||||
|
throwables = []
|
||||||
|
for child in event:
|
||||||
|
name = _local_name(child.tag).lower()
|
||||||
|
if name == "message":
|
||||||
|
messages.append("".join(child.itertext()))
|
||||||
|
elif name == "throwable":
|
||||||
|
content = "".join(child.itertext()).strip()
|
||||||
|
if content:
|
||||||
|
throwables.append(content)
|
||||||
|
message = "\n".join(messages)
|
||||||
|
if throwables:
|
||||||
|
message += ("\n" if message else "") + "\n".join(throwables)
|
||||||
|
return [(level, prefix + message)]
|
||||||
|
|
||||||
|
|
||||||
|
class LogParser:
|
||||||
|
def __init__(self, source: str):
|
||||||
|
self.raw_type = "error" if source == "stderr" else "normal"
|
||||||
|
self.pending = ""
|
||||||
|
|
||||||
|
def _raw(self, text: str) -> list[tuple[str, str]]:
|
||||||
|
return [(self.raw_type, line) for line in text.splitlines()]
|
||||||
|
|
||||||
|
def feed(self, text: str | None) -> list[tuple[str, str]]:
|
||||||
|
if text is None:
|
||||||
|
pending, self.pending = self.pending, ""
|
||||||
|
return self._raw(pending)
|
||||||
|
if not self.pending and not EVENT_START.search(text):
|
||||||
|
return [(self.raw_type, text)]
|
||||||
|
self.pending += text + "\n"
|
||||||
|
output = []
|
||||||
|
while self.pending:
|
||||||
|
start = EVENT_START.search(self.pending)
|
||||||
|
if start is None:
|
||||||
|
output.extend(self._raw(self.pending))
|
||||||
|
self.pending = ""
|
||||||
|
break
|
||||||
|
prefix, self.pending = self.pending[:start.start()], self.pending[start.start():]
|
||||||
|
if prefix.strip():
|
||||||
|
output.extend(self._raw(prefix))
|
||||||
|
end = _event_end(self.pending)
|
||||||
|
if end is None:
|
||||||
|
if len(self.pending) > MAX_EVENT_CHARS:
|
||||||
|
output.extend(self._raw(self.pending))
|
||||||
|
self.pending = ""
|
||||||
|
break
|
||||||
|
xml, self.pending = self.pending[:end], self.pending[end:]
|
||||||
|
# The newline emitted after an XML fragment is a delimiter.
|
||||||
|
self.pending = self.pending.removeprefix("\r\n").removeprefix("\n")
|
||||||
|
try:
|
||||||
|
output.extend(_format_event(xml))
|
||||||
|
except (ET.ParseError, ValueError):
|
||||||
|
output.extend(self._raw(xml))
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class Log4jPlugin:
|
||||||
|
def __init__(self, context):
|
||||||
|
self.context = context
|
||||||
|
self.parsers = WeakKeyDictionary()
|
||||||
|
self.windows = WeakSet()
|
||||||
|
self._download_lock = threading.Lock()
|
||||||
|
|
||||||
|
def extra_arguments(self, profile, version_manifest: dict) -> dict[str, list[str]]:
|
||||||
|
logging = version_manifest.get("logging", {}).get("client")
|
||||||
|
if not logging:
|
||||||
|
return {"jvm": [], "game": []}
|
||||||
|
if logging.get("type") != "log4j2-xml":
|
||||||
|
self.context.logger.warning("Unsupported client logging type: %s", logging.get("type"))
|
||||||
|
return {"jvm": [], "game": []}
|
||||||
|
path = self._prepare_config(logging["file"])
|
||||||
|
argument = logging["argument"]
|
||||||
|
if not isinstance(argument, str) or "${path}" not in argument:
|
||||||
|
raise ValueError("Invalid client logging argument")
|
||||||
|
# A Windows drive prefix (C:/...) can be interpreted as a URI scheme.
|
||||||
|
# Use an explicit file URI, including escaping spaces and Unicode.
|
||||||
|
return {"jvm": [argument.replace("${path}", path.as_uri())], "game": []}
|
||||||
|
|
||||||
|
def _prepare_config(self, file: dict) -> Path:
|
||||||
|
sha1 = file["sha1"].lower()
|
||||||
|
if re.fullmatch(r"[0-9a-f]{40}", sha1) is None:
|
||||||
|
raise ValueError("Invalid client logging SHA-1")
|
||||||
|
expected_size = file["size"]
|
||||||
|
if not isinstance(expected_size, int) or not 0 < expected_size <= MAX_CONFIG_BYTES:
|
||||||
|
raise ValueError("Invalid client logging configuration size")
|
||||||
|
# Content-addressed paths also avoid trusting a manifest filename as a path.
|
||||||
|
path = (Path(self.context.data_dir) / "log_configs" / sha1 / "client.xml").resolve()
|
||||||
|
|
||||||
|
def verified(data):
|
||||||
|
return len(data) == expected_size and hashlib.sha1(data).hexdigest() == sha1
|
||||||
|
|
||||||
|
with self._download_lock:
|
||||||
|
if path.is_file() and path.stat().st_size == expected_size and verified(path.read_bytes()):
|
||||||
|
return path
|
||||||
|
data = bytearray()
|
||||||
|
with requests.get(file["url"], stream=True, timeout=(10, 30)) as response:
|
||||||
|
response.raise_for_status()
|
||||||
|
for chunk in response.iter_content(8192):
|
||||||
|
data.extend(chunk)
|
||||||
|
if len(data) > expected_size:
|
||||||
|
raise ValueError("Client logging configuration exceeds expected size")
|
||||||
|
if not verified(data):
|
||||||
|
raise ValueError("Client logging configuration size or SHA-1 mismatch")
|
||||||
|
ET.fromstring(data) # Fail before launching if the configuration is invalid XML.
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temporary = None
|
||||||
|
try:
|
||||||
|
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
||||||
|
temporary = Path(stream.name)
|
||||||
|
stream.write(data)
|
||||||
|
temporary.replace(path)
|
||||||
|
finally:
|
||||||
|
if temporary is not None:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def create_widget(self, window):
|
||||||
|
from .log_widget import ColoredLogOutput
|
||||||
|
|
||||||
|
self.windows.add(window)
|
||||||
|
return ColoredLogOutput(window)
|
||||||
|
|
||||||
|
def output(self, window, source: str, text: str | None) -> list[tuple[str, str]]:
|
||||||
|
from .log_widget import ColoredLogOutput
|
||||||
|
|
||||||
|
# Also upgrade windows that were opened before the plugin was enabled.
|
||||||
|
if hasattr(window, "set_output_widget") and not isinstance(window.log_output, ColoredLogOutput):
|
||||||
|
window.set_output_widget(self.create_widget(window))
|
||||||
|
streams = self.parsers.setdefault(window, {})
|
||||||
|
parser = streams.setdefault(source, LogParser(source))
|
||||||
|
events = parser.feed(text)
|
||||||
|
if text is None:
|
||||||
|
streams.pop(source, None)
|
||||||
|
if not streams:
|
||||||
|
self.parsers.pop(window, None)
|
||||||
|
return events
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
# Overrides are restored before this callback by Wheel's reverse cleanup.
|
||||||
|
for window, streams in list(self.parsers.items()):
|
||||||
|
for parser in streams.values():
|
||||||
|
for line_type, message in parser.feed(None):
|
||||||
|
window._append_output(line_type, message)
|
||||||
|
self.parsers.clear()
|
||||||
|
from .log_widget import ColoredLogOutput
|
||||||
|
from pages.process_log import create_process_log_widget
|
||||||
|
|
||||||
|
for window in list(self.windows):
|
||||||
|
if isinstance(window.log_output, ColoredLogOutput):
|
||||||
|
window.set_output_widget(create_process_log_widget(window))
|
||||||
|
self.windows.clear()
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Plain-text log viewer with severity colors and no HTML interpretation."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from PySide6.QtGui import QColor, QPalette, QTextCharFormat, QTextCursor
|
||||||
|
from PySide6.QtWidgets import QPlainTextEdit
|
||||||
|
|
||||||
|
|
||||||
|
class ColoredLogOutput(QPlainTextEdit):
|
||||||
|
DARK_COLORS = {
|
||||||
|
"TRACE": "#9299a5", "DEBUG": "#93a8c4", "INFO": "#8ed49f",
|
||||||
|
"WARN": "#f2c66d", "WARNING": "#f2c66d", "ERROR": "#ff8585", "FATAL": "#f099d7",
|
||||||
|
}
|
||||||
|
LIGHT_COLORS = {
|
||||||
|
"TRACE": "#616977", "DEBUG": "#405e91", "INFO": "#24713a",
|
||||||
|
"WARN": "#946000", "WARNING": "#946000", "ERROR": "#bc2424", "FATAL": "#952278",
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(self, parent=None):
|
||||||
|
super().__init__(parent)
|
||||||
|
self._has_entries = False
|
||||||
|
|
||||||
|
def append_log_entry(self, line_type: str, message: str) -> None:
|
||||||
|
level = line_type.upper()
|
||||||
|
if line_type in {"normal", "error"}:
|
||||||
|
match = re.search(r"\[[^\]\n]*/(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]", message)
|
||||||
|
warning = re.match(r"^(WARNING|WARN|ERROR|FATAL):", message)
|
||||||
|
if match or warning:
|
||||||
|
level = (match or warning).group(1)
|
||||||
|
colors = (self.LIGHT_COLORS if self.palette().color(QPalette.ColorRole.Base).lightness() > 128
|
||||||
|
else self.DARK_COLORS)
|
||||||
|
fmt = QTextCharFormat()
|
||||||
|
fmt.setForeground(QColor(colors[level]) if level in colors else self.palette().color(QPalette.ColorRole.Text))
|
||||||
|
fmt.setFontWeight(700 if level == "FATAL" else 400)
|
||||||
|
scroll = self.verticalScrollBar()
|
||||||
|
follow = scroll.value() >= scroll.maximum()
|
||||||
|
cursor = QTextCursor(self.document())
|
||||||
|
cursor.movePosition(QTextCursor.MoveOperation.End)
|
||||||
|
cursor.beginEditBlock()
|
||||||
|
if self._has_entries:
|
||||||
|
cursor.insertBlock()
|
||||||
|
cursor.insertText(message, fmt)
|
||||||
|
cursor.endEditBlock()
|
||||||
|
self._has_entries = True
|
||||||
|
if follow:
|
||||||
|
scroll.setValue(scroll.maximum())
|
||||||
|
|
||||||
|
def set_log_entries(self, entries) -> None:
|
||||||
|
self.clear()
|
||||||
|
self._has_entries = False
|
||||||
|
for line_type, message in entries:
|
||||||
|
self.append_log_entry(line_type, message)
|
||||||
File renamed without changes.
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.7 MiB |
@@ -0,0 +1,8 @@
|
|||||||
|
group = "net.wei"
|
||||||
|
id = "prettylog"
|
||||||
|
name = "PrettyLog"
|
||||||
|
version = "1.0.0"
|
||||||
|
api_version = ">=0.0.2"
|
||||||
|
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
||||||
|
icon = "nugget.gif" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
||||||
|
description = "Make log output more pretty! Use the version's official Log4j client XML configuration and display parsed game logs."
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
from TapLauncher import Plugin, PluginContext
|
|
||||||
|
|
||||||
class ExperimentalFarm(Plugin):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def entry(context: PluginContext) -> None:
|
|
||||||
context.data_dir.mkdir(parents=True, exist_ok=True)
|
|
||||||
context.logger.info("Experimental Farm initialized")
|
|
||||||
list_apis = context.get_api("launcher.apis.list")
|
|
||||||
context.logger.debug("Available launcher APIs: %s", list_apis())
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
group = "net.wei"
|
|
||||||
id = "experimentalfarm"
|
|
||||||
name = "實驗田"
|
|
||||||
version = "1.0.0"
|
|
||||||
api_version = ">=0.0.1"
|
|
||||||
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
|
||||||
icon = "nugget.gif" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
|
||||||
description = "A experimental plugin!"
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
from TapLauncher import PluginContext, core
|
|
||||||
|
|
||||||
def entry(context: PluginContext) -> None:
|
|
||||||
# init
|
|
||||||
context.data_dir.mkdir(parents=True, exist_ok=True)
|
|
||||||
logger = context.logger
|
|
||||||
context.logger.info("Forge test initialized")
|
|
||||||
|
|
||||||
# Start
|
|
||||||
versions = core.fetch_forge_versions()
|
|
||||||
logger.info(f"Found {len(versions)} versions")
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
@@ -1,8 +0,0 @@
|
|||||||
group = "net.wei"
|
|
||||||
id = "forgetest"
|
|
||||||
name = "ForgeTest"
|
|
||||||
version = "1.0.0"
|
|
||||||
api_version = ">=0.0.1"
|
|
||||||
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
|
||||||
icon = "neoforged.ico" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
|
||||||
description = "Test forge support!"
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 6.5 KiB |
@@ -1,4 +1,13 @@
|
|||||||
{
|
{
|
||||||
|
"OK": "OK",
|
||||||
|
"Old Alpha": "Old Alpha",
|
||||||
|
"Old Beta": "Old Beta",
|
||||||
|
"Release": "Release",
|
||||||
|
"Snapshot": "Snapshot",
|
||||||
|
"Use profile isolation": "Use profile isolation",
|
||||||
|
"{version} (stable)": "{version} (stable)",
|
||||||
|
"Selected a quilt loader version before creating profile.": "Selected a quilt loader version before creating profile.",
|
||||||
|
"Profile {profile_id} with quilt loader successfully created.": "Profile {profile_id} with quilt loader successfully created.",
|
||||||
"Clear selection": "Clear selection",
|
"Clear selection": "Clear selection",
|
||||||
"Select a mod to view its details.": "Select a mod to view its details.",
|
"Select a mod to view its details.": "Select a mod to view its details.",
|
||||||
"Install {count} selected mods": "Install {count} selected mods",
|
"Install {count} selected mods": "Install {count} selected mods",
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
{
|
{
|
||||||
|
"OK": "確定",
|
||||||
|
"Old Alpha": "舊版 Alpha",
|
||||||
|
"Old Beta": "舊版 Beta",
|
||||||
|
"Release": "正式版",
|
||||||
|
"Snapshot": "快照版",
|
||||||
|
"Use profile isolation": "使用獨立的遊戲目錄",
|
||||||
|
"{version} (stable)": "{version}(穩定版)",
|
||||||
|
"Selected a quilt loader version before creating profile.": "請先選擇 Quilt 載入器版本再建立設定檔。",
|
||||||
|
"Profile {profile_id} with quilt loader successfully created.": "已成功建立使用 Quilt 載入器的設定檔 {profile_id}。",
|
||||||
"Clear selection": "清除勾選",
|
"Clear selection": "清除勾選",
|
||||||
"Select a mod to view its details.": "選擇模組以查看詳細資訊。",
|
"Select a mod to view its details.": "選擇模組以查看詳細資訊。",
|
||||||
"Install {count} selected mods": "安裝已勾選的 {count} 個模組",
|
"Install {count} selected mods": "安裝已勾選的 {count} 個模組",
|
||||||
|
|||||||
@@ -108,3 +108,27 @@ def test_legacy_selector_excludes_missing_runtimes(java_manager):
|
|||||||
runtime = add_runtime(java_manager)
|
runtime = add_runtime(java_manager)
|
||||||
runtime.executable.unlink()
|
runtime.executable.unlink()
|
||||||
assert java_manager.get_or_cache_jvm_settings() == []
|
assert java_manager.get_or_cache_jvm_settings() == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("manifest", [{}, {"javaVersion": None}])
|
||||||
|
def test_legacy_manifest_resolves_java_8(java_manager, manifest):
|
||||||
|
add_runtime(java_manager, "modern", major=21)
|
||||||
|
legacy = add_runtime(java_manager, "legacy", major=8)
|
||||||
|
assert java_manager.resolve_runtime(manifest=manifest) == legacy
|
||||||
|
assert java_manager.ensure_runtime(manifest) == legacy
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("manifest", [{}, {"javaVersion": None}])
|
||||||
|
def test_legacy_manifest_installs_java_8(java_manager, monkeypatch, manifest):
|
||||||
|
monkeypatch.setattr("manager.game.find_java_installations", lambda _: ([], []))
|
||||||
|
runtime = JavaRuntime("legacy", 8, "1.8.0", Path("java"), Path("jre"), "managed")
|
||||||
|
install = Mock(return_value=runtime)
|
||||||
|
monkeypatch.setattr(java_manager, "install_runtime", install)
|
||||||
|
|
||||||
|
assert java_manager.ensure_runtime(manifest, auto_install=True) == runtime
|
||||||
|
install.assert_called_once_with("jre-legacy", progress_callback=None, redownload_callback=None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_without_requirement_returns_none(java_manager):
|
||||||
|
add_runtime(java_manager, "legacy", major=8)
|
||||||
|
assert java_manager.resolve_runtime() is None
|
||||||
Reference in new issue
Block a user