From 83167221699138356d67138e2cc677d375d618e0 Mon Sep 17 00:00:00 2001 From: wei Date: Sun, 1 Nov 2026 17:35:22 +0800 Subject: [PATCH] Update to v0.1.3-alpha - Add Forge/Neoforge support. - Now launcher will try to recreate the manifest if specific version does not exist. - Themed "ItLooksLikeOfficial" scrollbar. CoreLib update to 0.1.6 --- constant.py | 2 +- core_lib/__init__.py | 673 ++++++++- core_lib/common/exception.py | 13 +- core_lib/game/argument.py | 15 +- core_lib/game/library_core.py | 35 +- core_lib/game/libraryx.py | 14 +- core_lib/game/mod/fabric.py | 14 +- core_lib/game/mod/forge_like.py | 1254 +++++++++++++++++ core_lib/game/mod/mod_core.py | 80 +- core_lib/game/mod/rules.py | 20 +- core_lib/game/version_info.py | 9 +- manager/game.py | 276 +++- pages/add_modded_version.py | 123 +- pages/create_profile.py | 215 ++- pages/forge_profile_install_dialog.py | 217 +++ pages/loader_errors.py | 17 + .../builtin_plugins/forge_test/__init__.py | 11 + .../builtin_plugins/forge_test/neoforged.ico | Bin 0 -> 67646 bytes .../builtin_plugins/forge_test/plugin.toml | 8 + resources/icons/modLoader/forge.png | Bin 0 -> 17896 bytes .../styles/main.qss | 55 + resources/translations/en.json | 37 + resources/translations/zh-TW.json | 39 +- 23 files changed, 3000 insertions(+), 127 deletions(-) create mode 100644 core_lib/game/mod/forge_like.py create mode 100644 pages/forge_profile_install_dialog.py create mode 100644 pages/loader_errors.py create mode 100644 resources/builtin_plugins/forge_test/__init__.py create mode 100644 resources/builtin_plugins/forge_test/neoforged.ico create mode 100644 resources/builtin_plugins/forge_test/plugin.toml create mode 100644 resources/icons/modLoader/forge.png diff --git a/constant.py b/constant.py index 88e6403..a6be075 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.1.2-alpha" +LAUNCHER_VERSION = "0.1.3-alpha" LAUNCHER_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" diff --git a/core_lib/__init__.py b/core_lib/__init__.py index 3c5b10f..d18cebb 100644 --- a/core_lib/__init__.py +++ b/core_lib/__init__.py @@ -1,6 +1,673 @@ -__version__ = '0.1.5' +__version__ = '0.1.6' __description__ = """ -The core library of the *Launcher* +A library for Python-based block game launcher. Some reference implementation are from bk_core. -""" \ No newline at end of file +""" + +from .common.common import ( + DEFAULT_HASH_CHUNK_SIZE, + DEFAULT_DOWNLOAD_CHUNK_SIZE, + THREADED_DOWNLOAD_MAX_WORKERS, + SUPPORTED_HASH_ALGORITHMS, + FileObject, + generate_random_suffix, + download_file, + download_multiple_files, + unzip, + get_platform_info, + is_valid_zipfile, + bytes_to_data_url, + attempt, +) + +from .common.exception import ( + LauncherException, + LauncherHTTPException, + HashMismatchException, + UnsupportedHashAlgorithmException, + UnsupportedPlatformException, + VersionNotSelectedException, + VersionManifestFetchException, + VersionManifestSaveException, + NoVersionFoundException, + NoSpecifiedVersionKeyException, + VersionDataKeyNotFoundException, + VersionManifestException, + DependencyException, + NativeResolveException, + DownloadException, + ExtractException, + AssetManifestFetchException, + AssetManifestSaveException, + AssetManifestException, + AssetDataKeyNotFoundException, + JavaRuntimeException, + JavaRuntimeParseException, + RuntimeManifestFetchException, + RuntimeManifestDataException, + ProfileException, + ProfileSaveException, + ProfileLoadException, + ProfileKeyNotFoundException, + AccountException, + AccountSaveException, + AccountLoadException, + AccountKeyNotFoundException, + AuthenticationException, + AuthenticationConnectException, + AuthenticationSessionException, + ThirdPartyAPIException, + SettingsError, + ModelRegistrationError, + ConfigValidationError, + ArgumentError, + ArgumentValueError, +) + +from .common.python import ( + is_function_in_file, +) + +from .game.account import ( + get_account_sample, + get_accounts_sample, + Account, + create_account_data_from_object, + SUPPORT_DATA_URL_IMAGE_TYPE, + is_valid_account_avatar, + is_account_valid, + is_accounts_valid, + list_accounts, + is_account_exists, + get_account, + get_current_account_id, + get_active_account_id, + get_current_account, + get_active_account, + set_current_account_id, + set_active_account_id, + add_account, + create_account, + update_account, + remove_account, + convert_account_data_to_object, + read_account_file, + read_accounts_file, + create_or_save_account_file, + get_account_avatar, + save_account_avatar, + create_or_save_accounts_file, +) + +from .game.argument import ( + FeatureSpec, + validate_resolution, + FEATURE_SPECS, + compare_versions, + is_argument_allowed, + PLACEHOLDER_PATTERN, + replace_placeholders, + ArgumentMappings, + convert_argument_to_multiple_string, + find_game_and_jvm_args, + parse_and_generate_arguments, + append_missing_necessary_jvm_arguments, + find_match_feature_argument, + generate_enabled_feature_arguments, + generate_feature_placeholders, + generate_launch_command, + is_a_argument, + generate_argument_details, + is_same_argument, +) + +from .game.asset import ( + MOJANG_RESOURCE_ENDPOINT, + ASSET_DOWNLOAD_MAX_WORKERS, + ASSET_CHECK_MAX_WORKERS, + fetch_asset_manifest, + fetch_and_save_asset_manifest, + collect_assets_from_manifest, + download_assets_and_copy, + correct_assets_name_and_copy, + download_assets, + check_assets_exist, + read_exist_assets_indexes, + find_correct_assets_dir, +) + +from .game.authentication import ( + MICROSOFT_DEVICE_CODE_URL, + MICROSOFT_TOKEN_URL, + XBOX_AUTH_URL, + XSTS_AUTH_URL, + MINECRAFT_LOGIN_URL, + MINECRAFT_ENTITLEMENTS_URL, + MINECRAFT_PROFILE_URL, + auth_exception_handler, + get_device_code, + get_microsoft_token, + get_xbox_token_and_user_hash, + get_xsts_token, + extract_xuid, + get_xbox_xuid, + get_minecraft_access_token, + get_account_entitlements, + get_minecraft_profile, + has_minecraft_license, + refresh_microsoft_token, + is_access_token_valid, +) + +from .game.library import ( + parse_maven_coordinate, + convert_maven_version, + generate_filename_from_maven_coordinate, + generate_repo_path, + is_complete_maven_url, + generate_repo_url, + is_library_allowed, + filter_platform_libraries, + get_natives_platform_info, + is_native_allowed, + is_legacy_native_allowed, + generate_relative_path_by_maven_coordinate, + remove_duplicate_artifacts, + generate_formatted_artifact_with_name, +) + +from .game.library_core import ( + collect_library_artifacts, + locate_natives_extract_dir, + locate_natives_extract_dir_by_manifest, + collect_native_artifacts, + download_libraries, + unzip_natives, + check_libraries_exists, + check_natives_exists, + check_full_libraries_exists, + generate_classpath, + download_full_libraries, +) + +from .game.libraryx import ( + convert_maven_version_with_extra, + generate_unique_library_key, + normalize_library_to_common_struct, + LibraryPreference, + PREFER_BY_HIGHER_VERSION, + PREFER_BY_LOWER_VERSION, + PREFER_MOD_LIBRARY, + PREFER_INHERITS_LIBRARY, + LIBRARY_PREFER_OPTIONS, + compare_library_versions, + deduplicate_libraries, +) + +from .game.mod.fabric import ( + FABRIC_META_VERSION_ENDPOINT_V2, + FABRIC_META_LOADER_VERSION_ENDPOINT_V2, + FABRIC_META_LOADER_MANIFEST_ENDPOINT_V2, + FABRIC_MAVEN_URL, + get_full_version_string, + fetch_fabric_versions, + is_version_supported_and_stable, + get_version_support_loader_list, + get_loader_manifest_from_loader_data, +) + +from .game.mod.forge_like import ( + FORGE_MAVEN_URL, + FORGE_METADATA_URL, + fetch_forge_versions, +) + +from .game.mod.mod_core import ( + LOADER_LIBRARY_MARKERS, + detect_loader_name, + find_useful_part_in_mod_version_manifest, + merge_necessary_dependencies, + merge_arguments, + merge_game_and_jvm_args, + merge_manifest, +) + +from .game.mod.rules import ( + MOD_LOADER_RULES, +) + +from .game.profile import ( + get_profile_sample, + Profile, + create_profile_data_from_object, + create_profile, + create_or_save_profile_file, + read_profile_file, + is_profiles_valid, + is_profile_valid, + is_profile_exists, + list_profiles, + get_profile, + set_current_profile_id, + get_current_profile_id, + get_last_played_profile_id, + add_profile, + remove_profile, + duplicate_profile, + convert_profile_data_to_object, + update_profile, + set_last_used_time, + set_last_used_time_to_current, +) + +from .game.third_party import ( + MC_HEADS_HEAD_ENDPOINT, + get_minecraft_head_url, + get_minecraft_head, +) + +from .game.version_info import ( + MOJANG_VERSION_MANIFEST_V2, + MOJANG_VERSION_MANIFEST, + MOJANG_LIBRARIES_ENDPOINT, + NATIVE_OS_KEY_MAP, + NATIVE_OS_RULE_MAP, + NATIVE_ARCH_KEY_MAP, + NATIVE_OLD_TO_NEW_ARCH, + NATIVE_NEW_TO_OLD_ARCH, + RUNTIME_PLATFORM_MAP, + RUNTIME_ARCH_EMPTY, + RUNTIME_ARCH_MAP, + get_version_manifest, + get_latest_version, + get_all_versions, + get_available_version_types, + get_specific_version_manifest_url, + get_specific_version_manifest_url_and_hash, + fetch_specific_version_manifest, + get_specific_version_manifest, + default_java_version, + find_useful_part_in_specific_version_manifest, + get_core_file_download_url_and_hash, + validate_version_manifest, + save_version_manifest, + fetch_and_save_version_manifest, + download_core_file, + check_core_file_exists_and_verify, + LATEST_VERSION_ALIASES, +) + +from .i18n import ( + SUPPORTED_LANGUAGES, + TranslationManager, +) + +from .launcher.object import ( + Launcher, +) + +from .log.default import ( + DEFAULT_FORMAT, + DEFAULT_DATE_FORMAT, + get_colorful_handler, + LogEmitter, + LogCaptureHandler, +) + +from .qt.hack import ( + move_window_to_center, + is_main_thread, + recolor_standard_icon, + recolor_pixmap, + recolor_icon, + is_light_theme, + add_icon_padding, + data_url_to_qt_image, +) + +from .qt.item_button import ( + ItemButton, +) + +from .qt.messagebox import ( + create_messagebox, + error, + info, + warning, + error_with_plain_text, + ask_yes_no_with_plain_text, +) + +from .qt.progress_dialog import ( + ProgressRow, + ProgressDialog, +) + +from .runtime.java import ( + get_java_version, + find_java_installations, +) + +from .runtime.mojang import ( + MOJANG_RUNTIME_MANIFEST, + RUNTIME_CHECK_MAX_WORKERS, + RUNTIME_DOWNLOAD_MAX_WORKERS, + get_current_platform_runtime_key, + fetch_runtime_manifest, + find_support_runtime_manifests_info, + get_support_runtime_manifest, + RuntimeCheckResult, + collect_runtime_files, + post_process_runtime_dir, + download_java_runtimes, +) + +__all__ = [ + # common.common + "DEFAULT_HASH_CHUNK_SIZE", + "DEFAULT_DOWNLOAD_CHUNK_SIZE", + "THREADED_DOWNLOAD_MAX_WORKERS", + "SUPPORTED_HASH_ALGORITHMS", + "FileObject", + "generate_random_suffix", + "download_file", + "download_multiple_files", + "unzip", + "get_platform_info", + "is_valid_zipfile", + "bytes_to_data_url", + "attempt", + # common.exception + "LauncherException", + "LauncherHTTPException", + "HashMismatchException", + "UnsupportedHashAlgorithmException", + "UnsupportedPlatformException", + "VersionNotSelectedException", + "VersionManifestFetchException", + "VersionManifestSaveException", + "NoVersionFoundException", + "NoSpecifiedVersionKeyException", + "VersionDataKeyNotFoundException", + "VersionManifestException", + "DependencyException", + "NativeResolveException", + "DownloadException", + "ExtractException", + "AssetManifestFetchException", + "AssetManifestSaveException", + "AssetManifestException", + "AssetDataKeyNotFoundException", + "JavaRuntimeException", + "JavaRuntimeParseException", + "RuntimeManifestFetchException", + "RuntimeManifestDataException", + "ProfileException", + "ProfileSaveException", + "ProfileLoadException", + "ProfileKeyNotFoundException", + "AccountException", + "AccountSaveException", + "AccountLoadException", + "AccountKeyNotFoundException", + "AuthenticationException", + "AuthenticationConnectException", + "AuthenticationSessionException", + "ThirdPartyAPIException", + "SettingsError", + "ModelRegistrationError", + "ConfigValidationError", + "ArgumentError", + "ArgumentValueError", + # common.python + "is_function_in_file", + # game.account + "get_account_sample", + "get_accounts_sample", + "Account", + "create_account_data_from_object", + "SUPPORT_DATA_URL_IMAGE_TYPE", + "is_valid_account_avatar", + "is_account_valid", + "is_accounts_valid", + "list_accounts", + "is_account_exists", + "get_account", + "get_current_account_id", + "get_active_account_id", + "get_current_account", + "get_active_account", + "set_current_account_id", + "set_active_account_id", + "add_account", + "create_account", + "update_account", + "remove_account", + "convert_account_data_to_object", + "read_account_file", + "read_accounts_file", + "create_or_save_account_file", + "get_account_avatar", + "save_account_avatar", + "create_or_save_accounts_file", + # game.argument + "FeatureSpec", + "validate_resolution", + "FEATURE_SPECS", + "compare_versions", + "is_argument_allowed", + "PLACEHOLDER_PATTERN", + "replace_placeholders", + "ArgumentMappings", + "convert_argument_to_multiple_string", + "find_game_and_jvm_args", + "parse_and_generate_arguments", + "append_missing_necessary_jvm_arguments", + "find_match_feature_argument", + "generate_enabled_feature_arguments", + "generate_feature_placeholders", + "generate_launch_command", + "is_a_argument", + "generate_argument_details", + "is_same_argument", + # game.asset + "MOJANG_RESOURCE_ENDPOINT", + "ASSET_DOWNLOAD_MAX_WORKERS", + "ASSET_CHECK_MAX_WORKERS", + "fetch_asset_manifest", + "fetch_and_save_asset_manifest", + "collect_assets_from_manifest", + "download_assets_and_copy", + "correct_assets_name_and_copy", + "download_assets", + "check_assets_exist", + "read_exist_assets_indexes", + "find_correct_assets_dir", + # game.authentication + "MICROSOFT_DEVICE_CODE_URL", + "MICROSOFT_TOKEN_URL", + "XBOX_AUTH_URL", + "XSTS_AUTH_URL", + "MINECRAFT_LOGIN_URL", + "MINECRAFT_ENTITLEMENTS_URL", + "MINECRAFT_PROFILE_URL", + "auth_exception_handler", + "get_device_code", + "get_microsoft_token", + "get_xbox_token_and_user_hash", + "get_xsts_token", + "extract_xuid", + "get_xbox_xuid", + "get_minecraft_access_token", + "get_account_entitlements", + "get_minecraft_profile", + "has_minecraft_license", + "refresh_microsoft_token", + "is_access_token_valid", + # game.library + "parse_maven_coordinate", + "convert_maven_version", + "generate_filename_from_maven_coordinate", + "generate_repo_path", + "is_complete_maven_url", + "generate_repo_url", + "is_library_allowed", + "filter_platform_libraries", + "get_natives_platform_info", + "is_native_allowed", + "is_legacy_native_allowed", + "generate_relative_path_by_maven_coordinate", + "remove_duplicate_artifacts", + "generate_formatted_artifact_with_name", + # game.library_core + "collect_library_artifacts", + "locate_natives_extract_dir", + "locate_natives_extract_dir_by_manifest", + "collect_native_artifacts", + "download_libraries", + "unzip_natives", + "check_libraries_exists", + "check_natives_exists", + "check_full_libraries_exists", + "generate_classpath", + "download_full_libraries", + # game.libraryx + "convert_maven_version_with_extra", + "generate_unique_library_key", + "normalize_library_to_common_struct", + "LibraryPreference", + "PREFER_BY_HIGHER_VERSION", + "PREFER_BY_LOWER_VERSION", + "PREFER_MOD_LIBRARY", + "PREFER_INHERITS_LIBRARY", + "LIBRARY_PREFER_OPTIONS", + "compare_library_versions", + "deduplicate_libraries", + # game.mod.fabric + "FABRIC_META_VERSION_ENDPOINT_V2", + "FABRIC_META_LOADER_VERSION_ENDPOINT_V2", + "FABRIC_META_LOADER_MANIFEST_ENDPOINT_V2", + "FABRIC_MAVEN_URL", + "get_full_version_string", + "fetch_fabric_versions", + "is_version_supported_and_stable", + "get_version_support_loader_list", + "get_loader_manifest_from_loader_data", + # game.mod.forge + "FORGE_MAVEN_URL", + "FORGE_METADATA_URL", + "fetch_forge_versions", + # game.mod.mod_core + "LOADER_LIBRARY_MARKERS", + "detect_loader_name", + "find_useful_part_in_mod_version_manifest", + "merge_necessary_dependencies", + "merge_arguments", + "merge_game_and_jvm_args", + "merge_manifest", + # game.mod.rules + "MOD_LOADER_RULES", + # game.profile + "get_profile_sample", + "Profile", + "create_profile_data_from_object", + "create_profile", + "create_or_save_profile_file", + "read_profile_file", + "is_profiles_valid", + "is_profile_valid", + "is_profile_exists", + "list_profiles", + "get_profile", + "set_current_profile_id", + "get_current_profile_id", + "get_last_played_profile_id", + "add_profile", + "remove_profile", + "duplicate_profile", + "convert_profile_data_to_object", + "update_profile", + "set_last_used_time", + "set_last_used_time_to_current", + # game.third_party + "MC_HEADS_HEAD_ENDPOINT", + "get_minecraft_head_url", + "get_minecraft_head", + # game.version_info + "MOJANG_VERSION_MANIFEST_V2", + "MOJANG_VERSION_MANIFEST", + "MOJANG_LIBRARIES_ENDPOINT", + "NATIVE_OS_KEY_MAP", + "NATIVE_OS_RULE_MAP", + "NATIVE_ARCH_KEY_MAP", + "NATIVE_OLD_TO_NEW_ARCH", + "NATIVE_NEW_TO_OLD_ARCH", + "RUNTIME_PLATFORM_MAP", + "RUNTIME_ARCH_EMPTY", + "RUNTIME_ARCH_MAP", + "get_version_manifest", + "get_latest_version", + "get_all_versions", + "get_available_version_types", + "get_specific_version_manifest_url", + "get_specific_version_manifest_url_and_hash", + "fetch_specific_version_manifest", + "get_specific_version_manifest", + "default_java_version", + "find_useful_part_in_specific_version_manifest", + "get_core_file_download_url_and_hash", + "validate_version_manifest", + "save_version_manifest", + "fetch_and_save_version_manifest", + "download_core_file", + "check_core_file_exists_and_verify", + "LATEST_VERSION_ALIASES", + # i18n + "SUPPORTED_LANGUAGES", + "TranslationManager", + # launcher.object + "Launcher", + # log.default + "DEFAULT_FORMAT", + "DEFAULT_DATE_FORMAT", + "get_colorful_handler", + "LogEmitter", + "LogCaptureHandler", + # qt.hack + "move_window_to_center", + "is_main_thread", + "recolor_standard_icon", + "recolor_pixmap", + "recolor_icon", + "is_light_theme", + "add_icon_padding", + "data_url_to_qt_image", + # qt.item_button + "ItemButton", + # qt.messagebox + "create_messagebox", + "error", + "info", + "warning", + "error_with_plain_text", + "ask_yes_no_with_plain_text", + # qt.progress_dialog + "ProgressRow", + "ProgressDialog", + # runtime.java + "get_java_version", + "find_java_installations", + # runtime.mojang + "MOJANG_RUNTIME_MANIFEST", + "RUNTIME_CHECK_MAX_WORKERS", + "RUNTIME_DOWNLOAD_MAX_WORKERS", + "get_current_platform_runtime_key", + "fetch_runtime_manifest", + "find_support_runtime_manifests_info", + "get_support_runtime_manifest", + "RuntimeCheckResult", + "collect_runtime_files", + "post_process_runtime_dir", + "download_java_runtimes", +] diff --git a/core_lib/common/exception.py b/core_lib/common/exception.py index 9997ba6..14a8d71 100644 --- a/core_lib/common/exception.py +++ b/core_lib/common/exception.py @@ -147,4 +147,15 @@ class ArgumentError(LauncherException): user_message = "An error occurred while parsing arguments." class ArgumentValueError(ArgumentError): - user_message = "An invalid argument value was provided." \ No newline at end of file + user_message = "An invalid argument value was provided." + +class LoaderUnsupportedSpecificVersion(LauncherException): + user_message = "Loader does not support specific version." + + def __init__(self, loader_name: str, target_version: str): + self.loader_name = loader_name + self.target_version = target_version + super().__init__(f"{loader_name} does not support Minecraft {target_version}.") + +class LoaderInstallError(LauncherException): + user_message = "An error occurred while installing loader." \ No newline at end of file diff --git a/core_lib/game/argument.py b/core_lib/game/argument.py index 7155aaa..60ecca5 100644 --- a/core_lib/game/argument.py +++ b/core_lib/game/argument.py @@ -173,7 +173,7 @@ class ArgumentMappings: user_type=None, user_properties=None, version_type=None, natives_directory=None, launcher_name=None, launcher_version=None, classpath=None, classpath_separator=None, library_directory=None, - resolution: tuple[int, int] | None = None): + resolution: tuple[int, int] | None = None, client_jar_name: str | None = None): self.player_name = player_name self.version_name = version_name self.game_directory = game_directory @@ -201,6 +201,7 @@ class ArgumentMappings: self.launcher_name = launcher_name self.launcher_version = launcher_version self.classpath = classpath + self.client_jar_name = client_jar_name self.classpath_separator = classpath_separator self.library_directory = library_directory @@ -443,6 +444,18 @@ def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_pa arg_maps, ) + # BootstrapLauncher must ignore the original client when the loader supplies + # its patched Minecraft module. The client filename can differ from the + # profile's version_name because manifests inherit the vanilla client JAR. + if arg_maps.client_jar_name: + prefix = "-DignoreList=" + for index, argument in enumerate(parsed_jvm_args): + if argument.startswith(prefix): + ignored = [item for item in argument[len(prefix):].split(",") if item] + if not any(arg_maps.client_jar_name.startswith(item) for item in ignored): + ignored.append(arg_maps.client_jar_name) + parsed_jvm_args[index] = prefix + ",".join(ignored) + cmd.extend(parsed_jvm_args) cmd.append(main_class) cmd.extend(parsed_game_args) diff --git a/core_lib/game/library_core.py b/core_lib/game/library_core.py index 0c85ca9..45b44ff 100644 --- a/core_lib/game/library_core.py +++ b/core_lib/game/library_core.py @@ -15,6 +15,17 @@ from ..common.exception import UnsupportedPlatformException, NativeResolveExcept logger = logging.getLogger("Launcher.CoreLib") +def _is_native_only_library(library: dict) -> bool: + name = library.get("name", "") + if re.search(r":natives-[^:@]+(?:@[^:]+)?$", name): + return True + downloads = library.get("downloads") or {} + has_natives = library.get("natives") or any( + key.startswith("natives-") for key in (downloads.get("classifiers") or {}) + ) + return bool(has_natives and not downloads.get("artifact")) + + def collect_library_artifacts(specific_version_manifest): _, _, _, _, libraries, _, _ = find_useful_part_in_specific_version_manifest(specific_version_manifest) @@ -32,12 +43,8 @@ def collect_library_artifacts(specific_version_manifest): name = library.get("name", "") artifact_raw = library.get("downloads", {}).get("artifact", {}) rules = library.get("rules", []) - classifiers = library.get("downloads", {}).get("classifiers", {}) - natives = library.get("natives", {}) - - # Ignore natives - if (len(natives) > 0 or bool(re.search(r":natives-[^:]+$", name)) or - any(native.startswith("natives-") for native in classifiers)): + # Mixed entries also contain a Java JAR needed on the classpath. + if _is_native_only_library(library): logger.info(f"Skipping {name} because its a native library.") continue @@ -350,12 +357,8 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path): name = library.get("name", "") artifact_raw = library.get("downloads", {}).get("artifact", {}) rules = library.get("rules", []) - classifiers = library.get("downloads", {}).get("classifiers", {}) - natives = library.get("natives", {}) - - # Ignore natives - if (len(natives) > 0 or bool(re.search(r":natives-[^:]+$", name)) or - any(native.startswith("natives-") for native in classifiers)): + # Mixed entries also contain a Java JAR needed on the classpath. + if _is_native_only_library(library): logger.info(f"Skipping {name} because its a native library.") continue @@ -561,12 +564,8 @@ def generate_classpath(manifest: dict, libraries_dir: Path, core_file_path: Path name = library.get("name", "") artifact_raw = library.get("downloads", {}).get("artifact", {}) rules = library.get("rules", []) - classifiers = library.get("downloads", {}).get("classifiers", {}) - natives = library.get("natives", {}) - - # Ignore natives - if (len(natives) > 0 or bool(re.search(r":natives-[^:]+$", name)) or - any(native.startswith("natives-") for native in classifiers)): + # Mixed entries also contain a Java JAR needed on the classpath. + if _is_native_only_library(library): logger.info(f"Skipping {name} because its a native library.") continue diff --git a/core_lib/game/libraryx.py b/core_lib/game/libraryx.py index 54dabbd..8914bb7 100644 --- a/core_lib/game/libraryx.py +++ b/core_lib/game/libraryx.py @@ -49,7 +49,8 @@ def generate_unique_library_key(group: str, artifact: str, classifier: str | Non def normalize_library_to_common_struct(library: dict, default_maven_url: str | None = MOJANG_LIBRARIES_ENDPOINT, - default_extension: str = "jar") -> dict: + default_extension: str = "jar", + ignore_missing_url=False) -> dict: result = deepcopy(library) name: str | None = library.get("name") @@ -70,6 +71,13 @@ def normalize_library_to_common_struct(library: dict, default_maven_url: str | N artifact_raw = dict(downloads.get("artifact") or {}) + # Legacy native-only entries have classifiers, not a Java artifact. + # Do not invent a base JAR that may not exist in the repository. + if not artifact_raw and (result.get("natives") or any( + key.startswith("natives-") for key in (downloads.get("classifiers") or {}))): + result["downloads"] = downloads + return result + # Generate new relative path and put back if not artifact_raw.get("path"): filename = generate_filename_from_maven_coordinate( @@ -85,7 +93,7 @@ def normalize_library_to_common_struct(library: dict, default_maven_url: str | N filename, ) - if not artifact_raw.get("url"): + if not artifact_raw.get("url") and not ignore_missing_url: top_level_url: str | None = result.get("url") if top_level_url: @@ -231,4 +239,4 @@ def deduplicate_libraries(libraries: list[dict], preference: LibraryPreference, indexed[key] = library - return list(indexed.values()) \ No newline at end of file + return list(indexed.values()) diff --git a/core_lib/game/mod/fabric.py b/core_lib/game/mod/fabric.py index cbf1a17..7742e49 100644 --- a/core_lib/game/mod/fabric.py +++ b/core_lib/game/mod/fabric.py @@ -4,7 +4,7 @@ import logging import requests from core_lib.common.exception import VersionManifestFetchException, VersionDataKeyNotFoundException, \ - VersionManifestException + VersionManifestException, LoaderUnsupportedSpecificVersion logger = logging.getLogger("Launcher.CoreLib") @@ -16,7 +16,7 @@ FABRIC_MAVEN_URL = "https://maven.fabricmc.net/" def get_full_version_string(version: str, loader_version: str) -> str: return f"fabric-loader-{loader_version}-{version}" -def fetch_fabric_version_list(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: r = requests.get(version_manifest_url, timeout=timeout) except requests.exceptions.Timeout: @@ -80,10 +80,7 @@ def get_version_support_loader_list(target_version: str, loader_version_url: str ) except requests.exceptions.HTTPError as e: if e.response.status_code == 404 or e.response.status_code == 400: - raise VersionManifestFetchException( - "HTTP error while fetch from {}: {}".format(loader_version_url, e), - user_message="Target version {} no fabric version found".format(target_version) - ) + raise LoaderUnsupportedSpecificVersion("fabric", target_version) from e else: raise VersionManifestFetchException( "HTTP error while fetch from {}: HTTP Status: {}".format(loader_version_url, e.response.status_code) @@ -111,10 +108,7 @@ def get_version_support_loader_list(target_version: str, loader_version_url: str loaders.append(loader) if not loaders: - raise VersionManifestException( - "No available loader found in {}".format(loader_version_url), - user_message="Target version {} no fabric version found".format(target_version) - ) + raise LoaderUnsupportedSpecificVersion("fabric", target_version) return loaders diff --git a/core_lib/game/mod/forge_like.py b/core_lib/game/mod/forge_like.py new file mode 100644 index 0000000..7a66e6e --- /dev/null +++ b/core_lib/game/mod/forge_like.py @@ -0,0 +1,1254 @@ +import json +import hashlib +import logging +import os +import re +import shutil +import stat +import subprocess +import sys +import xml.etree.ElementTree as ET +import zipfile +from dataclasses import dataclass +from pathlib import Path, PureWindowsPath +from tempfile import NamedTemporaryFile, mkdtemp +from typing import Literal, Callable +from urllib.parse import urlsplit +from collections.abc import Mapping +import requests + +from core_lib.common.common import FileObject, download_file +from core_lib.common.exception import VersionManifestFetchException, NoSpecifiedVersionKeyException, \ + LoaderUnsupportedSpecificVersion, LoaderInstallError +from core_lib.game.library import ( + generate_repo_url, parse_maven_coordinate, + generate_filename_from_maven_coordinate, generate_repo_path, + filter_platform_libraries, +) +from core_lib.game.mod.rules import FORGE_LIKE_LOADERS, MOD_LOADER_RULES + +FORGE_MAVEN_URL = "https://maven.minecraftforge.net/" +FORGE_METADATA_URL = FORGE_MAVEN_URL + "net/minecraftforge/forge/maven-metadata.xml" +NEOFORGE_MAVEN_URL = "https://maven.neoforged.net/" +NEOFORGE_MAVEN_RELEASE_URL = NEOFORGE_MAVEN_URL + "releases/" +NEOFORGE_METADATA_URL = NEOFORGE_MAVEN_URL + "releases/net/neoforged/neoforge/maven-metadata.xml" +FORGE_INSTALLER_URL = FORGE_MAVEN_URL + "net/minecraftforge/forge/{version}/forge-{version}-installer.jar" +NEOFORGE_INSTALLER_URL = NEOFORGE_MAVEN_URL + "releases/net/neoforged/neoforge/{version}/neoforge-{version}-installer.jar" + +logger = logging.getLogger("Launcher.CoreLib") + + +def fetch_forge_versions(forge_metadata_url: str = FORGE_METADATA_URL, timeout: int = 5) -> list[str]: + """ + Fetch Forge maven metadata and return a list of version IDs. + :param forge_metadata_url: URL to fetch Forge maven metadata from + :param timeout: + :return: + found: list[str] + """ + try: + r = requests.get(forge_metadata_url, timeout=timeout) + r.raise_for_status() + except requests.exceptions.Timeout as e: + raise VersionManifestFetchException( + "Timeout while fetch from {}".format(forge_metadata_url) + ) from e + except requests.exceptions.ConnectionError as e: + raise VersionManifestFetchException( + "Connection error while fetch from {}: {}".format(forge_metadata_url, e) + ) from e + except requests.exceptions.HTTPError as e: + status_code = e.response.status_code if e.response is not None else "unknown" + raise VersionManifestFetchException( + "HTTP error while fetch from {}: HTTP Status: {}".format(forge_metadata_url, status_code) + ) from e + except requests.exceptions.RequestException as e: + raise VersionManifestFetchException( + "Request error while fetch from {}: {}".format(forge_metadata_url, e) + ) from e + + try: + root = ET.fromstring(r.content) + except ET.ParseError as e: + raise VersionManifestFetchException( + "XML decode error while fetch from {}: {}".format(forge_metadata_url, e) + ) from e + + versioning = root.find("versioning") + + if versioning is None: + raise NoSpecifiedVersionKeyException( + "Key \"Versioning\" not found in forge metadata" + ) + + versions = versioning.find("versions") + if versions is None: + raise NoSpecifiedVersionKeyException( + "Key \"Versions\" not found or is empty in forge metadata" + ) + + found = [] + for version in versions.findall("version"): + ver_id = (version.text or "").strip() + + if not ver_id: + raise NoSpecifiedVersionKeyException( + "Found empty version ID in forge metadata" + ) + + found.append(ver_id) + + if not found: + raise NoSpecifiedVersionKeyException( + "No version entries found in forge metadata" + ) + + return found + + +def split_forge_like_version(version: str, loader_name: Literal["forge", "neoforge"] = "forge") -> tuple[str, str]: + """ + Split forge and minecraft version from the loader version + :param version: + :param loader_name: + :return: + """ + version = version.strip() + + if loader_name not in FORGE_LIKE_LOADERS: + raise ValueError(f"Unsupported loader: {loader_name!r}") + + # For forge and old neoforge version + if loader_name == "forge" or version.startswith("1."): + minecraft_version, separator, loader_version = version.partition("-") + + if not separator or not loader_version: + raise ValueError(f"Invalid loader version: {version!r}") + + return minecraft_version, loader_version + elif loader_name == "neoforge" and version.startswith("0."): + # For special NeoForge version such as 0.25w14craftmine.3-beta + match = re.fullmatch( + r"0\.(?P[^.\s]+)\.(?P\d+)" + r"(?:-[0-9A-Za-z.-]+)?", + version, + ) + if match is None: + raise ValueError(f"Unsupported special NeoForge version: {version!r}") + + return match["minecraft"], version + + if loader_name == "forge": + raise ValueError(f"Invalid Forge version: {version!r}") + + match = re.fullmatch( + r"(?P\d+)\.(?P\d+)\.(?P\d+)" + r"(?:\.(?P\d+))?" + r"(?:-[0-9A-Za-z.-]+)?" + r"(?:\+(?P(?:snapshot|pre|rc)-\d+))?", + version, + ) + if match is None: + raise ValueError(f"Unsupported NeoForge version: {version!r}") + + major = int(match["major"]) + minor = int(match["minor"]) + patch = int(match["patch"]) + + if match["build"] is None: + if major >= 26: + raise ValueError("Calendar-based NeoForge requires four components") + + # Convert such as 21.1.x to 1.21.1 (x is loader patch version) + minecraft_version = f"1.{major}" + if minor: + minecraft_version += f".{minor}" + else: + minecraft_version = f"{major}.{minor}" + if patch: + minecraft_version += f".{patch}" + + if match["preview"]: + minecraft_version += f"-{match['preview']}" + + return minecraft_version, version + + +def get_version_support_loader_list(target_version: str, + forge_metadata_url: str = FORGE_METADATA_URL, + loader_name: Literal["forge", "neoforge"] = "forge", + version_splitter: Callable[[str], tuple[str, str]] = split_forge_like_version, + timeout: int = 5) \ + -> list[dict]: + versions = fetch_forge_versions(forge_metadata_url, timeout) + loaders = [] + + for version in versions: + ver_id, _ = version_splitter(version, loader_name=loader_name) + + if ver_id == target_version: + loaders.append(version) + + if not loaders: + raise LoaderUnsupportedSpecificVersion(loader_name, target_version) + + return loaders + + +def get_installer_coordinate(loader_version: str, + group: str = "net.minecraftforge", + name: str = "forge") -> str: + """ + Convert forge (maven) version to installer coordinate + For example: net.minecraftforge:forge:1.20.1-47.2.0:installer. + :param loader_version: + :param group: Group ID of the loader (usually is "net.minecraftforge", for neoforge is "net.neoforged") + :param name: + :return: + """ + version = loader_version.strip() + + if not version: + raise ValueError("Forge loader version must not be empty") + + if any(char.isspace() or char in ":@/\\" + for char in version): + raise ValueError(f"Invalid Forge loader version: {loader_version!r}") + + return f"{group}:{name}:{version}:installer" + + +def get_installer_url(loader_version: str, maven_url: str = FORGE_MAVEN_URL, *, + group: str = "net.minecraftforge", name: str = "forge") -> str: + """ + Generate installer URL for the loader version + :param loader_version: + :param maven_url: Maven URL of the loader + :param group: + :param name: + :return: + """ + coordinate = get_installer_coordinate(loader_version, group=group, name=name) + group_id, artifact, version, classifier, extension = parse_maven_coordinate(coordinate) + return generate_repo_url( + maven_url, group_id, artifact, version, + classifier=classifier, extension=extension, + ) + + +@dataclass +class LoaderInstallPlan: + loader_name: Literal["forge", "neoforge"] + loader_version: str + minecraft_version: str + version_manifest: dict + installer_path: Path + extracted_dir: Path + install_profile: dict | None = None + + @property + def version_id(self) -> str: + return self.version_manifest["id"] + + +def _read_json_object(path: Path) -> dict: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise ValueError(f"Unable to read installer JSON: {path}") from exc + + if not isinstance(data, dict): + raise ValueError(f"Installer JSON must contain an object: {path}") + return data + + +def parse_installer_metadata(extracted_dir: Path, *, + installer_path: Path, + loader_version: str, + loader_name: Literal["forge", "neoforge"] = "forge", + support_loader_list: list[str] | None = None) -> LoaderInstallPlan: + """Read version JSON or legacy versionInfo, with an optional install profile. + + The caller supplies the loader identity; profile is a display name. + Installers without usable launch metadata are explicitly unsupported. + """ + supported = FORGE_LIKE_LOADERS if support_loader_list is None else support_loader_list + if loader_name not in supported or loader_name not in ("forge", "neoforge"): + raise ValueError(f"Unsupported loader name: {loader_name!r}") + + # Validate the full Maven version. (If not supported, this will raise.) + get_installer_coordinate(loader_version) + + extracted_dir = Path(extracted_dir).resolve() + install_profile_path = extracted_dir / "install_profile.json" + + if install_profile_path.is_file(): + install_profile = _read_json_object(install_profile_path) + else: + install_profile = None + + profile = install_profile if install_profile is not None else {} + + manifest_entry = profile.get("json", "/version.json") + if not isinstance(manifest_entry, str) or not manifest_entry.strip(): + raise ValueError("Installer version JSON path must be a non-empty string") + + # Leading slashes denote installer resources, not filesystem roots. + manifest_path = (extracted_dir / manifest_entry.replace("\\", "/").lstrip("/")).resolve() + if not manifest_path.is_relative_to(extracted_dir): + raise ValueError("Installer version JSON path escapes the extracted directory") + + if manifest_path.is_file(): + version_manifest = _read_json_object(manifest_path) + elif isinstance(profile.get("versionInfo"), dict): + version_manifest = dict(profile["versionInfo"]) + else: + raise ValueError("Unsupported installer: no version JSON or versionInfo found") + + # Check necessary key exists + for key in ("id", "mainClass"): + if not isinstance(version_manifest.get(key), str) or not version_manifest[key].strip(): + raise ValueError(f"Installer version manifest is missing {key!r}") + + minecraft_version = version_manifest.get("inheritsFrom") or profile.get("minecraft") + + if not isinstance(minecraft_version, str) or not minecraft_version.strip(): + raise ValueError("Installer does not declare its Minecraft version") + if profile.get("minecraft") and profile["minecraft"] != minecraft_version: + raise ValueError("Installer and version manifest declare different Minecraft versions") + + version_manifest["inheritsFrom"] = minecraft_version + return LoaderInstallPlan( + loader_name=loader_name, + loader_version=loader_version.strip(), + minecraft_version=minecraft_version, + version_manifest=version_manifest, + installer_path=Path(installer_path).resolve(), + extracted_dir=extracted_dir, + install_profile=install_profile, + ) + + +def add_missing_url_flag_to_generated_after_install_libraries(install_plan: LoaderInstallPlan) -> None: + """ + Mark URL-less libraries in both installer manifests in place. + + Such artifacts must be supplied by the installer or its processors rather + than downloaded from an inferred Maven URL. This flag does not verify that + the artifact has actually been installed. + :param install_plan: + """ + manifests = (install_plan.version_manifest, install_plan.install_profile) + for manifest in manifests: + if manifest is None: + continue + + for library in manifest.get("libraries") or []: + downloads = library.get("downloads") or {} + artifact = downloads.get("artifact") or {} + if not library.get("url") and not artifact.get("url"): + library["ignoreMissingURL"] = True + + +def _extract_installer(installer_path: Path, extracted_dir: Path) -> None: + """ + Validate archive paths before extracting; reading each file checks its CRC. + :param installer_path: + :param extracted_dir: + :return: + """ + with zipfile.ZipFile(installer_path) as archive: + entries = [] + + for member in archive.infolist(): + name = member.filename.replace("\\", "/") + parts = name.rstrip("/").split("/") + destination = (extracted_dir / name).resolve() + if ( + name.startswith("/") + or PureWindowsPath(name).drive + or any(part in ("", ".", "..") or ":" in part for part in parts) + or not destination.is_relative_to(extracted_dir) + or stat.S_ISLNK(member.external_attr >> 16) + ): + raise ValueError(f"Unsafe installer archive entry: {member.filename!r}") + + entries.append((member, destination)) + + for member, destination in entries: + if member.is_dir(): + destination.mkdir(parents=True, exist_ok=True) + else: + destination.parent.mkdir(parents=True, exist_ok=True) + with archive.open(member) as source, destination.open("wb") as output: + shutil.copyfileobj(source, output) + + +def _get_neoforge_artifact(loader_version: str): + return "forge" if loader_version.startswith("1.") else "neoforge" + + +def prepare_installer(loader_name: Literal["forge", "neoforge"], + loader_version: str, working_dir: Path, + *, maven_url: str | None = None, + minecraft_version: str, + expected_sha1: str | None = None, + progress_callback: Callable[[str, float], None] | None = None) -> LoaderInstallPlan: + """ + Prepare the forge-like installer + :param loader_name: Loader name. + :param loader_version: Loader version. + :param working_dir: Working directory. + :param maven_url: Maven URL override; defaults to the loader's repository. + :param minecraft_version: Minecraft version. + :param expected_sha1: Expected SHA1 hash of the installer. (Optional because most loaders don't provide it) + :param progress_callback: Progress callback. + :return: Loader install plan. + """ + temp_dir: Path | None = None + stage = "validate installer request" + + try: + if loader_name not in FORGE_LIKE_LOADERS: + raise ValueError(f"Unsupported loader: {loader_name!r}") + + # Validate version + loader_version = loader_version.strip() + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+\-]*", loader_version): + raise ValueError(f"Invalid loader Maven version: {loader_version!r}") + + if not isinstance(minecraft_version, str) or not minecraft_version.strip(): + raise ValueError("Minecraft version must not be empty") + + # maven and install url + if loader_name == "forge": + repository = FORGE_MAVEN_URL + group, artifact = "net.minecraftforge", "forge" + else: + repository = NEOFORGE_MAVEN_RELEASE_URL + group = "net.neoforged" + artifact = _get_neoforge_artifact(loader_version) + + url = get_installer_url( + loader_version, maven_url=repository if maven_url is None else maven_url, + group=group, name=artifact, + ) + + # Prepare working directory and installer download path + stage = "create installer workspace" + working_dir = Path(working_dir).resolve() + working_dir.mkdir(parents=True, exist_ok=True) + temp_dir = Path(mkdtemp(prefix=f"{loader_name}-{loader_version}-", dir=working_dir)).resolve() + + installer_path = temp_dir / "installer.jar" + extracted_dir = temp_dir / "extracted" + extracted_dir.mkdir() + + # Download and extract installer + stage = "download installer" + file = FileObject(path=installer_path, url=url, sha1=expected_sha1) + download_file(file, progress_callback=progress_callback, overwrite=True) + + stage = "extract installer" + _extract_installer(installer_path, extracted_dir) + + # Parse installer metadata and create plan + stage = "parse installer metadata" + plan = parse_installer_metadata( + extracted_dir, installer_path=installer_path, + loader_version=loader_version, loader_name=loader_name, + ) + + # Check version + if plan.minecraft_version != minecraft_version: + raise ValueError( + f"Expected Minecraft version {minecraft_version}, but got {plan.minecraft_version} " + f"in {installer_path}." + ) + + # Add flag to libraries that will be generated by forge processor + add_missing_url_flag_to_generated_after_install_libraries(plan) + return plan + except Exception as e: + if temp_dir is not None and temp_dir.is_relative_to(working_dir) and temp_dir != working_dir: + try: + shutil.rmtree(temp_dir.as_posix()) + except OSError: + logger.warning("Unable to clean installer workspace %s", temp_dir, exc_info=True) + + raise LoaderInstallError(f"Failed to {stage} for {loader_name}: {e}") from e + + +def _is_artifact_link(path: Path) -> bool: + return path.is_symlink() or getattr(path, "is_junction", lambda: False)() + + +def _checked_artifact_path(root: Path, relative: str) -> Path: + """Resolve a relative artifact path without following links or junctions.""" + relative = relative.replace("\\", "/") + parts = relative.split("/") + + if ( + relative.startswith("/") or PureWindowsPath(relative).drive + or any(part in ("", ".", "..") or part.rstrip(". ") != part + or any(char in part for char in ':<>"|?*\0') for part in parts) + ): + raise ValueError(f"Invalid artifact path: {relative!r}") + + path = root + for part in parts: + path = path / part + if _is_artifact_link(path): + raise ValueError(f"Artifact path contains a link: {path}") + + if not path.resolve().is_relative_to(root): + raise ValueError(f"Artifact path escapes its root: {path}") + + return path + + +def _artifact_sha256(path: Path) -> str: + digest = hashlib.sha256() + + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + + return digest.hexdigest() + + +def copy_embedded_artifacts(install_plan: LoaderInstallPlan, + output_libraries_dir: Path) -> list[Path]: + """ + Copy maven and libraries trees/files from extracted dir to output dir. + + Conflicting embedded sources are rejected before copying. Existing identical + files are skipped; differing files are replaced atomically. Returns only the + destinations actually copied. Patch data stays in the extracted directory. + """ + source = Path(install_plan.extracted_dir) + destination = Path(output_libraries_dir) + + try: + if _is_artifact_link(source) or _is_artifact_link(destination): + raise ValueError("Artifact roots must not be links") + + root = source.resolve() + output_root = destination.resolve() + + if not root.is_dir(): + raise ValueError(f"Installer extraction directory does not exist: {root}") + + if output_root.is_relative_to(root) or root.is_relative_to(output_root): + raise ValueError("Artifact source and destination roots must not overlap") + + # Build and validate the entire copy plan before changing any artifacts. + artifacts: dict[Path, tuple[Path, str]] = {} + + def add_artifact(relative_source: str, relative_destination: str) -> None: + nonlocal source, destination + + source = _checked_artifact_path(root, relative_source) + destination = _checked_artifact_path(output_root, relative_destination) + + if not source.is_file(): + raise ValueError(f"Declared embedded artifact is missing or not a file: {source}") + + digest = _artifact_sha256(source) + previous = artifacts.get(destination) + + if previous is not None and previous[1] != digest: + raise ValueError(f"Conflicting embedded artifacts: {previous[0]} and {source}") + + artifacts.setdefault(destination, (source, digest)) + + def collect_tree(directory: Path, tree_root: Path) -> None: + for item in sorted(directory.iterdir()): + _checked_artifact_path(root, item.relative_to(root).as_posix()) + if item.is_dir(): + collect_tree(item, tree_root) + else: + add_artifact( + item.relative_to(root).as_posix(), item.relative_to(tree_root).as_posix(), + ) + + for directory_name in ("maven", "libraries"): + tree_root = _checked_artifact_path(root, directory_name) + + if tree_root.exists(): + if not tree_root.is_dir(): + raise ValueError(f"Embedded Maven root is not a directory: {tree_root}") + + collect_tree(tree_root, tree_root) + + profile = install_plan.install_profile or {} + if "install" in profile: + legacy = profile["install"] + + if not isinstance(legacy, dict): + raise ValueError("Legacy install metadata must be an object") + + file_path, coordinate = legacy.get("filePath"), legacy.get("path") + if not isinstance(file_path, str) or not isinstance(coordinate, str): + raise ValueError("Legacy install metadata requires filePath and path") + + group, artifact, version, classifier, extension = parse_maven_coordinate(coordinate) + + # The shared Maven parser checks structure; also validate its path components. + for component in (group, artifact, version, classifier, extension): + if component is not None: + if not component or any(char.isspace() or char in "/\\:@" for char in component): + raise ValueError(f"Invalid legacy Maven coordinate: {coordinate!r}") + + filename = generate_filename_from_maven_coordinate( + artifact, version, classifier=classifier, extension=extension, + ) + add_artifact(file_path, generate_repo_path(group, artifact, version, filename)) + + output_root.mkdir(parents=True, exist_ok=True) + copied = [] + for destination, (source, digest) in artifacts.items(): + _checked_artifact_path(root, source.relative_to(root).as_posix()) + _checked_artifact_path(output_root, destination.relative_to(output_root).as_posix()) + + if destination.is_file() and _artifact_sha256(destination) == digest: + continue + + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = None + try: + with NamedTemporaryFile(dir=destination.parent, prefix=f".{destination.name}.", + suffix=".tmp", delete=False) as stream: + temporary = Path(stream.name) + + shutil.copy2(source, temporary) + if _artifact_sha256(temporary) != digest: + raise ValueError(f"Copied artifact hash does not match source: {source}") + + temporary.replace(destination) + copied.append(destination) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return copied + except Exception as exc: + raise LoaderInstallError( + f"Failed to copy embedded artifact from {source} to {destination}: {exc}" + ) from exc + + +def collect_install_dependencies(install_plan: LoaderInstallPlan, libraries_dir: Path) -> list[FileObject]: + """ + Collect install dependencies from manifest and install profile. + :param install_plan: + :param libraries_dir: + + Missing SHA-1 is allowed, but a supplied hash must be valid. Local/generated + artifacts marked ignoreMissingURL are excluded. No files are created here. + Contains many checks to deal with the issue that forge install profile or manifest may contain invalid paths, missing + url... + :return: + """ + context = "libraries root" + try: + # Check libraries dir + libraries_dir = Path(libraries_dir) + if _is_artifact_link(libraries_dir): + raise ValueError("Libraries root must not be a link") + + root = libraries_dir.resolve() + if root.exists() and not root.is_dir(): + raise ValueError("Libraries root must be a directory") + + files: dict[Path, FileObject] = {} + + for source_name, manifest in ( + ("version manifest", install_plan.version_manifest), + ("install profile", install_plan.install_profile), + ): + if manifest is None: + continue + + if not isinstance(manifest, dict): # ignore invalid manifest + raise ValueError(f"{source_name} must be an object") + + libraries = manifest.get("libraries") + # Ignore invalid or empty + if libraries is None: + continue + elif not libraries: + continue + + if not isinstance(libraries, list): + raise ValueError(f"{source_name} libraries must be a list") + + for index, library in enumerate(libraries): + context = f"{source_name} library #{index}" + if not isinstance(library, dict): + raise ValueError("Library must be an object") + + context += f" ({library.get('name', 'unnamed')})" + + # Get flag that sat by add_missing_url_flag_to_generated_after_install_libraries + ignore_missing_url = library.get( + "ignoreMissingURL", + library.get("ignoreMissingUrl", False), + ) + if not isinstance(ignore_missing_url, bool): + raise ValueError("ignoreMissingURL must be a boolean") + + # Skip libraries that will be generated after installation + if ignore_missing_url: + continue + + downloads = library.get("downloads") + if not isinstance(downloads, dict): + raise ValueError("Library downloads must be an object") + + artifact = downloads.get("artifact") + if not isinstance(artifact, dict): + raise ValueError("Library downloads.artifact must be an object") + + url = artifact.get("url") + if ( + not isinstance(url, str) or not url + or any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in url) + or "\\" in url + ): + raise ValueError("Artifact URL must be a non-empty HTTP(S) URL without whitespace") + + # Not sure if this will be triggered in the daily use? + # Check protocol, fragment, credentials, path + parsed = urlsplit(url) + if ( + parsed.scheme.lower() not in ("http", "https") or not parsed.hostname + or parsed.username is not None or parsed.password is not None + or parsed.fragment + ): + raise ValueError("Artifact URL requires an HTTP(S) host and no credentials or fragment") + + # Accessing port also rejects non-numeric and out-of-range values. + if parsed.port is not None and parsed.port == 0: + raise ValueError("Artifact URL port must be between 1 and 65535") + + # Check sha1 + sha1 = artifact.get("sha1") + if sha1 is not None: + if not isinstance(sha1, str) or not re.fullmatch(r"[0-9a-fA-F]{40}", sha1): + raise ValueError("Artifact SHA-1 must contain exactly 40 hexadecimal characters") + + sha1 = sha1.lower() + + # Check path + path = artifact.get("path") + if not isinstance(path, str) or not path: + raise ValueError("Artifact path must be a non-empty relative string") + + if any(ord(char) < 32 or ord(char) == 127 for char in path): + raise ValueError("Artifact path must not contain control characters") + + reserved_names = {"CON", "PRN", "AUX", "NUL"} | { + f"{prefix}{number}" for prefix in ("COM", "LPT") for number in range(1, 10) + } + if any(part.split(".", 1)[0].upper() in reserved_names + for part in path.replace("\\", "/").split("/")): + raise ValueError("Artifact path must not use Windows device names") + + # Check destination + destination = _checked_artifact_path(root, path) + if destination.exists() and not destination.is_file(): + raise ValueError(f"Artifact destination is not a file: {destination}") + + previous = files.get(destination) + if previous is not None: + if previous.url != url or ( + previous.expected_sha1 is not None and sha1 is not None + and previous.expected_sha1 != sha1 + ): + raise ValueError(f"Conflicting download metadata for {destination}") + + if previous.expected_sha1 is None: + previous.expected_sha1 = sha1 + + continue + + files[destination] = FileObject(url=url, sha1=sha1, path=destination) + return list(files.values()) + except Exception as exc: + raise LoaderInstallError(f"Invalid install dependency in {context}: {exc}") from exc + +def resolve_processor_value(value: str, *, variables: Mapping[str, str], libraries_dir: Path) -> str: + """ + Resolve one processor argument, output path, or output hash. + """ + if not isinstance(value, str): + raise LoaderInstallError("Processor value must be a string") + + # Quoted values are literals, not paths. + if value.startswith("'") and value.endswith("'") and len(value) >= 2: + return value[1:-1] + + def replace_variable(match: re.Match) -> str: + key = match.group(1) + if key not in variables: + raise LoaderInstallError(f"Unknown processor variable: {key}") + + replacement = variables[key] + if not isinstance(replacement, str): + raise LoaderInstallError(f"Invalid processor variable: {key}") + + return replacement + + token_pattern = re.compile(r"\{([^{}]+)\}") + unmatched = token_pattern.sub("", value) + if "{" in unmatched or "}" in unmatched: + raise LoaderInstallError( + f"Malformed processor value: {value!r}" + ) + resolved = token_pattern.sub(replace_variable, value) + + # Variables already contain final values. Do not reinterpret a substituted + # literal (which may itself contain brackets or braces) as installer syntax. + if value.startswith("[") and value.endswith("]"): + coordinate = resolved[1:-1] + try: + group, artifact, version, classifier, extension = ( + parse_maven_coordinate(coordinate) + ) + filename = generate_filename_from_maven_coordinate( + artifact, + version, + classifier=classifier, + extension=extension, + ) + relative_path = generate_repo_path( + group, artifact, version, filename, + ) + root = Path(libraries_dir) + if _is_artifact_link(root): + raise ValueError("Libraries root must not be a link") + + return str(_checked_artifact_path(root.resolve(), relative_path)) + except (ValueError, OSError) as exc: + raise LoaderInstallError( + f"Invalid processor artifact: {coordinate!r}" + ) from exc + + return resolved + +def run_processors(install_plan: LoaderInstallPlan, libraries_dir: Path, *, + java_path: Path, minecraft_jar: Path, minecraft_root: Path, + progress_callback: Callable[[str, float], None] | None = None, + timeout: float | None = None) -> None: + """ + Run forge-like processors in order and record verified outputs in the manifest. + + The caller supplies downloaded dependencies and a compatible Java executable. + Save version_manifest after success, including forgeInstall, for launch-time + checks. No manifest is written to disk and no downloads are performed here. + + :param install_plan: Loader install plan + :param libraries_dir: Path to the libraries directory + :param java_path: Path to the Java executable + :param minecraft_jar: Path to the Minecraft JAR file + :param minecraft_root: Path to the Minecraft root directory (Libraries should be in this directory) + :param progress_callback: Optional callback for progress updates + :param timeout: Optional timeout for the processor run + """ + context = "processor configuration" + + try: + if not isinstance(install_plan.version_manifest, dict): + raise ValueError("Version manifest must be an object") + + install_plan.version_manifest.pop("forgeInstall", None) + libraries_dir = _processor_root(libraries_dir) + minecraft_root = _processor_root(minecraft_root) + minecraft_jar = Path(minecraft_jar).resolve() + java_path = Path(java_path).resolve() + processors = _client_processors(install_plan.install_profile) + variables = build_processor_variables( + install_plan, libraries_dir, minecraft_jar=minecraft_jar, + minecraft_root=minecraft_root, + ) if processors else {} # 1.12.2 and older don't have processors or is empty + + tracked: dict[Path, str | None] = {} + for index, processor in enumerate(processors, start=1): + context = f"client processor {index}/{len(processors)} ({processor.get('jar')})" + outputs = _processor_outputs(processor, variables, libraries_dir) + + # Later processors may overwrite earlier intermediates. + tracked.update(outputs) + + # Only declared, hash-verified outputs provide a safe cache hit. + if outputs and all(sha1 is not None and _valid_installed_file(path, sha1) + for path, sha1 in outputs.items()): + logger.info("Skipping cached %s", context) + else: + if not java_path.is_file(): + raise ValueError(f"Java executable does not exist: {java_path}") + + if not _valid_installed_file(minecraft_jar): + raise ValueError(f"Minecraft client JAR is missing or invalid: {minecraft_jar}") + + jar_raw: str | None = processor.get("jar") # processor maven address + + if not jar_raw: + raise ValueError("Processor missing key \"jar\" (Aka processor maven address)") + + jar = _processor_artifact(jar_raw, libraries_dir) + classpath = processor.get("classpath", []) + if not isinstance(classpath, list): + raise ValueError("Processor classpath must be a list") + + # Append processor dependencies (including itself) + dependencies = [jar] + [_processor_artifact(item, libraries_dir) for item in classpath] + dependencies = list(dict.fromkeys(dependencies)) + for dependency in dependencies: + if not _valid_installed_file(dependency): + raise ValueError(f"Processor dependency is missing or invalid: {dependency}") + + # Get processor arguments + args = _processor_args(processor, variables, libraries_dir) + for output in outputs: + output.parent.mkdir(parents=True, exist_ok=True) + + minecraft_root.mkdir(parents=True, exist_ok=True) + + # Generate processor command + command = [str(java_path), "-cp", os.pathsep.join(map(str, dependencies)), + _jar_main_class(jar), *args] + + # Run processor + logger.info("Running %s: %s", context, command) + completed = subprocess.run( + command, cwd=minecraft_root, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=timeout, + creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, + ) + + if completed.stdout: + logger.info("%s stdout:\n%s", context, completed.stdout) + + if completed.stderr: + logger.warning("%s stderr:\n%s", context, completed.stderr) + + if completed.returncode != 0: + raise ValueError( + f"Processor exited with code {completed.returncode}: " + f"{(completed.stderr or completed.stdout or '')[-2000:]}" + ) + + # Check output files + for output, sha1 in outputs.items(): + _checked_artifact_path(libraries_dir, output.relative_to(libraries_dir).as_posix()) + if not _valid_installed_file(output, sha1): + raise ValueError(f"Processor output is missing, corrupt or has the wrong hash: {output}") + + if progress_callback is not None: + progress_callback(context, index / len(processors) * 100) + + # Includes embedded/legacy artifacts and generated runtime libraries. + for path, sha1, size in _generated_libraries(install_plan.version_manifest, libraries_dir): + if not _valid_installed_file(path, sha1, size): + raise ValueError(f"Required installed artifact is missing or invalid: {path}") + tracked[path] = sha1 + + records = [] + for path in tracked: + _checked_artifact_path(libraries_dir, path.relative_to(libraries_dir).as_posix()) + + if not _valid_installed_file(path, tracked[path]): + raise ValueError(f"Installed processor artifact is missing or invalid: {path}") + + records.append({ + "path": path.relative_to(libraries_dir).as_posix(), + "sha1": FileObject(path).sha1, "size": path.stat().st_size, + }) + + install_plan.version_manifest["forgeInstall"] = { + "schema": 1, "versionId": install_plan.version_id, + "loader": install_plan.loader_name, "loaderVersion": install_plan.loader_version, + "minecraftVersion": install_plan.minecraft_version, "outputs": records, + } + except Exception as exc: + raise LoaderInstallError(f"Failed to run {context}: {exc}") from exc + + +def _processor_root(path: Path) -> Path: + path = Path(path) + + if _is_artifact_link(path): + raise ValueError(f"Processor root must not be a link: {path}") + + return path.resolve() + + +def _client_processors(profile: dict | None) -> list[dict]: + if profile is None: + return [] + + if not isinstance(profile, dict): + raise ValueError("Install profile must be an object") + + processors = profile.get("processors", []) + if not isinstance(processors, list): + raise ValueError("Processors must be a list") + + selected = [] + for processor in processors: + if not isinstance(processor, dict): + raise ValueError("Processor must be an object") + + sides = processor.get("sides") + if sides is not None and (not isinstance(sides, list) or + not all(isinstance(side, str) for side in sides)): + raise ValueError("Processor sides must be a list of strings") + + if sides is None or "client" in sides: + selected.append(processor) + + return selected + + +def build_processor_variables(install_plan: LoaderInstallPlan, libraries_dir: Path, *, + minecraft_jar: Path, minecraft_root: Path) -> dict[str, str]: + """Resolve client data entries, then inject the six reserved installer tokens.""" + libraries_dir = _processor_root(libraries_dir) + variables = {} + data = (install_plan.install_profile or {}).get("data", {}) + + if not isinstance(data, dict): + raise LoaderInstallError("Processor data must be an object") + + reserved = {"SIDE", "MINECRAFT_JAR", "MINECRAFT_VERSION", "ROOT", "INSTALLER", "LIBRARY_DIR"} # necessary variable + # that used by processor + + for key, entry in data.items(): + if key in reserved: + continue + + if not isinstance(key, str) or not isinstance(entry, dict): + raise LoaderInstallError(f"Invalid processor data entry: {key!r}") + + value = entry.get("client") + if not isinstance(value, str) or not value: + raise LoaderInstallError(f"Processor data has no client value: {key}") + if (value.startswith("[") and value.endswith("]")) or ( + value.startswith("'") and value.endswith("'") + ): + variables[key] = resolve_processor_value(value, variables={}, libraries_dir=libraries_dir) + else: + root = _processor_root(install_plan.extracted_dir) + resource = _checked_artifact_path(root, value.lstrip("/")) + if not resource.is_file(): + raise LoaderInstallError(f"Installer data resource is missing: {resource}") + variables[key] = str(resource) + + variables.update({ + "SIDE": "client", "MINECRAFT_JAR": str(Path(minecraft_jar).resolve()), + "MINECRAFT_VERSION": install_plan.minecraft_version, + "ROOT": str(_processor_root(minecraft_root)), + "INSTALLER": str(Path(install_plan.installer_path).resolve()), + "LIBRARY_DIR": str(libraries_dir), + }) + return variables + + +def _processor_artifact(coordinate: str, libraries_dir: Path) -> Path: + if not isinstance(coordinate, str) or not coordinate or any(char in coordinate for char in "[]{}"): + raise ValueError(f"Invalid processor artifact: {coordinate!r}") + + return Path(resolve_processor_value(f"[{coordinate}]", variables={}, libraries_dir=libraries_dir)) + + +def _processor_args(processor: dict, variables: Mapping[str, str], libraries_dir: Path) -> list[str]: + args = processor.get("args", []) + if not isinstance(args, list): + raise ValueError("Processor args must be a list") + + result = [resolve_processor_value(arg, variables=variables, libraries_dir=libraries_dir) for arg in args] + if any("\0" in arg for arg in result): + raise ValueError("Processor args must not contain NUL") + + return result + + +def _processor_output_path(value: str, libraries_dir: Path) -> Path: + path = Path(value) + if not path.is_absolute() or not path.is_relative_to(libraries_dir): + raise ValueError(f"Processor output must be under libraries: {value}") + + return _checked_artifact_path(libraries_dir, path.relative_to(libraries_dir).as_posix()) + + +def _processor_outputs(processor: dict, variables: Mapping[str, str], + libraries_dir: Path) -> dict[Path, str | None]: + """ + Find output paths in processor data. + :param processor: + :param variables: + :param libraries_dir: + :return: + """ + raw = processor.get("outputs", {}) + if not isinstance(raw, dict): + raise ValueError("Processor outputs must be an object") + + outputs = {} + for key, value in raw.items(): + path = _processor_output_path( + resolve_processor_value(key, variables=variables, libraries_dir=libraries_dir), libraries_dir, + ) + sha1 = resolve_processor_value(value, variables=variables, libraries_dir=libraries_dir) + + if re.fullmatch(r"[0-9a-fA-F]{40}", sha1) is None: + raise ValueError(f"Invalid processor output SHA-1: {sha1!r}") + + if path in outputs and outputs[path] != sha1.lower(): + raise ValueError(f"Conflicting processor output hashes: {path}") + + outputs[path] = sha1.lower() + + # New NeoForge profiles omit outputs. Track explicit output arguments and + # record their resulting hashes so later launches can validate them offline. + args = _processor_args(processor, variables, libraries_dir) + for index, arg in enumerate(args): + value = None + + if arg in ("--output", "--out-jar"): + if index + 1 >= len(args): + raise ValueError(f"Missing value for processor argument {arg}") + value = args[index + 1] + elif arg.startswith(("--output=", "--out-jar=")): + value = arg.partition("=")[2] + if value is not None: + outputs.setdefault(_processor_output_path(value, libraries_dir), None) + + return outputs + + +def _jar_main_class(path: Path) -> str: + with zipfile.ZipFile(path) as jar: + text = jar.read("META-INF/MANIFEST.MF").decode("utf-8") + + # JAR manifest attributes may continue on the following space-prefixed line. + text = re.sub(r"\r?\n ", "", text) + for line in text.splitlines(): + if not line: + break # Named sections must not supply the main entry point. + + key, separator, value = line.partition(":") + if separator and key.lower() == "main-class": + value = value.strip() + if re.fullmatch(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*", value): + return value + + raise ValueError(f"Processor JAR has no valid Main-Class: {path}") + + +def _valid_installed_file(path: Path, sha1: str | None = None, size: int | None = None) -> bool: + if not path.is_file() or path.stat().st_size == 0: + return False + + if size is not None and (type(size) is not int or size < 0 or path.stat().st_size != size): + return False + + if sha1 is not None: + if not isinstance(sha1, str) or re.fullmatch(r"[0-9a-fA-F]{40}", sha1) is None: + return False + + return FileObject(path).sha1 == sha1.lower() + + if path.suffix.lower() == ".jar": + try: + with zipfile.ZipFile(path) as jar: + return jar.testzip() is None + except (OSError, zipfile.BadZipFile, RuntimeError): + return False + + return True + + +def _generated_libraries(manifest: dict, libraries_dir: Path) -> list[tuple[Path, str | None, int | None]]: + libraries = manifest.get("libraries", []) + if not isinstance(libraries, list) or not all(isinstance(item, dict) for item in libraries): + raise ValueError("Manifest libraries must be a list of objects") + + generated = [] + for library in filter_platform_libraries(libraries): + artifact = (library.get("downloads") or {}).get("artifact") or {} + + if not isinstance(artifact, dict): + raise ValueError("Library artifact must be an object") + if not (library.get("ignoreMissingURL") or library.get("ignoreMissingUrl")) and ( + artifact.get("url") or library.get("url") + ): + continue + + relative = artifact.get("path") + if relative is not None: + if not isinstance(relative, str): + raise ValueError("Library path must be a string") + path = _checked_artifact_path(libraries_dir, relative) + else: + name: str | None = library.get("name") + + if not name: + raise ValueError("Library name is missing: {}".format(library)) + + path = _processor_artifact(name, libraries_dir) + + generated.append((path, artifact.get("sha1", library.get("sha1")), artifact.get("size", library.get("size")))) + + return generated + + +def check_forge_dependencies(version_manifest: dict, libraries_dir: Path) -> bool: + """ + Check forge dependencies after post-installation. + :param version_manifest: + :param libraries_dir: + :return: + is_ok: bool (True when installer artifacts are valid; False means rerun the installer) + """ + try: + libraries_dir = _processor_root(libraries_dir) + generated = _generated_libraries(version_manifest, libraries_dir) + for path, sha1, size in generated: + if not _valid_installed_file(path, sha1, size): + logger.info("Forge installation needs repair: %s", path) + return False + + receipt = version_manifest.get("forgeInstall") + if receipt is None: + return bool(generated) + if ( + not isinstance(receipt, dict) or type(receipt.get("schema")) is not int or receipt.get("schema") != 1 + or receipt.get("versionId") != version_manifest.get("id") + or receipt.get("loader") not in FORGE_LIKE_LOADERS + or not isinstance(receipt.get("outputs"), list) + ): + return False + + parent = version_manifest.get("inheritsFrom") + if parent is not None and receipt.get("minecraftVersion") != parent: + return False + + # Check processor outputs + for output in receipt["outputs"]: + if not isinstance(output, dict) or not isinstance(output.get("path"), str): + return False + + path = _checked_artifact_path(libraries_dir, output["path"]) + + # Verify installed file that generated by processor + if (not isinstance(output.get("sha1"), str) or "size" not in output + or not _valid_installed_file(path, output["sha1"], output["size"])): + logger.info("Forge processor output needs repair: %s", path) + return False + + return True + except (OSError, ValueError, TypeError, AttributeError, LoaderInstallError) as exc: + logger.warning("Unable to validate Forge installation: %s", exc) + return False diff --git a/core_lib/game/mod/mod_core.py b/core_lib/game/mod/mod_core.py index bcc51ac..97f7117 100644 --- a/core_lib/game/mod/mod_core.py +++ b/core_lib/game/mod/mod_core.py @@ -22,26 +22,19 @@ LOADER_LIBRARY_MARKERS = { def detect_loader_name(manifest: dict) -> str | None: - candidates = set() + """Read the recorded loader identity without inferring it from dependencies.""" + loader_name = manifest.get("loader") + if isinstance(loader_name, str) and loader_name: + return loader_name - for library in manifest.get("libraries", []): - name = library.get("name", "") - parts = name.split(":") + # Older Forge installations already record the identity in their receipt. + receipt = manifest.get("forgeInstall") + if isinstance(receipt, dict): + loader_name = receipt.get("loader") + if isinstance(loader_name, str) and loader_name: + return loader_name - if len(parts) < 3: - continue - - loader_name = LOADER_LIBRARY_MARKERS.get( - (parts[0], parts[1]) - ) - if loader_name: - candidates.add(loader_name) - - # Return None if no loader is found or multiple loaders are found. - if len(candidates) != 1: - return None - - return next(iter(candidates)) + return None def find_useful_part_in_mod_version_manifest(mod_version_manifest: dict): ver_id = mod_version_manifest.get("id", None) @@ -95,7 +88,20 @@ def find_useful_part_in_mod_version_manifest(mod_version_manifest: dict): def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, inherits_maven_url=MOJANG_LIBRARIES_ENDPOINT, mod_maven_url=None, default_extension="jar", - prefer_libraries_by: LibraryPreference = PREFER_MOD_LIBRARY) -> list[dict]: + prefer_libraries_by: LibraryPreference = PREFER_MOD_LIBRARY, + ignore_missing_url_libraries=False) -> list[dict]: + """ + Merge necessary dependencies + :param inherits_libraries: + :param mod_libraries: + :param inherits_maven_url: + :param mod_maven_url: + :param default_extension: + :param prefer_libraries_by: + :param ignore_missing_url_libraries: Skip url regeneration if library url is missing and contains the key + "ignoreMissingURL": true + :return: + """ inherits = {} result_pre = [] @@ -286,8 +292,9 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, # Check library download url endpoint = library["parsed"]["endpoint"] # maven url artifact_url = ((library.get("downloads") or {}).get("artifact") or {}).get("url") + ignore_missing_url = library.get("ignoreMissingURL", False) - if not artifact_url and not library.get("url") and not endpoint: + if not artifact_url and not library.get("url") and not endpoint and not ignore_missing_url: raise DependencyException( f"No download source for library {library['name']!r}." ) @@ -295,7 +302,8 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, library_normalized = normalize_library_to_common_struct( library, default_maven_url=endpoint, - default_extension=default_extension + default_extension=default_extension, + ignore_missing_url=ignore_missing_url ) # Cleanup and append @@ -363,11 +371,23 @@ def merge_manifest(inherits_version_manifest: dict, mod_version_manifest: dict, prefer_libraries_by=prefer_libraries_by ) - # arguments - inherits_arguments = inherits_version_manifest.get("arguments", []) or inherits_version_manifest.get("minecraftArguments", "") - mod_arguments = mod_version_manifest.get("arguments", {}) or mod_version_manifest.get("minecraftArguments", {}) + # Modern argument arrays extend the parent. Legacy minecraftArguments is a + # complete game command line (including vanilla options), so it replaces it. + def read_arguments(manifest: dict) -> dict: + arguments = deepcopy(manifest.get("arguments") or {}) + if "game" not in arguments and manifest.get("minecraftArguments"): + arguments["game"] = shlex.split(manifest["minecraftArguments"]) + return arguments + + inherits_arguments = read_arguments(inherits_version_manifest) + mod_arguments = read_arguments(mod_version_manifest) + if (mod_version_manifest.get("minecraftArguments") + and "game" not in (mod_version_manifest.get("arguments") or {})): + inherits_arguments.pop("game", None) merged_manifest["arguments"] = merge_game_and_jvm_args(inherits_arguments, mod_arguments) + # The merged manifest now has a single canonical argument representation. + merged_manifest.pop("minecraftArguments", None) # Update version number mod_id = mod_version_manifest.get("id") @@ -379,4 +399,14 @@ def merge_manifest(inherits_version_manifest: dict, mod_version_manifest: dict, if inherits_id: merged_manifest["inheritsFrom"] = inherits_id - return merged_manifest \ No newline at end of file + # Keep the child's recorded identity instead of inheriting the parent's. + merged_manifest.pop("loader", None) + loader_name = detect_loader_name(mod_version_manifest) + if loader_name is not None: + merged_manifest["loader"] = loader_name + + # Processor output receipts must survive inheritance for launch-time checks. + if "forgeInstall" in mod_version_manifest: + merged_manifest["forgeInstall"] = deepcopy(mod_version_manifest["forgeInstall"]) + + return merged_manifest diff --git a/core_lib/game/mod/rules.py b/core_lib/game/mod/rules.py index 1897092..2a3f3ec 100644 --- a/core_lib/game/mod/rules.py +++ b/core_lib/game/mod/rules.py @@ -3,14 +3,32 @@ from core_lib.game.mod.mod_core import PREFER_MOD_LIBRARY MOD_LOADER_RULES = { "fabric": { "preferLibraryBy": PREFER_MOD_LIBRARY, + "maven": { + "group": "net.fabricmc", + "name": "fabric-loader" + } }, "forge": { "preferLibraryBy": PREFER_MOD_LIBRARY, + "maven": { + "group": "net.minecraftforge", + "name": "forge" + } }, "neoforge": { "preferLibraryBy": PREFER_MOD_LIBRARY, + "maven": { + "group": "net.neoforged", + "name": "neoforge" + } }, "quilt": { "preferLibraryBy": PREFER_MOD_LIBRARY, + "maven": { + "group": "net.quiltmc", + "name": "quilt-loader" + } } -} \ No newline at end of file +} + +FORGE_LIKE_LOADERS = ["forge", "neoforge"] \ No newline at end of file diff --git a/core_lib/game/version_info.py b/core_lib/game/version_info.py index 33073cb..d8b1595 100644 --- a/core_lib/game/version_info.py +++ b/core_lib/game/version_info.py @@ -1,5 +1,6 @@ import json import logging +import re import tempfile import warnings from collections.abc import Callable @@ -12,7 +13,6 @@ from ..common.common import FileObject, download_file, SUPPORTED_HASH_ALGORITHMS from ..common.exception import VersionManifestFetchException, NoVersionFoundException, \ NoSpecifiedVersionKeyException, VersionDataKeyNotFoundException, VersionManifestSaveException, \ HashMismatchException, UnsupportedHashAlgorithmException -from ..i18n import SUPPORTED_LANGUAGES MOJANG_VERSION_MANIFEST_V2 = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" MOJANG_VERSION_MANIFEST = "https://piston-meta.mojang.com/mc/game/version_manifest.json" @@ -602,6 +602,13 @@ def check_core_file_exists_and_verify(manifest: dict, core_file_path: Path, return True +def validate_minecraft_version(version: str) -> bool: + if not isinstance(version, str) or not re.fullmatch( + r"[A-Za-z0-9][A-Za-z0-9._+\-]*", version): + return False + + return True + LATEST_VERSION_ALIASES = { "latest-release": {"displayName": "Latest Release"}, "latest-snapshot": {"displayName": "Latest Snapshot"}, diff --git a/manager/game.py b/manager/game.py index 062fa19..fba8ab9 100644 --- a/manager/game.py +++ b/manager/game.py @@ -10,6 +10,7 @@ import traceback from collections.abc import Callable from dataclasses import dataclass, field, replace from pathlib import Path +from tempfile import TemporaryDirectory from threading import Thread from typing import Literal from uuid import uuid4 @@ -17,15 +18,16 @@ from PySide6.QtCore import QObject, Signal from constant import CLIENT_ID, LAUNCHER_VERSION from core_lib.common.common import FileObject, download_multiple_files -from core_lib.common.exception import JavaRuntimeException +from core_lib.common.exception import JavaRuntimeException, LoaderInstallError from core_lib.game.argument import ArgumentMappings, generate_launch_command from core_lib.game.asset import check_assets_exist, download_assets, find_correct_assets_dir from core_lib.game.library_core import check_full_libraries_exists, download_full_libraries, generate_classpath +from core_lib.game.mod import forge_like from core_lib.game.mod.mod_core import merge_manifest, PREFER_MOD_LIBRARY, detect_loader_name 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, \ 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 + LATEST_VERSION_ALIASES, check_core_file_exists_and_verify, validate_version_manifest, validate_minecraft_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 manager.account import AccountManager, LaunchAccount @@ -50,6 +52,7 @@ class ManifestManager: # Flags self.use_expired_manifest = False self._manifest_prompt_lock = threading.Lock() + self._manifest_rebuild_lock = threading.Lock() # # ============ Version Data Cache ============ @@ -61,6 +64,98 @@ class ManifestManager: def get_specific_version_manifest_path(self, target_version: str) -> Path | None: return Path(self.app.work_dir, "versions", target_version, f"{target_version}.json") + def _manifest_rebuild_text(self, text: str, **values) -> str: + translate = getattr(self.app, "tr_text", None) + return translate(text, **values) if callable(translate) else text.format(**values) + + def _get_manifest_backup_path(self, version_id: str) -> Path: + if not validate_minecraft_version(version_id): + raise ValueError("Invalid version ID: {}".format(version_id)) + root = Path(self.app.work_dir).resolve() + path = root / "cache" / "version_manifests" / "{}.json".format(version_id) + if not path.resolve().is_relative_to(root): + raise ValueError("Manifest backup path is outside the launcher directory.") + return path + + def backup_version_manifest(self, version_id: str, payload: bytes | None = None) -> None: + """Keep verified manifest bytes for recovery, including custom loader metadata.""" + try: + backup = self._get_manifest_backup_path(version_id) + if payload is None: + source = self.get_specific_version_manifest_path(version_id) + if source is None: + raise ValueError("Version manifest path is unavailable") + root = Path(self.app.work_dir).resolve() / "versions" + if not source.resolve().is_relative_to(root): + raise ValueError("Version manifest path is outside the versions directory") + payload = source.read_bytes() + validate_version_manifest(json.loads(payload.decode("utf-8")), version_id) + if backup.is_file() and backup.read_bytes() == payload: + return + save_version_manifest(payload, backup) + except Exception as exc: + # An optional recovery copy must not turn a successful read/install into failure. + self.app.logger.warning("Unable to back up manifest %s: %s", version_id, exc) + + def rebuild_missing_version_manifest(self, version_id: str) -> dict | None: + """Ask before restoring a missing manifest; download known vanilla versions if needed.""" + with self._manifest_rebuild_lock: + try: + backup = self._get_manifest_backup_path(version_id) + path = self.get_specific_version_manifest_path(version_id) + root = Path(self.app.work_dir).resolve() / "versions" + if path is None or not path.resolve().is_relative_to(root): + raise ValueError("Version manifest path is outside the versions directory") + # Another launch may have completed recovery while this one waited. + if path.is_file(): + return self._read_cached_version_manifest(version_id) + + request = AskForRequest( + self._manifest_rebuild_text("Missing version manifest"), + self._manifest_rebuild_text( + "The manifest for version {version} is missing. Rebuild it now?", version=version_id, + ), + ) + request.details = str(path) + self.widget_mgr.signal.askyesno.emit(request) + if not request.wait(120): + self.widget_mgr.signal.show_error_message.emit(self._manifest_rebuild_text( + "Timed out while waiting to rebuild the version manifest." + )) + return None + if request.result() is not True: + return None + + if path.is_file(): + return self._read_cached_version_manifest(version_id) + + if backup.is_file(): + try: + payload = backup.read_bytes() + validate_version_manifest(json.loads(payload.decode("utf-8")), version_id) + except (OSError, ValueError) as exc: + self.app.logger.warning("Ignoring invalid manifest backup %s: %s", backup, exc) + else: + return save_version_manifest(payload, path) + + root_manifest = self.get_cached_version_manifest() + if root_manifest is None: + return None + if any(item.get("id") == version_id for item in root_manifest.get("versions", [])): + return self.get_cached_version_manifest(version_id) + + self.widget_mgr.signal.show_error_message.emit(self._manifest_rebuild_text( + "No valid backup is available for {version}. Reinstall this mod-loader version " + "or restore its custom manifest, then try launching again.", version=version_id, + )) + return None + except Exception as exc: + self.app.logger.exception("Unable to rebuild version manifest %s", version_id) + self.widget_mgr.signal.show_error_message.emit(self._manifest_rebuild_text( + "Unable to rebuild the manifest for {version}: {error}", version=version_id, error=str(exc), + )) + return None + def switch_between_specific_path(self, specified_ver: str | None = None): if specified_ver is None: path = self.version_manifest_path @@ -75,6 +170,8 @@ class ManifestManager: self.switch_between_specific_path(specified_ver), target_version=specified_ver, root_manifest=root_manifest, ) + if specified_ver is not None: + self.backup_version_manifest(specified_ver) return True, data except Exception as exc: self.app.logger.warning("Unable to refresh version manifest: %s", exc) @@ -85,6 +182,7 @@ class ManifestManager: data, sha1 = fetch_manifest_handler(version_id) validate_version_manifest(data, version_id) save_version_manifest(data, self.get_specific_version_manifest_path(version_id), sha1=sha1) + self.backup_version_manifest(version_id) return True, data except Exception as exc: self.app.logger.warning("Unable to refresh custom manifest %s: %s", version_id, exc) @@ -101,6 +199,8 @@ class ManifestManager: raise ValueError("Cached manifest SHA-1 does not match") data = json.loads(payload.decode("utf-8")) validate_version_manifest(data, specified_ver) + if specified_ver is not None: + self.backup_version_manifest(specified_ver, payload) return data except (OSError, ValueError) as exc: self.app.logger.warning("Ignoring invalid cached manifest %s: %s", path, exc) @@ -218,7 +318,8 @@ class ManifestManager: version_id: str client_version_id: str - def resolve_manifest(self, version_id: str, visited: set[str] | None = None) -> ResolvedVersionManifest | None: + def resolve_manifest(self, version_id: str, visited: set[str] | None = None, *, + allow_rebuild: bool = False) -> ResolvedVersionManifest | None: visited = set() if visited is None else visited if version_id in visited: @@ -240,6 +341,8 @@ class ManifestManager: # Read the custom (or mod loader) manifest first. If not exist, get manifest from official data if manifest_path.is_file(): manifest = self._read_cached_version_manifest(version_id) + elif allow_rebuild: + manifest = self.rebuild_missing_version_manifest(version_id) else: manifest = self.get_cached_version_manifest(version_id) @@ -257,21 +360,14 @@ class ManifestManager: ) # Get the parent manifest if needed - parent = self.resolve_manifest(parent_id, visited) + parent = self.resolve_manifest(parent_id, visited, allow_rebuild=allow_rebuild) if parent is None: return None try: - # TODO: Get absolute loader name with a reliable method. Not guess it. loader_name = detect_loader_name(manifest) - - if loader_name is None: - self.widget_mgr.signal.show_error_message.emit( - f"Unable to detect loader name for version {version_id}" - ) - return None - + # Untagged legacy and custom manifests use the default merge policy. rules = MOD_LOADER_RULES.get(loader_name, {}) # Merge official and loader manifest @@ -771,10 +867,11 @@ class GameFileDownloadRequest(SignalTransferItem): self.args: tuple = args class GameFileManager: - def __init__(self, app, manifest_manager: ManifestManager): + def __init__(self, app, manifest_manager: ManifestManager, java_mgr: JavaManager): self.app = app self.widget_mgr = app.widget_manager self.manifest_mgr = manifest_manager + self.java_mgr = java_mgr self.jobs = { "download_client": self.download_client, "download_libraries": self.download_libraries, @@ -1008,6 +1105,154 @@ class GameFileManager: return False, pending + def install_forge_like_version( + self, + loader_name: Literal["forge", "neoforge"], + minecraft_version: str, + loader_version: str, + *, + progress_callback: Callable[[str, float], None] | None = None, + status_callback: Callable[[str], None] | None = None, + error_callback: Callable[[str, str], None] | None = None, + ) -> tuple[dict | None, dict | None]: + """ + Install Forge or NeoForge and save the verified loader manifest. + :param loader_name: + :param minecraft_version: + :param loader_version: Full Maven version from the loader version list. + :param progress_callback: + :param status_callback: Receives the current installation stage. + :param error_callback: Receives the failed stage and traceback instead of a global error dialog. + :return: + vanilla_manifest: dict | None + loader_manifest: dict | None + """ + task_id = None + stage = "validating installation request" + + def update_stage(value: str): + nonlocal stage + stage = value + if status_callback is not None: + status_callback(stage) + + try: + update_stage("validating installation request") + if loader_name not in ("forge", "neoforge"): + raise LoaderInstallError("Unsupported loader: {}".format(loader_name)) + + if not validate_minecraft_version(minecraft_version): + raise LoaderInstallError("Invalid Minecraft version: {}".format(minecraft_version)) + + if progress_callback is None: + progress_callback, task_id = self.manifest_mgr.create_download_progress_callback( + "Installing {} {}".format(loader_name, loader_version) + ) + + # Get the parent manifest before preparing the loader. + update_stage("loading the vanilla manifest") + vanilla = self.manifest_mgr.get_cached_version_manifest(minecraft_version) + if vanilla is None: + raise LoaderInstallError("Unable to load the vanilla manifest.") + + root = Path(self.app.work_dir).resolve() + libraries_dir = root / "libraries" + client_jar = root / "versions" / minecraft_version / "{}.jar".format(minecraft_version) + + update_stage("preparing the installer") + with TemporaryDirectory(prefix="forge-install-") as temporary: + plan = forge_like.prepare_installer( + loader_name, loader_version, Path(temporary), + minecraft_version=minecraft_version, + progress_callback=progress_callback, + ) + + version_id = plan.version_id + if not isinstance(version_id, str) or not re.fullmatch( + r"[A-Za-z0-9][A-Za-z0-9._+\-]*", version_id): + raise LoaderInstallError("Invalid loader version ID: {}".format(version_id)) + + validate_version_manifest(plan.version_manifest, version_id) + if plan.version_manifest.get("inheritsFrom") != minecraft_version or version_id == minecraft_version: + raise LoaderInstallError("Loader manifest does not inherit from the expected Minecraft version.") + + # Resolve Java using the combined vanilla and loader manifest. + update_stage("preparing Java runtime") + merged = merge_manifest(vanilla, plan.version_manifest) + runtime = self.java_mgr.ensure_runtime( + merged, auto_install=True, + progress_callback=progress_callback, + redownload_callback=self.redownload_files, + ) + + update_stage("downloading the Minecraft client") + if not check_core_file_exists_and_verify(vanilla, client_jar): + # Keep client progress and its original errors in this installation task. + download_core_file( + vanilla, client_jar, raise_for_null_hash=True, + progress_callback=progress_callback, + ) + + update_stage("copying embedded artifacts") + forge_like.copy_embedded_artifacts(plan, libraries_dir) + + update_stage("downloading installer dependencies") + files = forge_like.collect_install_dependencies(plan, libraries_dir) + failures, _ = download_multiple_files(files, progress_callback=progress_callback) + if failures: + success, failures = self.redownload_files(failures) + if not success or failures: + raise LoaderInstallError("Unable to download installer dependencies.") + + update_stage("running installer processors") + forge_like.run_processors( + plan, libraries_dir, java_path=runtime.executable, + minecraft_jar=client_jar, minecraft_root=root, + progress_callback=progress_callback, + ) + + update_stage("verifying installed artifacts") + if not forge_like.check_forge_dependencies(plan.version_manifest, libraries_dir): + raise LoaderInstallError("Installed artifacts failed verification.") + + manifest = plan.version_manifest + manifest["loader"] = loader_name + update_stage("cleaning installer workspace") + + # Publish only the verified loader manifest, including forgeInstall. + update_stage("saving the loader manifest") + validate_version_manifest(manifest, version_id) + destination = self.manifest_mgr.get_specific_version_manifest_path(version_id) + if destination is None: + raise LoaderInstallError("Unable to locate the manifest path for {}".format(version_id)) + + destination = Path(destination).resolve() + if not destination.is_relative_to(root / "versions"): + raise LoaderInstallError("Loader manifest path is outside the versions directory.") + + saved_manifest = save_version_manifest(manifest, destination) + self.manifest_mgr.backup_version_manifest(version_id) + except Exception as e: + message = "Unable to install {} {} for Minecraft {} while {}:\n{}".format( + loader_name, loader_version, minecraft_version, stage, e, + ) + self.app.logger.exception(message) + + if task_id is not None: + self.widget_mgr.download_signal.failed.emit(task_id, message) + + if error_callback is not None: + error_callback(stage, traceback.format_exc()) + else: + self.widget_mgr.signal.show_error_message.emit(message) + return None, None + else: + if task_id is not None: + self.widget_mgr.download_signal.finished.emit(task_id) + + return vanilla, saved_manifest + + @dataclass class LaunchResult: process: subprocess.Popen | None = None @@ -1066,7 +1311,7 @@ class LaunchManager: return result.fail("Unable to resolve the correct version id of the profile.") # Version manifest - resolved = self.manifest_mgr.resolve_manifest(version_id) + resolved = self.manifest_mgr.resolve_manifest(version_id, allow_rebuild=True) if resolved is None: return result.fail( @@ -1188,6 +1433,7 @@ class LaunchManager: launcher_name="TestLauncher", launcher_version=LAUNCHER_VERSION, classpath=classpath, + client_jar_name=core_file_path.name, classpath_separator=os.pathsep, library_directory=libraries_dir.as_posix(), resolution=profile.resolution @@ -1390,7 +1636,7 @@ class GameManager(QObject): self.widget_mgr = app.widget_manager self.manifest = ManifestManager(self.app) self.java = JavaManager(self.app) - self.game_file = GameFileManager(self.app, manifest_manager=self.manifest) + self.game_file = GameFileManager(self.app, manifest_manager=self.manifest, java_mgr=self.java) self.launch = LaunchManager(self.app, self.manifest, self.java, self.game_file, self.account_manager, self.profile_mgr) diff --git a/pages/add_modded_version.py b/pages/add_modded_version.py index 567d3d1..09617f3 100644 --- a/pages/add_modded_version.py +++ b/pages/add_modded_version.py @@ -1,28 +1,29 @@ import threading -from PySide6.QtCore import QObject, Signal +from PySide6.QtCore import QObject, Signal, QTimer from PySide6.QtWidgets import ( QComboBox, QDialog, QFormLayout, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, ) -from core_lib.game.mod import fabric +from core_lib.common.exception import LoaderUnsupportedSpecificVersion +from core_lib.game.mod import fabric, forge_like from core_lib.game.mod.mod_core import find_useful_part_in_mod_version_manifest from core_lib.game.version_info import get_available_version_types +from pages.loader_errors import format_unsupported_loader_version +from pages.forge_profile_install_dialog import ForgeProfileInstallDialog class AddModdedVersionDialog(QDialog): """ - Create a local mod-loader manifest without creating a profile. - - This dialog is vibed. + Install a local mod-loader version without creating a profile. """ version_created = Signal(str) class WorkerSignals(QObject): manifest_loaded = Signal(object, object) - loader_versions_loaded = Signal(str, object, object) + loader_versions_loaded = Signal(int, str, str, object, object) version_installed = Signal(object, object) def __init__(self, app, parent=None): @@ -30,6 +31,9 @@ class AddModdedVersionDialog(QDialog): self.app = app self.manifest_manager = app.game_manager.manifest self.root_manifest: dict = {} + self._loader_request_id = 0 + self._installing = False + self._installer_dialog: ForgeProfileInstallDialog | None = None self.worker_signals = self.WorkerSignals(self) self.setWindowTitle(self.app.tr_text("Add Modded Version")) @@ -42,7 +46,7 @@ class AddModdedVersionDialog(QDialog): title = QLabel(self.app.tr_text("Add Modded Version")) title.setObjectName("dialogTitle") description = QLabel(self.app.tr_text( - "Create a local mod-loader version manifest without creating a profile." + "Install a mod-loader version without creating a profile." )) description.setWordWrap(True) @@ -52,6 +56,8 @@ class AddModdedVersionDialog(QDialog): self.loader_dropdown = QComboBox() self.loader_dropdown.setObjectName("Dropdown") self.loader_dropdown.addItem(self.app.tr_text("Fabric"), "fabric") + self.loader_dropdown.addItem("Forge", "forge") + self.loader_dropdown.addItem("NeoForge", "neoforge") self.minecraft_type_dropdown = QComboBox() self.minecraft_type_dropdown.setObjectName("Dropdown") @@ -90,6 +96,7 @@ class AddModdedVersionDialog(QDialog): self.minecraft_version_dropdown.currentIndexChanged.connect( self._start_load_loader_versions ) + self.loader_dropdown.currentIndexChanged.connect(self._start_load_loader_versions) self.refresh_button.clicked.connect(self.load_versions) self.cancel_button.clicked.connect(self.reject) self.add_button.clicked.connect(self.install_selected_version) @@ -102,17 +109,21 @@ class AddModdedVersionDialog(QDialog): self.load_versions() - @staticmethod - def _error_text(error: Exception) -> str: + def _error_text(self, error: Exception) -> str: + if isinstance(error, LoaderUnsupportedSpecificVersion): + return format_unsupported_loader_version(error, self.app.tr_text) return str(getattr(error, "user_message", None) or error) def _set_loading(self, loading: bool, status: str = "") -> None: self.refresh_button.setEnabled(not loading) - self.add_button.setEnabled(not loading) + self.add_button.setEnabled(not loading and isinstance(self.loader_version_dropdown.currentData(), dict)) self.status_label.setText(status) def load_versions(self) -> None: + if self._installing: + return self._set_loading(True, self.app.tr_text("Loading Minecraft versions...")) + self.loader_dropdown.setEnabled(False) self.minecraft_type_dropdown.setEnabled(False) self.minecraft_version_dropdown.setEnabled(False) self.loader_version_dropdown.setEnabled(False) @@ -129,6 +140,7 @@ class AddModdedVersionDialog(QDialog): threading.Thread(target=worker, daemon=True).start() def _manifest_loaded(self, manifest, error) -> None: + self.loader_dropdown.setEnabled(True) if error is not None: self._set_loading(False, self.app.tr_text( "Unable to load versions: {error}", error=self._error_text(error) @@ -173,6 +185,12 @@ class AddModdedVersionDialog(QDialog): self._start_load_loader_versions() def _start_load_loader_versions(self, _index: int = -1) -> None: + if self._installing: + return + self._loader_request_id += 1 + request_id = self._loader_request_id + loader_name = self.loader_dropdown.currentData() + loader_label = self.loader_dropdown.currentText() minecraft_version = self.minecraft_version_dropdown.currentData() self.loader_version_dropdown.clear() self.loader_version_dropdown.setEnabled(False) @@ -182,32 +200,44 @@ class AddModdedVersionDialog(QDialog): return self._set_loading(True, self.app.tr_text( - "Loading Fabric versions for {version}...", version=minecraft_version + "Loading {loader} versions for {version}...", loader=loader_label, version=minecraft_version, )) def worker(): try: - loaders = fabric.get_version_support_loader_list(minecraft_version) + if loader_name == "fabric": + loaders = fabric.get_version_support_loader_list(minecraft_version) + else: + metadata_url = ( + forge_like.NEOFORGE_METADATA_URL if loader_name == "neoforge" + else forge_like.FORGE_METADATA_URL + ) + versions = forge_like.get_version_support_loader_list( + minecraft_version, forge_metadata_url=metadata_url, loader_name=loader_name, + ) + loaders = [{"version": version} for version in versions] self.worker_signals.loader_versions_loaded.emit( - minecraft_version, loaders, None + request_id, loader_name, minecraft_version, loaders, None, ) except Exception as error: self.worker_signals.loader_versions_loaded.emit( - minecraft_version, None, error + request_id, loader_name, minecraft_version, None, error, ) threading.Thread(target=worker, daemon=True).start() - def _loader_versions_loaded(self, minecraft_version, loaders, error) -> None: - # Ignore an obsolete response after the user selected another version. - if minecraft_version != self.minecraft_version_dropdown.currentData(): + def _loader_versions_loaded(self, request_id, loader_name, minecraft_version, loaders, error) -> None: + # Include the request ID: switching away and back can produce the same pair. + if (request_id != self._loader_request_id or loader_name != self.loader_dropdown.currentData() + or minecraft_version != self.minecraft_version_dropdown.currentData() or self._installing): return if error is not None: self._set_loading( False, self.app.tr_text( - "Unable to load Fabric versions: {error}", + "Unable to load {loader} versions: {error}", + loader=self.loader_dropdown.currentText(), error=self._error_text(error), ), ) @@ -226,9 +256,18 @@ class AddModdedVersionDialog(QDialog): self.loader_version_dropdown.setEnabled( self.loader_version_dropdown.count() > 0 ) + if self.loader_version_dropdown.count() == 0: + self._set_loading(False, self.app.tr_text( + "No {loader} versions are available for Minecraft {version}.", + loader=self.loader_dropdown.currentText(), version=minecraft_version, + )) + return self._set_loading(False, self.app.tr_text("Select a loader version to continue.")) def install_selected_version(self) -> None: + if self._installing: + return + loader_name = self.loader_dropdown.currentData() minecraft_version = self.minecraft_version_dropdown.currentData() loader_data = self.loader_version_dropdown.currentData() @@ -241,12 +280,27 @@ class AddModdedVersionDialog(QDialog): self.status_label.setText(self.app.tr_text("The selected loader version is invalid.")) return - self._set_loading(True, self.app.tr_text("Creating the Fabric version manifest...")) + self._installing = True + self.cancel_button.setEnabled(False) + self._set_loading(True, self.app.tr_text( + "Installing {loader}...", loader=self.loader_dropdown.currentText(), + )) self.loader_dropdown.setEnabled(False) self.minecraft_type_dropdown.setEnabled(False) self.minecraft_version_dropdown.setEnabled(False) self.loader_version_dropdown.setEnabled(False) + if loader_name in ("forge", "neoforge"): + dialog = ForgeProfileInstallDialog( + self.app, loader_name, minecraft_version, loader_version, parent=self, + ) + self._installer_dialog = dialog + dialog.completed.connect(self._forge_installation_completed) + dialog.version_installed.connect(self._forge_version_installed) + dialog.open() + QTimer.singleShot(0, dialog.start) + return + def worker(): try: # Cache the parent manifest as well, so the new modded version @@ -265,12 +319,11 @@ class AddModdedVersionDialog(QDialog): ) def fetch_manifest(_version_id: str): - return ( - fabric.get_loader_manifest_from_loader_data( - minecraft_version, loader_data - ), - None, + manifest = fabric.get_loader_manifest_from_loader_data( + minecraft_version, loader_data ) + manifest["loader"] = "fabric" + return manifest, None manifest = self.manifest_manager.get_cached_custom_version_manifest( version_id, @@ -298,6 +351,8 @@ class AddModdedVersionDialog(QDialog): threading.Thread(target=worker, daemon=True).start() def _version_installed(self, version_id, error) -> None: + self._installing = False + self.cancel_button.setEnabled(True) if error is not None: self.loader_dropdown.setEnabled(True) self.minecraft_type_dropdown.setEnabled(True) @@ -313,3 +368,23 @@ class AddModdedVersionDialog(QDialog): )) self.version_created.emit(version_id) self.accept() + + def _forge_installation_completed(self, success: bool) -> None: + if not success: + self._version_installed(None, RuntimeError(self.app.tr_text( + "Installation failed. Select a version to try again." + ))) + + def _forge_version_installed(self, version_id: str) -> None: + self._installer_dialog.accept() + self._version_installed(version_id, None) + + def reject(self): + if not self._installing: + super().reject() + + def closeEvent(self, event): + if self._installing: + event.ignore() + else: + super().closeEvent(event) diff --git a/pages/create_profile.py b/pages/create_profile.py index 0d41528..de68f0f 100644 --- a/pages/create_profile.py +++ b/pages/create_profile.py @@ -2,18 +2,23 @@ import threading from collections.abc import Callable from pathlib import Path -from PySide6.QtCore import QSize, Qt, QObject, Signal, Slot +from PySide6.QtCore import QSize, Qt, QObject, Signal, Slot, QTimer from PySide6.QtWidgets import QWidget, QVBoxLayout, QComboBox, QListWidget, QPushButton, QLabel, QHBoxLayout, \ QSizePolicy, QListWidgetItem, QInputDialog -from core_lib.common.exception import VersionManifestFetchException, VersionManifestException -from core_lib.game.mod import fabric +from core_lib.common.exception import ( + VersionManifestFetchException, VersionManifestException, LoaderUnsupportedSpecificVersion, +) +from core_lib.game.mod import fabric, forge_like 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 manager.game import ManifestManager, GameManager from manager.profile import CreateProfileRequest from manager.widgets import SignalTransferItem, WidgetManager from pages.install_java_dialog import InstallJavaDialog +from pages.forge_profile_install_dialog import ForgeProfileInstallDialog +from pages.loader_errors import format_unsupported_loader_version + class CreateProfilePage(QWidget): def __init__(self, app, parent=None): @@ -24,6 +29,7 @@ class CreateProfilePage(QWidget): self.widget_mgr: WidgetManager = app.widget_manager self.game_mgr: GameManager = app.game_manager self.manifest_mgr: ManifestManager = self.game_mgr.manifest + self._forge_install_dialog: ForgeProfileInstallDialog | None = None # Layout self.layout = QVBoxLayout() @@ -182,6 +188,12 @@ class CreateProfilePage(QWidget): "icon": Path(self.app.icon_dir, "modLoader", "neoforged.ico"), "loadVersionMethod": getattr(self, "load_neoforge_version_list", None), "profileCreateHandler": self.handle_neoforge_profile_create, + }, + "Forge": { + "type": "modded", + "icon": Path(self.app.icon_dir, "modLoader", "forge.png"), + "loadVersionMethod": getattr(self, "load_forge_version_list", None), + "profileCreateHandler": self.handle_forge_profile_create, } } self.init_all() @@ -201,7 +213,7 @@ class CreateProfilePage(QWidget): # Signal Handler # class UpdateListRequest(object): - def __init__(self, target_list: QListWidget | QComboBox, items: list[str], clean: bool=True, + def __init__(self, target_list: QListWidget | QComboBox, items: list[str], clean: bool = True, current_index: int | None = None, custom_handler: Callable = None, block_signals: bool = False, complete_callback: Callable = None): self.target_list = target_list @@ -301,7 +313,7 @@ class CreateProfilePage(QWidget): self.target_list = target_list class DisplayListItem(QListWidgetItem): - def __init__(self, parent: QListWidget=None, display_text: str=None, raw_value: str=None): + def __init__(self, parent: QListWidget = None, display_text: str = None, raw_value: str = None): QListWidgetItem.__init__(self, parent) self.display_text = display_text @@ -345,7 +357,6 @@ class CreateProfilePage(QWidget): if len(self.version_type_dropdown.currentText()) == 0: self.version_type_dropdown.setCurrentIndex(0) - def update_version_list(self, request: UpdateListRequest): version_list = request.target_list @@ -353,16 +364,20 @@ class CreateProfilePage(QWidget): raise TypeError("Target list is not a QListWidget or QComboBox") for version in request.items: - ver_id = version.get("id", None) or version.get("version", None) - stable = version.get("stable", None) + if isinstance(version, dict): + ver_id = version.get("id", None) or version.get("version", None) + stable = version.get("stable", None) - if not ver_id: - self.app.logger.warning("Provided version {} missing ID.".format(version)) + if not ver_id: + self.app.logger.warning("Provided version {} missing ID.".format(version)) + else: + ver_id = version + stable = None display_text = ver_id if stable is not None and isinstance(stable, bool): - display_text = f"{ver_id}"+(" (stable)" if stable else "") + display_text = f"{ver_id}" + (" (stable)" if stable else "") item = self.DisplayListItem( parent=request.target_list, @@ -490,7 +505,8 @@ class CreateProfilePage(QWidget): if callable(profile_create_handler): profile_create_handler(profile_name, minecraft_version, loader_version) - def handle_vanilla_profile_create(self, profile_name: str, version: str, loader_version: None=None, switch_to_current=False): + def handle_vanilla_profile_create(self, profile_name: str, version: str, loader_version: None = None, + switch_to_current=False): """ Handle vanilla profile creation. :param profile_name: @@ -539,7 +555,8 @@ class CreateProfilePage(QWidget): self.app.tr_text("Profile {profile_id} successfully created.", profile_id=profile_id), ) - def handle_fabric_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None, switch_to_current=False): + def handle_fabric_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None, + switch_to_current=False): """ Handle fabric profile creation. :param profile_name: @@ -571,10 +588,11 @@ class CreateProfilePage(QWidget): minecraft_version, {"version": loader_version}, ) + manifest["loader"] = "fabric" return manifest, None loader_manifest = self.manifest_mgr.get_cached_custom_version_manifest( - version_id, fetch_manifest_handler=fetch_loader_manifest,) + version_id, fetch_manifest_handler=fetch_loader_manifest, ) if not loader_manifest: self.widget_mgr.signal.show_error_message.emit( @@ -628,18 +646,58 @@ class CreateProfilePage(QWidget): ), ) + def handle_forge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None, + switch_to_current=False): + """ + Handle forge profile creation. + :param profile_name: + :param minecraft_version: + :param loader_version: + :param switch_to_current: + :return: + """ + self._start_forge_like_profile_create( + "forge", profile_name, minecraft_version, loader_version, switch_to_current, + ) - def handle_forge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None): - if not loader_version: - self.widget_mgr.signal.show_warning_message.emit( - self.app.tr_text("Selected a forge loader version before creating profile."), - ) + def handle_neoforge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None, + switch_to_current=False): + """ + Handle neoforge profile creation. + :param profile_name: + :param minecraft_version: + :param loader_version: + :param switch_to_current: + :return: + """ + self._start_forge_like_profile_create( + "neoforge", profile_name, minecraft_version, loader_version, switch_to_current, + ) - def handle_neoforge_profile_create(self, profile_name: str, minecraft_version: str, loader_version: str | None): + def _start_forge_like_profile_create(self, loader_name: str, profile_name: str, + minecraft_version: str, loader_version: str | None, + switch_to_current: bool = False): if not loader_version: - self.widget_mgr.signal.show_warning_message.emit( - self.app.tr_text("Selected a neoforge loader version before creating profile."), - ) + self.widget_mgr.signal.show_warning_message.emit(self.app.tr_text( + "Select a {loader} version before creating a profile.", + loader="NeoForge" if loader_name == "neoforge" else "Forge", + )) + return + + if self._forge_install_dialog is not None and self._forge_install_dialog.is_running: + self._forge_install_dialog.raise_() + self._forge_install_dialog.activateWindow() + return + + dialog = ForgeProfileInstallDialog( + self.app, loader_name, minecraft_version, loader_version, + profile_name, switch_to_current=switch_to_current, parent=self, + ) + self._forge_install_dialog = dialog + self.create_profile_button.setEnabled(False) + dialog.completed.connect(lambda _success: self.create_profile_button.setEnabled(True)) + dialog.open() + QTimer.singleShot(0, dialog.start) # # Background Thread @@ -734,6 +792,117 @@ class CreateProfilePage(QWidget): loaders = fabric.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): + 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."), + ) + + selected_version = request.result() + + if not selected_version: + self.widget_mgr.signal.show_warning_message.emit( + self.app.tr_text("No version selected."), + ) + + try: + loaders = forge_like.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_neoforge_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."), + ) + + selected_version = request.result() + + if not selected_version: + self.widget_mgr.signal.show_warning_message.emit( + self.app.tr_text("No version selected."), + ) + + try: + loaders = forge_like.get_version_support_loader_list( + selected_version, + forge_metadata_url=forge_like.NEOFORGE_METADATA_URL, + loader_name="neoforge", + ) + 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( diff --git a/pages/forge_profile_install_dialog.py b/pages/forge_profile_install_dialog.py new file mode 100644 index 0000000..89b1b2a --- /dev/null +++ b/pages/forge_profile_install_dialog.py @@ -0,0 +1,217 @@ +import math +import threading +import traceback + +from PySide6.QtCore import QObject, Qt, Signal, Slot +from PySide6.QtWidgets import ( + QDialog, QLabel, QPlainTextEdit, QProgressBar, QPushButton, QVBoxLayout, +) + +from manager.profile import CreateProfileRequest + + +INSTALL_STAGES = { + "validating installation request": "Validating installation request...", + "loading the vanilla manifest": "Loading Minecraft version information...", + "preparing the installer": "Downloading and preparing the loader installer...", + "preparing Java runtime": "Preparing the required Java runtime...", + "downloading the Minecraft client": "Checking and downloading the Minecraft client...", + "copying embedded artifacts": "Installing bundled libraries...", + "downloading installer dependencies": "Downloading required libraries...", + "running installer processors": "Applying loader patches...", + "verifying installed artifacts": "Verifying the installed files...", + "cleaning installer workspace": "Cleaning up temporary installer files...", + "saving the loader manifest": "Saving the installed version...", + "creating the profile": "Creating the launch profile...", +} + + +class ForgeProfileInstallDialog(QDialog): + """Show loader installation progress and optionally create a launch profile.""" + + completed = Signal(bool) + version_installed = Signal(str) + + class WorkerSignals(QObject): + stage = Signal(str) + progress = Signal(str, float) + failed = Signal(str, str) + installed = Signal(object, object) + + 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): + super().__init__(parent) + self.app = app + self.loader_name = loader_name + self.minecraft_version = minecraft_version + self.loader_version = loader_version + self.profile_name = profile_name + self.switch_to_current = switch_to_current + self.is_running = True + self._started = False + self.worker_signals = self.WorkerSignals(self) + self.worker_signals.stage.connect(self._stage_changed) + self.worker_signals.progress.connect(self._progress_changed) + self.worker_signals.failed.connect(self._failed) + self.worker_signals.installed.connect(self._installed) + + loader = "NeoForge" if loader_name == "neoforge" else "Forge" + self.setWindowTitle(app.tr_text("Install {loader}", loader=loader)) + self.setWindowModality(Qt.WindowModality.WindowModal) + self.setMinimumWidth(600) + layout = QVBoxLayout(self) + self.summary_label = QLabel(app.tr_text( + "Installing {loader} {loader_version} for Minecraft {minecraft_version}", + loader=loader, loader_version=loader_version, minecraft_version=minecraft_version, + )) + self.status_label = QLabel(app.tr_text("Waiting to start installation...")) + self.item_label = QLabel() + for label in (self.summary_label, self.status_label, self.item_label): + label.setTextFormat(Qt.TextFormat.PlainText) + label.setWordWrap(True) + self.progress_bar = QProgressBar() + self.progress_bar.setFormat(app.tr_text("Stage progress: %p%")) + self.progress_bar.setRange(0, 0) + self.details_label = QLabel(app.tr_text("Installation details")) + self.details = QPlainTextEdit() + self.details.setReadOnly(True) + self.details.setMinimumHeight(180) + self.close_button = QPushButton(app.tr_text("Close")) + self.close_button.setEnabled(False) + self.close_button.clicked.connect(self.accept) + for widget in (self.summary_label, self.status_label, self.item_label, self.progress_bar, + self.details_label, self.details, self.close_button): + layout.addWidget(widget) + + def start(self): + if self._started: + return + self._started = True + + def worker(): + reported_error = False + + def failed(stage, details): + nonlocal reported_error + reported_error = True + self.worker_signals.failed.emit(stage, details) + + try: + vanilla, manifest = self.app.game_manager.game_file.install_forge_like_version( + loader_name=self.loader_name, + minecraft_version=self.minecraft_version, + loader_version=self.loader_version, + progress_callback=self.worker_signals.progress.emit, + status_callback=self.worker_signals.stage.emit, + error_callback=failed, + ) + if reported_error: + return + if not vanilla or not manifest: + self.worker_signals.failed.emit( + "", self.app.tr_text("The installer did not return an installed version."), + ) + return + self.worker_signals.installed.emit(vanilla, manifest) + except Exception: + self.app.logger.exception("Loader installation failed") + self.worker_signals.failed.emit("", traceback.format_exc()) + + self.worker = threading.Thread(target=worker, daemon=True) + self.worker.start() + + @Slot(str) + def _stage_changed(self, stage: str): + if not self.is_running: + return + text = self.app.tr_text(INSTALL_STAGES.get(stage, stage)) + self.status_label.setText(text) + self.item_label.clear() + self.progress_bar.setRange(0, 0) + self.details.appendPlainText(text) + + @Slot(str, float) + def _progress_changed(self, name: str, percent: float): + if not self.is_running or not math.isfinite(percent): + return + self.item_label.setText(self.app.tr_text("Current item: {item}", item=name)) + self.progress_bar.setRange(0, 100) + self.progress_bar.setValue(round(max(0, min(100, percent)))) + + @Slot(str, str) + def _failed(self, stage: str, details: str): + if not self.is_running: + return + if stage: + text = self.app.tr_text( + "Installation failed while: {stage}", + stage=self.app.tr_text(INSTALL_STAGES.get(stage, stage)), + ) + else: + text = self.app.tr_text("Installation failed. See the details below.") + self.status_label.setText(text) + self.details.appendPlainText(text) + self.details.appendPlainText(details) + self.progress_bar.setRange(0, 100) + self._finish(False) + + @Slot(object, object) + def _installed(self, vanilla: dict, manifest: dict): + if not self.is_running: + return + stage = "creating the profile" if self.profile_name is not None else "saving the loader manifest" + try: + version_id = manifest.get("id") + if not isinstance(version_id, str) or not version_id: + raise ValueError(self.app.tr_text("The installed version has no version ID.")) + if self.profile_name is None: + self._show_success(self.app.tr_text("Added version {version_id}.", version_id=version_id)) + self.version_installed.emit(version_id) + return + self._stage_changed("creating the profile") + request = CreateProfileRequest( + name=self.profile_name, version_id=version_id, + version_type=manifest.get("type") or vanilla.get("type") or "custom", + ) + profile_id = self.app.profile_manager.create_profile(request) + if profile_id is None: + raise RuntimeError(self.app.tr_text( + "The loader was installed, but the profile could not be created." + )) + if self.switch_to_current and not self.app.profile_manager.set_current_profile(profile_id): + raise RuntimeError(self.app.tr_text( + "The profile was created, but could not be selected." + )) + except Exception: + self.app.logger.exception("Unable to create profile after loader installation") + self._failed(stage, traceback.format_exc()) + return + text = self.app.tr_text("Profile {profile_id} successfully created.", profile_id=profile_id) + self._show_success(text) + + def _show_success(self, text: str): + self.status_label.setText(text) + self.item_label.clear() + self.progress_bar.setRange(0, 100) + self.progress_bar.setValue(100) + self.details.appendPlainText(text) + self._finish(True) + + def _finish(self, success: bool): + self.is_running = False + self.close_button.setEnabled(True) + self.completed.emit(success) + + def accept(self): + if not self.is_running: + super().accept() + + def reject(self): + if not self.is_running: + super().reject() + + def closeEvent(self, event): + if self.is_running: + event.ignore() + else: + super().closeEvent(event) diff --git a/pages/loader_errors.py b/pages/loader_errors.py new file mode 100644 index 0000000..02ef4a7 --- /dev/null +++ b/pages/loader_errors.py @@ -0,0 +1,17 @@ +"""Presentation of structured loader errors shared by loader selection views.""" + +from collections.abc import Callable + +from core_lib.common.exception import LoaderUnsupportedSpecificVersion + + +def format_unsupported_loader_version( + error: LoaderUnsupportedSpecificVersion, translate: Callable[..., str], +) -> str: + loader = { + "fabric": "Fabric", "forge": "Forge", "neoforge": "NeoForge", + }.get(error.loader_name, error.loader_name) + return translate( + "{loader} does not support Minecraft {version}.", + loader=loader, version=error.target_version, + ) diff --git a/resources/builtin_plugins/forge_test/__init__.py b/resources/builtin_plugins/forge_test/__init__.py new file mode 100644 index 0000000..0f8986b --- /dev/null +++ b/resources/builtin_plugins/forge_test/__init__.py @@ -0,0 +1,11 @@ +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") diff --git a/resources/builtin_plugins/forge_test/neoforged.ico b/resources/builtin_plugins/forge_test/neoforged.ico new file mode 100644 index 0000000000000000000000000000000000000000..3e78a3f6c0ffc9819da57e21bedda0e9f43f7ebd GIT binary patch literal 67646 zcmeI*zprIu6vpwR(+h=4C8AM~_$z4q1sc&xs7>!jjO=0FZ{D@ndY-l3ea@Y8uhZ#~d;i?IbGrBYQ>SMhedP4S>2!ML z-gR$jE&jc}{xiR#Kop1qQ6LILfhf=^aObVJwp_PggU;uQ$NSsw{qnH#w_A_@@jpFq z`+K09^NPp&+wXnO|LgE@&n#B+-L3DrXZAigeJ7vg(-)tAwpG`spM1DgSG6bWwVwY) zn@aDsuKn^@OfjdqC}x=ZW2(747Ly;-Tof}b{-+1(9+=LYW?W2OOmk7pu-f~j%~W%F zEG9puxhQ5>{7(t1_uo$j4#u6<(4bGlD4_ptbX{`3Ft-LJOl+T)e>PJR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