diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..101f8c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/reference/ +/build/ diff --git a/constant.py b/constant.py index ea0d242..88e6403 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.1.1-alpha" +LAUNCHER_VERSION = "0.1.2-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 4a41992..3c5b10f 100644 --- a/core_lib/__init__.py +++ b/core_lib/__init__.py @@ -1,4 +1,4 @@ -__version__ = '0.1.4' +__version__ = '0.1.5' __description__ = """ The core library of the *Launcher* diff --git a/core_lib/game/library.py b/core_lib/game/library.py index 7064c37..c0e3813 100644 --- a/core_lib/game/library.py +++ b/core_lib/game/library.py @@ -140,6 +140,20 @@ def is_library_allowed(rules, platform_rule_name, platform_arch_type, platform_v return allowed +def filter_platform_libraries(libraries: list[dict]) -> list[dict]: + _, _, os_version = get_platform_info() + _, platform_rule_name, platform_arch_type = get_natives_platform_info() + + return [ + library + for library in libraries + if is_library_allowed( + library.get("rules") or [], + platform_rule_name, + platform_arch_type, + os_version, + ) + ] def get_natives_platform_info(): """ @@ -277,7 +291,8 @@ def is_legacy_native_allowed(natives, classifiers, platform_rule_name, platform_ return False, None, None -def generate_relative_path_by_maven_coordinate(maven_coordinate: str, extra=None) -> str | None: +def generate_relative_path_by_maven_coordinate(maven_coordinate: str, extra=None, + extension: str = "jar") -> str | None: parts = maven_coordinate.split(":") if len(parts) not in (3, 4): @@ -293,7 +308,7 @@ def generate_relative_path_by_maven_coordinate(maven_coordinate: str, extra=None if classifier: filename += f"-{classifier}" - return f"{base_path}/{artifact}/{version}/{filename}.jar" + return f"{base_path}/{artifact}/{version}/{filename}.{extension}" def remove_duplicate_artifacts(artifacts: list[dict], ignore_null=False, compare_by_name=False) -> list[dict]: diff --git a/core_lib/game/libraryx.py b/core_lib/game/libraryx.py index 559a55b..54dabbd 100644 --- a/core_lib/game/libraryx.py +++ b/core_lib/game/libraryx.py @@ -1,12 +1,14 @@ """ -This module provide some advanced function for library parse/download process use. +This module provides some advanced function for library parse/download process use. """ import logging import re from copy import deepcopy +from enum import StrEnum -from .library import (convert_maven_version, parse_maven_coordinate, generate_relative_path_by_maven_coordinate, - is_complete_maven_url, generate_repo_url) +from .library import (convert_maven_version, parse_maven_coordinate, is_complete_maven_url, + generate_repo_url, generate_filename_from_maven_coordinate, + generate_repo_path) from .version_info import MOJANG_LIBRARIES_ENDPOINT from ..common.exception import VersionDataKeyNotFoundException, DependencyException @@ -46,16 +48,18 @@ def generate_unique_library_key(group: str, artifact: str, classifier: str | Non return key -def normalize_library_to_common_struct(library: dict, default_maven_url: str = MOJANG_LIBRARIES_ENDPOINT) -> dict: +def normalize_library_to_common_struct(library: dict, default_maven_url: str | None = MOJANG_LIBRARIES_ENDPOINT, + default_extension: str = "jar") -> dict: result = deepcopy(library) - name: str = library.get("name") + name: str | None = library.get("name") if name is None: raise VersionDataKeyNotFoundException( "Provided mod loader version manifest library does not contain key \"name\"." ) - group, artifact, version, classifier, extension = parse_maven_coordinate(name) + group, artifact, version, classifier, extension = parse_maven_coordinate(name, + default_extension=default_extension) downloads_raw = result.setdefault("downloads", {}) @@ -68,15 +72,21 @@ def normalize_library_to_common_struct(library: dict, default_maven_url: str = M # Generate new relative path and put back if not artifact_raw.get("path"): - path = generate_relative_path_by_maven_coordinate(name) - if not path: - raise DependencyException( - f"Unable to generate artifact path for {name}" - ) - artifact_raw["path"] = path + filename = generate_filename_from_maven_coordinate( + artifact, + version, + classifier=classifier, + extension=extension, + ) + artifact_raw["path"] = generate_repo_path( + group, + artifact, + version, + filename, + ) if not artifact_raw.get("url"): - top_level_url = result.get("url") + top_level_url: str | None = result.get("url") if top_level_url: if is_complete_maven_url( @@ -100,6 +110,11 @@ def normalize_library_to_common_struct(library: dict, default_maven_url: str = M extension, ) else: + if not default_maven_url: + raise DependencyException( + f"No download source for library {name!r}." + ) + # Generate missing url artifact_raw["url"] = generate_repo_url( default_maven_url, @@ -128,3 +143,92 @@ def normalize_library_to_common_struct(library: dict, default_maven_url: str = M result["downloads"] = downloads return result + +class LibraryPreference(StrEnum): + HIGHER_VERSION = "higher_version" + LOWER_VERSION = "lower_version" + MOD_LIBRARY = "mod_library" + INHERITS_LIBRARY = "inherits_library" + + +PREFER_BY_HIGHER_VERSION = LibraryPreference.HIGHER_VERSION +PREFER_BY_LOWER_VERSION = LibraryPreference.LOWER_VERSION +PREFER_MOD_LIBRARY = LibraryPreference.MOD_LIBRARY +PREFER_INHERITS_LIBRARY = LibraryPreference.INHERITS_LIBRARY + +LIBRARY_PREFER_OPTIONS = (PREFER_BY_HIGHER_VERSION, PREFER_BY_LOWER_VERSION, PREFER_MOD_LIBRARY, PREFER_INHERITS_LIBRARY,) + + +def compare_library_versions(left: str, right: str) -> int: + """ + Compare two library version string. + :param left: + :param right: + :return: + result: -1 if left < right, 0 if left == right, 1 if left > right. If parse failed, throw DependencyException. + """ + if left == right: + return 0 + + numeric_version = r"[0-9]+(?:\.[0-9]+)*" + + if not (re.fullmatch(numeric_version, left) and re.fullmatch(numeric_version, right)): + raise DependencyException(f"Cannot compare library versions {left!r} and {right!r}." + f" Use PREFER_MOD_LIBRARY or PREFER_INHERITS_LIBRARY may solve this issue.") + + left_parts = tuple(map(int, left.split("."))) + right_parts = tuple(map(int, right.split("."))) + + length = max(len(left_parts), len(right_parts)) + left_parts += (0,) * (length - len(left_parts)) + right_parts += (0,) * (length - len(right_parts)) + + return (left_parts > right_parts) - (left_parts < right_parts) + +def deduplicate_libraries(libraries: list[dict], preference: LibraryPreference, + default_extension: str = "jar") -> list[dict]: + indexed = {} + + preference = LibraryPreference(preference) + + for library in libraries: + name: str | None = library.get("name") + if not name: + raise DependencyException("Library is missing its name.") + + group, artifact, version, classifier, extension = parse_maven_coordinate(name, + default_extension=default_extension) + key = generate_unique_library_key( + group=group, + artifact=artifact, + classifier=classifier, + extension=extension, + ) + + previous = indexed.get(key) + + if previous is not None: + logger.warning( + "Duplicate library: %s / %s", + previous["name"], + name, + ) + + # Skip/Replace library depend by the library preference + if preference in (PREFER_BY_HIGHER_VERSION, PREFER_BY_LOWER_VERSION,): + previous_version = parse_maven_coordinate(previous["name"], default_extension=default_extension)[2] + + comparison = compare_library_versions(previous_version, version,) + + keep_previous = ( + comparison > 0 + if preference == PREFER_BY_HIGHER_VERSION + else comparison < 0 + ) + + if keep_previous: + continue + + indexed[key] = library + + return list(indexed.values()) \ No newline at end of file diff --git a/core_lib/game/mod/mod_core.py b/core_lib/game/mod/mod_core.py index f9a6897..bcc51ac 100644 --- a/core_lib/game/mod/mod_core.py +++ b/core_lib/game/mod/mod_core.py @@ -4,13 +4,45 @@ import shlex from core_lib.common.exception import VersionDataKeyNotFoundException, DependencyException from core_lib.game.library import parse_maven_coordinate, generate_repo_url, \ - is_complete_maven_url + is_complete_maven_url, filter_platform_libraries from core_lib.game.libraryx import convert_maven_version_with_extra, generate_unique_library_key, \ - normalize_library_to_common_struct + normalize_library_to_common_struct, compare_library_versions, LibraryPreference, PREFER_MOD_LIBRARY, \ + PREFER_INHERITS_LIBRARY, PREFER_BY_HIGHER_VERSION, deduplicate_libraries from core_lib.game.version_info import MOJANG_LIBRARIES_ENDPOINT logger = logging.getLogger("Launcher.CoreLib") +LOADER_LIBRARY_MARKERS = { + ("net.fabricmc", "fabric-loader"): "fabric", + ("org.quiltmc", "quilt-loader"): "quilt", + ("net.minecraftforge", "forge"): "forge", + ("net.neoforged", "neoforge"): "neoforge", + ("net.neoforged", "forge"): "neoforge", +} + + +def detect_loader_name(manifest: dict) -> str | None: + candidates = set() + + for library in manifest.get("libraries", []): + name = library.get("name", "") + parts = name.split(":") + + 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)) + def find_useful_part_in_mod_version_manifest(mod_version_manifest: dict): ver_id = mod_version_manifest.get("id", None) inherits_from = mod_version_manifest.get("inheritsFrom", None) @@ -61,8 +93,9 @@ def find_useful_part_in_mod_version_manifest(mod_version_manifest: dict): } -def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, mod_maven_url=None, - inherits_maven_url=MOJANG_LIBRARIES_ENDPOINT, default_extension="jar") -> list[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]: inherits = {} result_pre = [] @@ -72,43 +105,70 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, inherits_libraries = deepcopy(inherits_libraries) mod_libraries = deepcopy(mod_libraries) - def check_lib(lib: dict): - url: str = lib.get("url", "") - source_from = lib["sourceFrom"] - lib_group=lib["parsed"]["group"] - lib_artifact=lib["parsed"]["artifact"] - lib_version=lib["parsed"]["versionRaw"] - lib_classifier=lib["parsed"]["classifier"] - lib_extension=lib["parsed"]["extension"] + # Filter platform (natives) libraries + inherits_libraries = filter_platform_libraries(inherits_libraries) + mod_libraries = filter_platform_libraries(mod_libraries) - recreated = False + preference = LibraryPreference(prefer_libraries_by) - if not url: - if source_from == "official": - new_url = generate_repo_url(inherits_maven_url, lib_group, lib_artifact, lib_version, lib_classifier, - lib_extension) - else: - new_url = generate_repo_url(mod_maven_url, lib_group, lib_artifact, lib_version, lib_classifier, - lib_extension) + # Remove duplicate libraries + inherits_libraries = deduplicate_libraries( + inherits_libraries, + preference, + default_extension, + ) + mod_libraries = deduplicate_libraries( + mod_libraries, + preference, + default_extension, + ) - lib["url"] = new_url - - recreated = True - - if not recreated: - url_result = is_complete_maven_url(url, lib_group, lib_artifact, lib_version, lib_classifier, lib_extension) - - if not url_result: - # deal with some weird maven url that don't contain repo path - # Some mod loader (such as fabric), did not contain a full path inside the library. We will need to - # generate it from maven coordinate (aka lib_name) - target_maven = mod_maven_url or url - repo_url = generate_repo_url(target_maven, lib_group, lib_artifact, lib_version, lib_classifier, - lib_extension) - lib["url"] = repo_url + # def check_lib(lib: dict): + # url: str = lib.get("url", "") + # source_from = lib["sourceFrom"] + # lib_group=lib["parsed"]["group"] + # lib_artifact=lib["parsed"]["artifact"] + # lib_version=lib["parsed"]["versionRaw"] + # lib_classifier=lib["parsed"]["classifier"] + # lib_extension=lib["parsed"]["extension"] + # lib_downloads = lib["downloads"] + # + # recreated = False + # + # if not url: + # artifact_url = lib_downloads.get("artifact", {}).get("url", "") + # is_completed = is_complete_maven_url(artifact_url, lib_group, lib_artifact, lib_version, lib_classifier, lib_extension) + # + # if is_completed: + # lib["url"] = artifact_url + # else: + # if source_from == "official": + # new_url = generate_repo_url(inherits_maven_url, lib_group, lib_artifact, lib_version, + # lib_classifier, + # lib_extension) + # else: + # new_url = generate_repo_url(mod_maven_url, lib_group, lib_artifact, lib_version, lib_classifier, + # lib_extension) + # + # lib["url"] = new_url + # + # recreated = True + # + # if not recreated: + # url_result = is_complete_maven_url(url, lib_group, lib_artifact, lib_version, lib_classifier, lib_extension) + # + # if not url_result: + # # deal with some weird maven url that don't contain srepo path + # # Some mod loader (such as fabric), did not contain a full path inside the library. We will need to + # # generate it from maven coordinate (aka lib_name) + # target_maven = url or mod_maven_url + # repo_url = generate_repo_url(target_maven, lib_group, lib_artifact, lib_version, lib_classifier, + # lib_extension) + # lib["url"] = repo_url for library in inherits_libraries: - name = library.get("name", None) + name: str | None = library.get("name", None) + downloads = library.get("downloads", {}) if not name: raise DependencyException( @@ -116,15 +176,16 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, ) group, artifact, version_raw, classifier, extension = parse_maven_coordinate(name, default_extension=default_extension) - ver_converted, extra = convert_maven_version_with_extra(version_raw) - if extra: - logger.debug("Found extra version \"{}\" for library {}".format(extra, name)) - - if not ver_converted: - raise DependencyException( - f"Unable to convert provided inherited library name {name}'s version {version_raw} to tuple." - ) + # ver_converted, extra = convert_maven_version_with_extra(version_raw) + # + # if extra: + # logger.debug("Found extra version \"{}\" for library {}".format(extra, name)) + # + # if not ver_converted: + # raise DependencyException( + # f"Unable to convert provided inherited library name {name}'s version {version_raw} to tuple." + # ) lib_key = generate_unique_library_key( group=group, @@ -139,12 +200,12 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, inherits[lib_key]["parsed"] = { "group": group, "artifact": artifact, - "version": ver_converted, + "version": version_raw, "versionRaw": version_raw, - "versionExtra": extra, "classifier": classifier, "extension": extension, - "endpoint": inherits_maven_url + "endpoint": inherits_maven_url, + "downloads": downloads, } inherits[lib_key]["sourceFrom"] = "official" else: @@ -152,23 +213,22 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, for mod_library in mod_libraries: name = mod_library.get("name", None) + downloads = mod_library.get("downloads", {}) if not name: raise DependencyException( "Provided mod library does not contain key \"name\"." ) - group, artifact, version_raw, classifier, extension = parse_maven_coordinate(name, default_extension=default_extension) - - ver_converted, extra = convert_maven_version_with_extra(version_raw) - - if extra: - logger.debug("Found extra version \"{}\" for library {}".format(extra, name)) - - if ver_converted is None: - raise DependencyException( - "Unable to convert mod library version {} to tuple".format(version_raw), - ) + # ver_converted, extra = convert_maven_version_with_extra(version_raw) + # + # if extra: + # logger.debug("Found extra version \"{}\" for library {}".format(extra, name)) + # + # if ver_converted is None: + # raise DependencyException( + # "Unable to convert mod library version {} to tuple".format(version_raw), + # ) group, artifact, version_raw, classifier, extension = parse_maven_coordinate(name, default_extension=default_extension) lib_key = generate_unique_library_key( @@ -183,34 +243,37 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, "group": group, "artifact": artifact, # "version": {"raw": version, "converted": ver_converted, "extra": extra}, - "version": ver_converted, + "version": version_raw, "versionRaw": version_raw, - "versionExtra": extra, "classifier": classifier, "extension": extension, "endpoint": mod_maven_url, + "downloads": downloads, } if lib_key in inherits: found_lib = inherits.pop(lib_key) found_lib_ver = found_lib["parsed"]["version"] - found_lib_ver_extra = found_lib["parsed"]["versionExtra"] if found_lib_ver is None: raise DependencyException( "Unable to convert mod library version {} to tuple".format(found_lib["versionRaw"]) ) - if found_lib_ver > ver_converted: - result_pre.append(found_lib) - elif found_lib_ver < ver_converted: - result_pre.append(mod_library) + if preference in (PREFER_MOD_LIBRARY, PREFER_INHERITS_LIBRARY,): + selected = mod_library if preference == PREFER_MOD_LIBRARY else found_lib else: - # Use mod loader library if extra version is existing - if found_lib_ver_extra == mod_library["parsed"]["versionExtra"]: - result_pre.append(found_lib) - else: - result_pre.append(mod_library) + comparison = compare_library_versions( + found_lib["parsed"]["versionRaw"], + mod_library["parsed"]["versionRaw"], + ) + + if preference == PREFER_BY_HIGHER_VERSION: + selected = found_lib if comparison > 0 else mod_library + else: # PREFER_BY_LOWER_VERSION + selected = found_lib if comparison < 0 else mod_library + + result_pre.append(selected) else: result_pre.append(mod_library) @@ -220,13 +283,24 @@ def merge_necessary_dependencies(inherits_libraries: list, mod_libraries: list, result_pre.append(value) for library in result_pre: - # Cleanup - check_lib(library) - library_normalized = normalize_library_to_common_struct(library, default_maven_url=library["parsed"]["endpoint"]) + # Check library download url + endpoint = library["parsed"]["endpoint"] # maven url + artifact_url = ((library.get("downloads") or {}).get("artifact") or {}).get("url") + if not artifact_url and not library.get("url") and not endpoint: + raise DependencyException( + f"No download source for library {library['name']!r}." + ) + + library_normalized = normalize_library_to_common_struct( + library, + default_maven_url=endpoint, + default_extension=default_extension + ) + + # Cleanup and append library_normalized.pop("parsed", None) library_normalized.pop("sourceFrom", None) - library_normalized.pop("endpoint", None) result.append(library_normalized) return result @@ -262,7 +336,8 @@ def merge_game_and_jvm_args(inherits_args: dict[str, list[str]] | str, mod_args: return merged -def merge_manifest(inherits_version_manifest: dict, mod_version_manifest: dict, mod_maven_url=None) -> dict: +def merge_manifest(inherits_version_manifest: dict, mod_version_manifest: dict, mod_maven_url=None, + *, prefer_libraries_by: LibraryPreference = PREFER_MOD_LIBRARY) -> dict: merged_manifest = deepcopy(inherits_version_manifest) # main class @@ -281,8 +356,12 @@ def merge_manifest(inherits_version_manifest: dict, mod_version_manifest: dict, "Inherited (or mod) version manifest does not contain key \"libraries\"." ) - merged_manifest["libraries"] = merge_necessary_dependencies(inherits_libraries, mod_libraries, - mod_maven_url=mod_maven_url) + merged_manifest["libraries"] = merge_necessary_dependencies( + inherits_libraries, + mod_libraries, + mod_maven_url=mod_maven_url, + prefer_libraries_by=prefer_libraries_by + ) # arguments inherits_arguments = inherits_version_manifest.get("arguments", []) or inherits_version_manifest.get("minecraftArguments", "") diff --git a/core_lib/game/mod/rules.py b/core_lib/game/mod/rules.py new file mode 100644 index 0000000..1897092 --- /dev/null +++ b/core_lib/game/mod/rules.py @@ -0,0 +1,16 @@ +from core_lib.game.mod.mod_core import PREFER_MOD_LIBRARY + +MOD_LOADER_RULES = { + "fabric": { + "preferLibraryBy": PREFER_MOD_LIBRARY, + }, + "forge": { + "preferLibraryBy": PREFER_MOD_LIBRARY, + }, + "neoforge": { + "preferLibraryBy": PREFER_MOD_LIBRARY, + }, + "quilt": { + "preferLibraryBy": PREFER_MOD_LIBRARY, + } +} \ No newline at end of file diff --git a/core_lib/runtime/mojang.py b/core_lib/runtime/mojang.py index 59f3e9e..731cbc2 100644 --- a/core_lib/runtime/mojang.py +++ b/core_lib/runtime/mojang.py @@ -12,7 +12,7 @@ import requests from ..common.common import get_platform_info, FileObject, download_multiple_files from ..common.exception import RuntimeManifestFetchException, UnsupportedPlatformException, \ - RuntimeManifestDataException, HashMismatchException, DownloadException, LauncherException + RuntimeManifestDataException, DownloadException, LauncherException from ..game.version_info import RUNTIME_PLATFORM_MAP, RUNTIME_ARCH_EMPTY, RUNTIME_ARCH_MAP MOJANG_RUNTIME_MANIFEST = "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json" diff --git a/manager/game.py b/manager/game.py index e9ddbf0..062fa19 100644 --- a/manager/game.py +++ b/manager/game.py @@ -8,7 +8,7 @@ import threading import time import traceback from collections.abc import Callable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from threading import Thread from typing import Literal @@ -21,7 +21,8 @@ from core_lib.common.exception import JavaRuntimeException 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.mod_core import merge_manifest +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 @@ -230,7 +231,13 @@ class ManifestManager: manifest_path = self.get_specific_version_manifest_path(version_id) - # Read custom (or mod loader) manifest first. If not exist, get manifest from official data + if manifest_path is None: + self.widget_mgr.signal.show_error_message.emit( + f"Version manifest not found: {version_id}" + ) + return None + + # 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) else: @@ -239,9 +246,9 @@ class ManifestManager: if not manifest: return None - parent_id = manifest.get("inheritsFrom") + parent_id: str | None = manifest.get("inheritsFrom") - # Return if the version don't need to merge manifest + # Return if the version doesn't need to merge manifest if not parent_id: return self.ResolvedVersionManifest( manifest=manifest, @@ -249,17 +256,32 @@ class ManifestManager: client_version_id=version_id, ) - # Get inherits if needed + # Get the parent manifest if needed parent = self.resolve_manifest(parent_id, visited) 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 + + rules = MOD_LOADER_RULES.get(loader_name, {}) + # Merge official and loader manifest merged = merge_manifest( inherits_version_manifest=parent.manifest, mod_version_manifest=manifest, + prefer_libraries_by=rules.get( + "preferLibraryBy", + PREFER_MOD_LIBRARY, + ) ) except Exception as exc: self.widget_mgr.signal.show_error_message.emit( @@ -524,7 +546,7 @@ class JavaManager: errors: list[Path] """ discovered, errors = self.discover_runtimes(extra_install_patterns) - retained = [runtime for runtime in self.runtimes if runtime.source != "system"] + retained = [runtime for runtime in self.list_runtimes() if runtime.source != "system"] by_executable = {runtime.executable.resolve(): runtime for runtime in retained} for runtime in discovered: @@ -544,7 +566,13 @@ class JavaManager: for runtime in self.runtimes: if runtime.executable.resolve() == candidate: - return runtime + updated = self.inspect_runtime( + candidate, source=runtime.source, component=runtime.component, + runtime_id=runtime.id, + ) + self.runtimes = [updated if item.id == runtime.id else item for item in self.runtimes] + self.save_runtimes() + return updated runtime = self.inspect_runtime(candidate, source="custom") self.runtimes.append(runtime) @@ -611,7 +639,7 @@ class JavaManager: if not self.runtimes: self.refresh_runtimes() - return [runtime.to_dict() for runtime in self.runtimes] + return [runtime.to_dict() for runtime in self.list_runtimes() if runtime.valid] def get_support_runtime_jvm_executable(self, major_version: int | str, no_error: bool=False) -> str | None: runtime = self.resolve_runtime(major_version=int(major_version)) @@ -628,6 +656,12 @@ class JavaManager: def list_runtimes(self, *, refresh: bool = False) -> list[JavaRuntime]: if refresh: self.refresh_runtimes() + # A runtime can be removed or restored while the launcher is open. + # JavaRuntime is immutable, so replace stale snapshots before exposing them. + self.runtimes = [ + replace(runtime, valid=runtime.executable.is_file()) + for runtime in self.runtimes + ] return list(self.runtimes) @staticmethod @@ -642,7 +676,7 @@ class JavaManager: for runtime in runtimes: executable = runtime.executable - if not executable.exists(): + if not executable.is_file(): errors.append(runtime) return errors @@ -657,7 +691,7 @@ class JavaManager: runtimes = self.list_runtimes() errors = self.check_runtimes(runtimes) - if not runtimes or errors: + if errors or not any(item.valid and item.major_version == int(required_major) for item in runtimes): if errors: self.widget_mgr.signal.show_plain_error_text.emit( { diff --git a/pyproject.toml b/pyproject.toml index 4b9f43e..42aea40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "testlauncher" -version = "0.1.1a0" +version = "0.1.2a0" description = "A lightweight Minecraft launcher." readme = "README.md" requires-python = ">=3.10" diff --git a/resources/styles/main.qss b/resources/styles/main.qss index 696300d..3acc50a 100644 --- a/resources/styles/main.qss +++ b/resources/styles/main.qss @@ -10,6 +10,131 @@ /* Add your QSS styles here */ +QPushButton { + background-color: palette(button); + color: palette(button-text); + border: 1px solid palette(mid); + border-radius: 4px; + padding: 6px 10px; +} + +QPushButton:hover { + background-color: palette(midlight); + color: palette(button-text); +} + +QPushButton:focus { + border-color: palette(highlight); +} + +QPushButton:pressed, +QPushButton:checked { + background-color: palette(highlight); + color: palette(highlighted-text); +} + +QPushButton:disabled { + background-color: palette(button); + color: palette(placeholder-text); +} + +QComboBox { + background-color: palette(base); + color: palette(text); + border: 1px solid palette(mid); + border-radius: 4px; + padding: 4px 24px 4px 8px; + selection-background-color: palette(highlight); + selection-color: palette(highlighted-text); +} + +QComboBox:focus { + border-color: palette(highlight); +} + +QComboBox::drop-down { + width: 20px; + background: transparent; + border: none; +} + +QComboBox QAbstractItemView, +QComboBox QLineEdit { + background-color: palette(base); + color: palette(text); + selection-background-color: palette(highlight); + selection-color: palette(highlighted-text); +} + +/* Scrollbars follow the active theme palette. */ +QScrollBar:vertical, +QScrollBar:horizontal { + background: palette(alternate-base); + border: none; + border-radius: 6px; + margin: 0; + padding: 2px; +} + +QScrollBar:vertical { + width: 12px; +} + +QScrollBar:horizontal { + height: 12px; +} + +QScrollBar::handle:vertical, +QScrollBar::handle:horizontal { + background: palette(mid); + border: none; + border-radius: 4px; +} + +QScrollBar::handle:vertical { + min-height: 32px; +} + +QScrollBar::handle:horizontal { + min-width: 32px; +} + +QScrollBar::handle:vertical:hover, +QScrollBar::handle:horizontal:hover { + background: palette(placeholder-text); +} + +QScrollBar::handle:vertical:pressed, +QScrollBar::handle:horizontal:pressed { + background: palette(highlight); +} + +QScrollBar::add-line:vertical, +QScrollBar::sub-line:vertical { + height: 0; + border: none; + background: transparent; +} + +QScrollBar::add-line:horizontal, +QScrollBar::sub-line:horizontal { + width: 0; + border: none; + background: transparent; +} + +QScrollBar::add-page:vertical, +QScrollBar::sub-page:vertical, +QScrollBar::add-page:horizontal, +QScrollBar::sub-page:horizontal { + background: transparent; +} + +QAbstractScrollArea::corner { + background: palette(window); + border: none; +} + QLabel#dev_info_box { font-size: 20pt; font-weight: bold; @@ -25,4 +150,49 @@ QLabel#version_label, QLabel#version_label { QLabel#icon_label { border-radius: 20px; -} \ No newline at end of file +} + +/* Modrinth follows the plugin list and details layout. */ +QWidget#modrinthPage QLabel#modrinthTitle { + font-size: 20px; + font-weight: bold; +} + +QWidget#modrinthPage QLabel#modrinthSectionTitle { + font-size: 14px; + font-weight: bold; +} + +QWidget#modrinthPage QLabel#modrinthMuted { + color: palette(placeholder-text); +} + +QListWidget#modrinthResults { + background-color: palette(base); + border: 1px solid palette(mid); + border-radius: 6px; + outline: none; +} + +QListWidget#modrinthResults::item { + padding: 6px; + border-radius: 4px; +} + +QListWidget#modrinthResults::item:selected { + background-color: palette(highlight); + color: palette(highlighted-text); +} + +QWidget#modrinthPage QLineEdit { + padding: 7px; + border: 1px solid palette(mid); + border-radius: 5px; + background-color: palette(base); + color: palette(text); +} + +QWidget#modrinthPage QSplitter::handle:horizontal { + width: 1px; + background-color: palette(mid); +} diff --git a/resources/styles/profile.qss b/resources/styles/profile.qss index 963a425..4dc80f3 100644 --- a/resources/styles/profile.qss +++ b/resources/styles/profile.qss @@ -56,6 +56,29 @@ QPushButton#launchButton { min-width: 150px; font-size: 15px; font-weight: 600; + background-color: palette(button); + color: palette(button-text); + border: 1px solid palette(mid); + border-radius: 5px; + padding: 6px 14px; +} + +QPushButton#launchButton:hover { + background-color: palette(midlight); + color: palette(button-text); +} + +QPushButton#launchButton:focus { + border-color: palette(highlight); +} + +QPushButton#launchButton:pressed { + background-color: palette(highlight); + color: palette(highlighted-text); +} + +QPushButton#launchButton:disabled { + color: palette(placeholder-text); } QLabel#headerLabel { diff --git a/resources/styles/toolbar.qss b/resources/styles/toolbar.qss index 94ab37d..432d061 100644 --- a/resources/styles/toolbar.qss +++ b/resources/styles/toolbar.qss @@ -53,17 +53,25 @@ QToolBar:right QToolButton { QToolBar QPushButton:hover, QToolBar QToolButton:hover { background-color: palette(midlight); + color: palette(button-text); } QToolBar QPushButton:focus, QToolBar QToolButton:focus { + background-color: palette(midlight); + color: palette(button-text); border-bottom: 2px solid palette(highlight); } QToolBar QPushButton:pressed, -QToolBar QToolButton:pressed, +QToolBar QToolButton:pressed { + background-color: palette(highlight); + color: palette(highlighted-text); +} + QToolBar QToolButton:checked { - background-color: palette(dark); + background-color: palette(highlight); + color: palette(highlighted-text); } QToolBar QPushButton:disabled, diff --git a/resources/translations/en.json b/resources/translations/en.json index 716af7f..c880e3b 100644 --- a/resources/translations/en.json +++ b/resources/translations/en.json @@ -1,4 +1,22 @@ { + "Clear selection": "Clear selection", + "Select a mod to view its details.": "Select a mod to view its details.", + "Install {count} selected mods": "Install {count} selected mods", + "{count} mods selected · Unspecified versions use the latest compatible version.": "{count} mods selected · Unspecified versions use the latest compatible version.", + "Uses saved profile settings. Profiles sharing a game directory also share mods.": "Uses saved profile settings. Profiles sharing a game directory also share mods.", + "Search Modrinth mods": "Search Modrinth mods", + "Open Modrinth project": "Open Modrinth project", + "Install with required dependencies": "Install with required dependencies", + "{name} · Minecraft {version} · {loader}\nMods: {path}": "{name} · Minecraft {version} · {loader}\nMods: {path}", + "Working...": "Working...", + "Modrinth error: {error}": "Modrinth error: {error}", + "{count} results · Page {page}": "{count} results · Page {page}", + "No compatible mods found.": "No compatible mods found.", + "No compatible versions found.": "No compatible versions found.", + "Install mods": "Install mods", + "Install {count} file(s) into {path}?": "Install {count} file(s) into {path}?", + "Installed or verified {count} mod file(s).": "Installed or verified {count} mod file(s).", + "Downloading {name}...": "Downloading {name}...", "Profile settings": "Profile settings", "Enable plugin": "Enable plugin", "Disable plugin": "Disable plugin", diff --git a/resources/translations/zh-TW.json b/resources/translations/zh-TW.json index 297f66a..69a2815 100644 --- a/resources/translations/zh-TW.json +++ b/resources/translations/zh-TW.json @@ -1,4 +1,22 @@ { + "Clear selection": "清除勾選", + "Select a mod to view its details.": "選擇模組以查看詳細資訊。", + "Install {count} selected mods": "安裝已勾選的 {count} 個模組", + "{count} mods selected · Unspecified versions use the latest compatible version.": "已勾選 {count} 個模組 · 未指定版本時使用最新相容版本。", + "Uses saved profile settings. Profiles sharing a game directory also share mods.": "使用已儲存的設定檔設定。共用遊戲目錄的設定檔也會共用模組。", + "Search Modrinth mods": "搜尋 Modrinth 模組", + "Open Modrinth project": "開啟 Modrinth 專案", + "Install with required dependencies": "安裝模組及必要相依套件", + "{name} · Minecraft {version} · {loader}\nMods: {path}": "{name} · Minecraft {version} · {loader}\n模組目錄:{path}", + "Working...": "處理中……", + "Modrinth error: {error}": "Modrinth 錯誤:{error}", + "{count} results · Page {page}": "{count} 個結果 · 第 {page} 頁", + "No compatible mods found.": "找不到相容的模組。", + "No compatible versions found.": "找不到相容的版本。", + "Install mods": "安裝模組", + "Install {count} file(s) into {path}?": "將 {count} 個檔案安裝至 {path}?", + "Installed or verified {count} mod file(s).": "已安裝或驗證 {count} 個模組檔案。", + "Downloading {name}...": "正在下載 {name}……", "Profile settings": "設定檔設定", "Enable plugin": "啟用插件", "Disable plugin": "停用插件", diff --git a/tests/test_java_manager.py b/tests/test_java_manager.py index 7b0c505..f1eea23 100644 --- a/tests/test_java_manager.py +++ b/tests/test_java_manager.py @@ -1,4 +1,31 @@ -from manager.game import JavaManager +import logging +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from core_lib.common.exception import JavaRuntimeException +from manager.game import JavaManager, JavaRuntime + + +@pytest.fixture +def java_manager(tmp_path): + app = SimpleNamespace( + work_dir=tmp_path, + logger=logging.getLogger(__name__), + widget_manager=SimpleNamespace(signal=SimpleNamespace(show_plain_error_text=Mock())), + ) + return JavaManager(app) + + +def add_runtime(manager, name="java", *, source="custom", major=21): + executable = Path(manager.app.work_dir) / name / "bin" / "java" + executable.parent.mkdir(parents=True) + executable.touch() + runtime = JavaRuntime(name, major, str(major), executable, executable.parent.parent, source) + manager.runtimes.append(runtime) + return runtime def test_runtime_major_version_from_modern_version(): @@ -13,3 +40,71 @@ def test_runtime_major_version_from_legacy_version(): def test_runtime_major_version_rejects_unknown_value(): assert JavaManager._runtime_major_version(None) is None assert JavaManager._runtime_major_version("unknown") is None + + +def test_runtime_list_tracks_removal_and_restoration(java_manager): + runtime = add_runtime(java_manager) + runtime.executable.unlink() + assert not java_manager.list_runtimes()[0].valid + runtime.executable.touch() + assert java_manager.list_runtimes()[0].valid + + +@pytest.mark.parametrize("source", ["custom", "managed"]) +def test_refresh_does_not_resolve_missing_retained_runtime(java_manager, monkeypatch, source): + runtime = add_runtime(java_manager, source=source) + runtime.executable.unlink() + monkeypatch.setattr("manager.game.find_java_installations", lambda _: ([], [])) + assert java_manager.resolve_runtime(major_version=21) is None + assert not java_manager.runtimes[0].valid + # Availability is also correct after restarting the launcher. + assert not JavaManager(java_manager.app).list_runtimes()[0].valid + + +def test_resolve_uses_available_runtime_when_managed_one_disappears(java_manager, monkeypatch): + missing = add_runtime(java_manager, "managed", source="managed") + available = add_runtime(java_manager, "custom") + missing.executable.unlink() + monkeypatch.setattr("manager.game.find_java_installations", lambda _: ([], [])) + assert java_manager.resolve_runtime(major_version=21).id == available.id + + +def test_directory_is_not_a_java_executable(java_manager): + runtime = add_runtime(java_manager) + runtime.executable.unlink() + runtime.executable.mkdir() + assert JavaManager.check_runtimes([runtime]) == [runtime] + assert not java_manager.list_runtimes()[0].valid + + +def test_register_existing_runtime_rechecks_version_and_preserves_identity(java_manager, monkeypatch): + runtime = add_runtime(java_manager, source="managed") + monkeypatch.setattr("manager.game.get_java_version", lambda _: (25, "25.0.1")) + updated = java_manager.register_runtime(runtime.executable) + assert updated.major_version == 25 + assert updated.id == runtime.id + assert updated.source == "managed" + assert java_manager.list_runtimes() == [updated] + + +def test_register_existing_missing_runtime_is_rejected(java_manager): + runtime = add_runtime(java_manager) + runtime.executable.unlink() + with pytest.raises(JavaRuntimeException): + java_manager.register_runtime(runtime.executable) + + +def test_resolve_discovers_required_version_even_with_other_cached_runtimes(java_manager, monkeypatch): + add_runtime(java_manager, "old", major=8) + executable = Path(java_manager.app.work_dir) / "new-java" + executable.touch() + monkeypatch.setattr("manager.game.find_java_installations", lambda _: ([{ + "major": 21, "raw": "21.0.8", "executable": str(executable), + }], [])) + assert java_manager.resolve_runtime(major_version=21).executable == executable + + +def test_legacy_selector_excludes_missing_runtimes(java_manager): + runtime = add_runtime(java_manager) + runtime.executable.unlink() + assert java_manager.get_or_cache_jvm_settings() == []