From 1754b012305da40f96dcb75bec9ebb4e9cd32137 Mon Sep 17 00:00:00 2001 From: wei Date: Sun, 18 Oct 2026 21:42:54 +0800 Subject: [PATCH] Fix an issue that causes create symlink failed when installing java on unix-like platforms. --- constant.py | 2 +- core_lib/__init__.py | 2 +- core_lib/common/common.py | 9 ++ core_lib/common/exception.py | 4 +- core_lib/game/argument.py | 95 ++++++++---- core_lib/game/library_core.py | 62 +++++++- core_lib/runtime/mojang.py | 102 ++++++++---- manager/game.py | 56 ++++++- manager/widgets.py | 1 + tests/test_i18n.py | 56 +++++++ tests/test_java_manager.py | 15 ++ tests/test_mac_os_arm64_runtime_install.py | 30 ++++ tests/test_profile_sorting.py | 55 +++++++ tests/test_settings.py | 171 +++++++++++++++++++++ window.py | 17 ++ 15 files changed, 600 insertions(+), 77 deletions(-) create mode 100644 tests/test_i18n.py create mode 100644 tests/test_java_manager.py create mode 100644 tests/test_mac_os_arm64_runtime_install.py create mode 100644 tests/test_profile_sorting.py create mode 100644 tests/test_settings.py diff --git a/constant.py b/constant.py index 482bc33..4b103f5 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.0.7-alpha" +LAUNCHER_VERSION = "0.0.8-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 1259449..d6adeb2 100644 --- a/core_lib/__init__.py +++ b/core_lib/__init__.py @@ -1,4 +1,4 @@ -__version__ = '0.1.1' +__version__ = '0.1.2' __description__ = """ The core library of the *Launcher* diff --git a/core_lib/common/common.py b/core_lib/common/common.py index c8cc60b..012d94f 100644 --- a/core_lib/common/common.py +++ b/core_lib/common/common.py @@ -160,6 +160,12 @@ class FileObject: def exists(self): return self.__path.exists() + def invalidate_hash_cache(self): + self.__sha1 = None + self.__sha256 = None + self.__sha512 = None + self.__md5 = None + def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None) -> FileObject | Exception: """ @@ -180,6 +186,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ logger.debug("Downloading file {} to {}".format(file.url, file)) + file.invalidate_hash_cache() # Clean cache hash try: with requests.get(file.url, stream=True) as r: r.raise_for_status() @@ -203,6 +210,8 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ raise DownloadException( "An error occurred while downloading file {}. {}".format(file.url, e) ) + finally: + file.invalidate_hash_cache() if file.expected_sha256 and not file.verify_sha256(): raise HashMismatchException("sha256", file.sha256, file.expected_sha256, file.posix_path) diff --git a/core_lib/common/exception.py b/core_lib/common/exception.py index 1b5f941..9c46c4c 100644 --- a/core_lib/common/exception.py +++ b/core_lib/common/exception.py @@ -24,8 +24,8 @@ class LauncherHTTPException(LauncherException): class HashMismatchException(Exception): def __init__(self, hash_name, got_hash, expected_hash, filepath: str | Path): if type(filepath) == Path: filepath = Path(filepath).absolute().as_posix() - self.message = "File {} hash mismatch. Expected hash {}. Got hash {} ({})".format(filepath, got_hash, - expected_hash, hash_name) + self.message = "File {} hash mismatch. Expected hash {}. Got hash {} ({})".format(filepath, expected_hash, got_hash, + hash_name) super().__init__(self.message) class UnsupportedPlatformException(LauncherException): diff --git a/core_lib/game/argument.py b/core_lib/game/argument.py index f4b9b7e..daef1df 100644 --- a/core_lib/game/argument.py +++ b/core_lib/game/argument.py @@ -4,10 +4,18 @@ import re import shlex from core_lib.common.common import get_platform_info +from core_lib.common.exception import LauncherException from core_lib.game.library import get_natives_platform_info logger = logging.getLogger("Launcher.CoreLib") +def compare_versions(left: str, right: str) -> int: + 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 is_argument_allowed(argument: dict | str, allow_features: dict | None = None) -> bool: """ @@ -44,6 +52,7 @@ def is_argument_allowed(argument: dict | str, allow_features: dict | None = None feature_rule = rule.get("features") or {} rule_arch = os_rule.get("arch") rule_version = os_rule.get("version") + rule_version_range = os_rule.get("versionRange") # Check platform if rule_os is not None and platform_rule_name != rule_os: @@ -69,6 +78,18 @@ def is_argument_allowed(argument: dict | str, allow_features: dict | None = None ) continue + # Check version range + if rule_version_range is not None: + min_value = rule_version_range.get("min") + max_value = rule_version_range.get("max") + + try: + if min_value is not None and compare_versions(platform_version, min_value) < 0: + continue + if max_value is not None and compare_versions(platform_version, max_value) > 0: + continue + except ValueError: + raise LauncherException("Unable to compare versions: SYS_VER: {} MIN: {} MAX: {}".format(platform_version, min_value, max_value)) # Check feature rule if any(allow_features.get(key, False) != expected for key, expected in feature_rule.items()): @@ -98,7 +119,8 @@ class ArgumentMappings: auth_access_token="", clientid=None, auth_xuid=None, 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): + classpath=None, classpath_separator=None, library_directory=None, + resolution: tuple[int, int] | None = None): self.player_name = player_name self.version_name = version_name self.game_directory = game_directory @@ -111,6 +133,7 @@ class ArgumentMappings: self.auth_xuid = auth_xuid self.user_type = user_type self.user_properties = user_properties + self.resolution = resolution if isinstance(user_properties, dict): self.user_properties = json.dumps( user_properties, @@ -194,24 +217,8 @@ def find_game_and_jvm_args(arguments: dict | str) -> tuple[list, list]: return game_args, jvm_args -REMAPPING_ARGUMENTS = { - # For some (I don't know) reason, in 26.2, Mojang include some - "-Djava.library.path=${natives_directory}/java": "-Djava.library.path=${natives_directory}" -} - - -def hard_remapping_special_arguments(argument: str) -> str: - for arg in REMAPPING_ARGUMENTS: - new_value = REMAPPING_ARGUMENTS[arg] - - if arg == argument: - return new_value - - return argument - - def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappings, features: dict | None = None) -> \ -list[str]: + list[str]: if features is None: features = {} @@ -228,13 +235,8 @@ list[str]: if not is_argument_allowed(argument, allow_features=features): continue - # Replace some special arguments - new_argument = hard_remapping_special_arguments(argument) - # Each argument (section) may contain multiple items, convert it to list before replace placeholder - converted = convert_argument_to_multiple_string(new_argument) - - for item in converted: + for item in convert_argument_to_multiple_string(argument): parsed = replace_placeholders(item, placeholders) parsed_arguments.append(parsed) @@ -263,24 +265,59 @@ def append_missing_necessary_jvm_arguments(arguments: list, arg_maps: ArgumentMa return result +def add_feature_arguments(arguments: dict, arg_maps: ArgumentMappings, features: dict | None = None) -> list[str]: + result = [] + + if features is None: + return result + + if features.get("has_custom_resolution"): + result.append(f"-Dminecraft.overrideResolution={features['resolution']}") + + return result def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_path: str, full_args: dict | str - , features: dict | None = None) -> list[str]: + , features: dict | None = None, user_jvm_args: list[str] | None | str = None) -> list[str]: cmd = [java_path] game_args, jvm_args = find_game_and_jvm_args(full_args) - parsed_jvm_args = parse_and_generate_arguments( + + if isinstance(user_jvm_args, str): + user_jvm_args = shlex.split(user_jvm_args) + + if user_jvm_args is None: + # Use manifest recommended user jvm arguments + default_args = ( + full_args.get("default-user-jvm", []) + if isinstance(full_args, dict) + else [] + ) + + parsed_user_jvm_args = parse_and_generate_arguments( + default_args, + arg_maps, + features=features, + ) + else: + # Use jvm arguments that provided by user + parsed_user_jvm_args = list(user_jvm_args) + + parsed_manifest_jvm_args = parse_and_generate_arguments( jvm_args, arg_maps, - features=features + features=features, ) + parsed_game_args = parse_and_generate_arguments( game_args, arg_maps, - features=features + features=features, ) # Legacy Minecraft don't have jvm arguments exist in the version library. We need to generate by ourselves - parsed_jvm_args = append_missing_necessary_jvm_arguments(parsed_jvm_args, arg_maps) + parsed_jvm_args = append_missing_necessary_jvm_arguments( + parsed_user_jvm_args + parsed_manifest_jvm_args, # Combine manifest and user jvm arguments together + arg_maps, + ) cmd.extend(parsed_jvm_args) cmd.append(main_class) diff --git a/core_lib/game/library_core.py b/core_lib/game/library_core.py index b3d76dc..0c85ca9 100644 --- a/core_lib/game/library_core.py +++ b/core_lib/game/library_core.py @@ -1,9 +1,10 @@ import logging import re import zipfile -from pathlib import Path +from pathlib import Path, PureWindowsPath from typing import Callable +from .argument import convert_argument_to_multiple_string, find_game_and_jvm_args, is_argument_allowed from .library import get_natives_platform_info, is_library_allowed, generate_formatted_artifact_with_name, \ is_native_allowed, is_legacy_native_allowed, remove_duplicate_artifacts from .libraryx import normalize_library_to_common_struct @@ -64,6 +65,47 @@ def collect_library_artifacts(specific_version_manifest): return items +def locate_natives_extract_dir(jvm_args: list[str | dict], default_extract_dir: Path, + features: dict | None = None) -> Path: + property_prefix = "-Djava.library.path=" + placeholder = "${natives_directory}" + + path_value = None + for argument in jvm_args: + if not is_argument_allowed(argument, allow_features=features): + continue + for arg in convert_argument_to_multiple_string(argument): + if arg.startswith(property_prefix): + path_value = arg[len(property_prefix):] + + if path_value is None or path_value == placeholder: + return default_extract_dir + + if not path_value.startswith(placeholder + "/") and not path_value.startswith(placeholder + "\\"): + raise ValueError("Unsupported java.library.path extraction layout") + + suffix = path_value[len(placeholder) + 1:].replace("\\", "/") + parts = suffix.split("/") + + if ( + any(part in ("", ".", "..") for part in parts) + or any(char in suffix for char in ":;${}") + or PureWindowsPath(suffix).drive + ): + raise ValueError("Invalid native extraction subdirectory") + + root = default_extract_dir.resolve() + destination = root.joinpath(*parts).resolve() + + if not destination.is_relative_to(root): + raise ValueError("Native extraction directory escapes its root") + + return destination + +def locate_natives_extract_dir_by_manifest(manifest: dict, default_extract_dir: Path, + features: dict | None = None) -> Path: + _, jvm = find_game_and_jvm_args(manifest.get("arguments") or {}) + return locate_natives_extract_dir(jvm, default_extract_dir, features=features) def collect_native_artifacts(specific_version_manifest): """ @@ -344,7 +386,9 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path): return not_found -def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path): +def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *, + features: dict | None = None): + extract_dir = locate_natives_extract_dir_by_manifest(manifest, natives_dir, features=features) filtered = [] # Convert current platform and architecture type to same formula @@ -464,17 +508,19 @@ def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path) return False for target in expected: - if not (natives_dir / target).exists(): + if not (extract_dir / target).is_file(): return False return True -def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path) -> bool: +def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *, + features: dict | None = None) -> bool: natives_exist = check_natives_exists( manifest, libraries_dir, natives_dir, + features=features, ) missing_libraries = check_libraries_exists( manifest, @@ -555,10 +601,12 @@ def generate_classpath(manifest: dict, libraries_dir: Path, core_file_path: Path return f"{separator}".join(classes) -def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Path, +def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives_dir: Path, progress_callback: Callable[[str, float], None] = None, redownload_callback: Callable[ - [list[FileObject]], tuple[bool, list[FileObject]]] = None) -> None: + [list[FileObject]], tuple[bool, list[FileObject]]] = None, *, + features: dict | None = None) -> None: + natives_dir = locate_natives_extract_dir_by_manifest(manifest, default_natives_dir, features=features) # libraries libraries = collect_library_artifacts(manifest) @@ -593,4 +641,4 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Pa else: raise DependencyException( "Certain libraries download failed. Unable to continue unzip process.\n" - ) \ No newline at end of file + ) diff --git a/core_lib/runtime/mojang.py b/core_lib/runtime/mojang.py index d28a87b..59f3e9e 100644 --- a/core_lib/runtime/mojang.py +++ b/core_lib/runtime/mojang.py @@ -164,19 +164,20 @@ def get_support_runtime_manifest(root_runtime_manifest: dict, require_component: @dataclass class RuntimeCheckResult: # file and dir + skip: bool is_executable: bool target_path: FileObject | Path | None # symlink only is_symlink: bool - source_path: Path + source_path: Path | str | None def _check_runtime_file(relative_path, source_path: str | None, file_type: str, sha1: str | None, size: str | None, url: str | None, executable: bool, runtime_dir: Path, no_hash_check: bool = False) -> RuntimeCheckResult: full_path = runtime_dir / Path(relative_path) - source_path = (runtime_dir / Path(source_path)) if source_path else None + source_path = Path(source_path) if source_path else None - result = RuntimeCheckResult(is_executable=executable, target_path=None, is_symlink=False, source_path=source_path) + result = RuntimeCheckResult(skip=False, is_executable=executable, target_path=None, is_symlink=False, source_path=source_path) if (not sha1 and not no_hash_check) and file_type == "file": raise RuntimeManifestDataException( @@ -221,16 +222,25 @@ def _check_runtime_file(relative_path, source_path: str | None, file_type: str, suffix ) ) - else: - result.target_path = target_file + result.skip = True + + result.target_path = target_file elif file_type == "directory": target_file = Path(full_path) - - if not target_file.exists() or not target_file.is_dir(): - result.target_path = target_file + result.target_path = target_file + if target_file.exists() and target_file.is_dir(): + result.skip = True elif file_type == "link": - if not Path(full_path).is_symlink() or os.readlink(full_path) != source_path: - result.target_path = Path(full_path) + result.is_symlink = True + result.target_path = Path(full_path) + + if not isinstance(source_path, Path): + raise RuntimeManifestDataException( + "Invalid source path: {}".format(source_path) + ) + + if Path(full_path).is_symlink() and os.readlink(full_path) == source_path.as_posix(): + result.skip = True else: raise RuntimeManifestDataException( "Unsupported file type: {}".format(file_type) @@ -281,9 +291,10 @@ def collect_runtime_files(manifest: dict, runtime_dir: Path, max_workers=RUNTIME for future in as_completed(futures): result: RuntimeCheckResult = future.result() target_path = result.target_path + skip = result.skip - if not target_path: - logger.debug("No target path found, skip process: {}".format(target_path)) + if skip: + logger.debug("Skip file: {}".format(target_path)) continue if not isinstance(target_path, (FileObject, Path)): @@ -295,23 +306,15 @@ def collect_runtime_files(manifest: dict, runtime_dir: Path, max_workers=RUNTIME target_list.append(target_path) elif isinstance(target_path, Path): if result.is_symlink: - result_symlinks.append({""}) + if not isinstance(result.source_path, (str, Path)): + raise RuntimeManifestDataException( + "Invalid source path: {}".format(result.source_path) + ) + + result_symlinks.append({"destination": target_path, "source": result.source_path}) else: result_dirs.append(target_path) - if result.target_path and isinstance(result.target_path, FileObject) and not result.is_executable: - result_files.append(result.target_path) - elif result.target_path and isinstance(result.target_path, FileObject) and result.is_executable: - result_executables.append(result.target_path) - elif result.target_path and isinstance(result.target_path, Path): - if result.is_symlink: - if not result.source_path: - raise RuntimeManifestDataException("Runtime data missing symlink source path.") - - result_symlinks.append({"destination": result.target_path, "source": result.source_path}) - else: - result_dirs.append(result.target_path) - if not use_raw: logger.warning( "The \"raw\" flag is not enabled, but the launcher does not support compressed files yet. " @@ -350,17 +353,41 @@ def post_process_runtime_dir(dirs: list[Path], executables: list[Path | FileObje future.result() for value in symlinks: - dest_path = value.get("destination") - source_path = value.get("source") + dest_path_raw: str | Path | None = value.get("destination") + source_path_raw: str | Path | None = value.get("source") + + if source_path_raw is None: + raise LauncherException("Invalid source path: {}".format(source_path_raw)) + + if dest_path_raw is None: + raise LauncherException("Invalid destination path: {}".format(dest_path_raw)) + + source_path = source_path_raw if isinstance(source_path_raw, Path) else Path(source_path_raw) + dest_path = dest_path_raw if isinstance(dest_path_raw, Path) else Path(dest_path_raw) # ignore existing - if Path(source_path).is_symlink() and os.readlink(source_path) == dest_path: - return + if Path(dest_path).is_symlink() and os.readlink(dest_path) == str(source_path): + continue try: + dest_path.parent.mkdir(parents=True, exist_ok=True) + + if dest_path.is_symlink(): + if os.readlink(dest_path) == str(source_path): + continue + dest_path.unlink() + elif dest_path.is_dir(): + dest_path.rmdir() + elif dest_path.exists(): + raise LauncherException( + f"Cannot create symlink: destination is an existing file: {dest_path}" + ) + os.symlink(source_path, dest_path) except Exception as exc: - raise LauncherException(f"Failed to symlink {source_path} to {dest_path}: {exc}") + raise LauncherException( + f"Failed to create symlink {dest_path} -> {source_path}: {exc}" + ) from exc def download_java_runtimes(component: str, runtime_dir: Path, no_hash_check: bool = False, progress_callback: Callable[[str, float], None] = None, @@ -405,6 +432,15 @@ def download_java_runtimes(component: str, runtime_dir: Path, no_hash_check: boo "Unable to download some runtime files.\n" ) - post_process_runtime_dir(dirs, executables, symlinks, max_workers=max_check_workers) + all_executables = [ + runtime_dir / relative_path + for relative_path, data in manifest.get("files", {}).items() + if data.get("type") == "file" and data.get("executable", False) + ] - return + post_process_runtime_dir( + dirs, + all_executables, + symlinks, + max_workers=max_check_workers, + ) diff --git a/manager/game.py b/manager/game.py index 2349992..32d3047 100644 --- a/manager/game.py +++ b/manager/game.py @@ -582,11 +582,15 @@ class JavaManager: return int(match.group(1)) if match else None def list_installable_runtimes(self) -> list[InstallableJavaRuntime]: - """Return Mojang components with the Java version carried by each one.""" + """ + Return Mojang components with the Java version carried by each one. + """ manifest = fetch_runtime_manifest() platform_key = get_current_platform_runtime_key() + if not platform_key: return [] + platform_runtimes = manifest.get(platform_key, {}) result = [] for component, versions in platform_runtimes.items(): @@ -601,10 +605,13 @@ class JavaManager: raw_version=raw_version, released=version.get("released"), )) + return sorted(result, key=lambda item: (item.major_version or -1, item.component), reverse=True) def list_installable_components(self) -> list[str]: - """Compatibility API returning component names only.""" + """ + Compatibility API returning component names only. + """ return [runtime.component for runtime in self.list_installable_runtimes()] def unregister_runtime(self, runtime_id: str) -> bool: @@ -646,6 +653,23 @@ class JavaManager: self.refresh_runtimes() return list(self.runtimes) + @staticmethod + def check_runtimes(runtimes: list[JavaRuntime]) -> list[JavaRuntime]: + """ + Check runtimes + :return: + error_runtimes: list[JavaRuntime] + """ + errors = [] + + for runtime in runtimes: + executable = runtime.executable + + if not executable.exists(): + errors.append(runtime) + + return errors + def resolve_runtime(self, *, manifest: dict | None = None, major_version: int | None = None, preferred_runtime_id: str | None = None) -> JavaRuntime | None: java_requirement = (manifest or {}).get("javaVersion", {}) @@ -655,7 +679,16 @@ class JavaManager: return None runtimes = self.list_runtimes() - if not runtimes: + errors = self.check_runtimes(runtimes) + if not runtimes or errors: + if errors: + self.widget_mgr.signal.show_plain_error_text.emit( + { + "message": "Some runtimes are no longer available after last check.", + "content": "\n".join(f"{runtime.id} ({runtime.major_version}): {runtime.executable} > {runtime.home_dir}" for runtime in errors), + } + ) + runtimes, _ = self.refresh_runtimes() if preferred_runtime_id: @@ -679,10 +712,13 @@ class JavaManager: progress_callback=progress_callback, redownload_callback=redownload_callback, ) + executable_name = "java.exe" if sys.platform == "win32" else "java" candidates = sorted(destination.rglob(executable_name)) + if not candidates: raise JavaRuntimeException(f"Installed runtime has no {executable_name}: {destination}") + runtime = self.inspect_runtime(candidates[0], source="managed", component=component) self.runtimes = [item for item in self.runtimes if item.executable.resolve() != runtime.executable.resolve()] self.runtimes.append(runtime) @@ -1142,6 +1178,7 @@ class LaunchManager: classpath=classpath, classpath_separator=os.pathsep, library_directory=libraries_dir.as_posix(), + resolution=profile.resolution, ) target_args = arguments if arguments else old_args @@ -1219,11 +1256,22 @@ class LaunchManager: self.app.logger.debug(f"Java executable path is: {java_path}") # Finally, generate launch command + if not main_class: + return result.fail( + "Main class does not exist in manifest." + ) + + features = { + "has_custom_resolution": profile.resolution is not None, + } + cmd = generate_launch_command( arg_maps=arg_maps, main_class=main_class, java_path=java_path, - full_args=target_args + full_args=target_args, + features=features, + user_jvm_args=profile.java_args ) safe_cmd = ["" if value == launch_account.access_token else value for value in cmd] diff --git a/manager/widgets.py b/manager/widgets.py index b9636e0..03cae19 100644 --- a/manager/widgets.py +++ b/manager/widgets.py @@ -54,6 +54,7 @@ class WidgetManager(QObject): show_and_print_error_message = Signal(dict) show_warning_message = Signal(str) show_info_message = Signal(str) + show_plain_error_text = Signal(dict) enable_widget = Signal(object) disable_widget = Signal(object) askyesno = Signal(object) diff --git a/tests/test_i18n.py b/tests/test_i18n.py new file mode 100644 index 0000000..b833e6d --- /dev/null +++ b/tests/test_i18n.py @@ -0,0 +1,56 @@ +import json +from pathlib import Path +from string import Formatter + +from core_lib.i18n import TranslationManager + + +def test_empty_catalog_uses_english_source_strings(tmp_path): + (tmp_path / "zh-TW.json").write_text("{}", encoding="utf-8") + translations = TranslationManager(tmp_path, "zh-TW") + + assert translations.language == "zh-TW" + assert translations.translate("Settings") == "Settings" + assert translations.translate("Version: {version}", version="1.0") == "Version: 1.0" + + +def test_catalog_translation_and_unknown_language_fallback(tmp_path): + (tmp_path / "zh-TW.json").write_text( + json.dumps({"Settings": "設定"}), encoding="utf-8" + ) + translations = TranslationManager(tmp_path, "zh-TW") + assert translations.translate("Settings") == "設定" + + translations.set_language("unsupported") + assert translations.language == "en" + assert translations.translate("Settings") == "Settings" + + +def test_bundled_catalogs_have_matching_english_entries(): + catalog_dir = Path(__file__).parents[1] / "resources" / "translations" + english = json.loads((catalog_dir / "en.json").read_text(encoding="utf-8")) + traditional_chinese = json.loads( + (catalog_dir / "zh-TW.json").read_text(encoding="utf-8") + ) + + assert english + assert set(traditional_chinese) == set(english) + assert traditional_chinese["Settings"] == "設定" + untranslated_names = {"English", "Fabric"} + assert { + key + for key, value in traditional_chinese.items() + if key == value + } == untranslated_names + + formatter = Formatter() + for key, translated in traditional_chinese.items(): + source_fields = { + field for _, field, _, _ in formatter.parse(key) if field is not None + } + translated_fields = { + field + for _, field, _, _ in formatter.parse(translated) + if field is not None + } + assert translated_fields == source_fields, key diff --git a/tests/test_java_manager.py b/tests/test_java_manager.py new file mode 100644 index 0000000..7b0c505 --- /dev/null +++ b/tests/test_java_manager.py @@ -0,0 +1,15 @@ +from manager.game import JavaManager + + +def test_runtime_major_version_from_modern_version(): + assert JavaManager._runtime_major_version("21.0.8") == 21 + + +def test_runtime_major_version_from_legacy_version(): + assert JavaManager._runtime_major_version("1.8.0_51") == 8 + assert JavaManager._runtime_major_version("8u51") == 8 + + +def test_runtime_major_version_rejects_unknown_value(): + assert JavaManager._runtime_major_version(None) is None + assert JavaManager._runtime_major_version("unknown") is None diff --git a/tests/test_mac_os_arm64_runtime_install.py b/tests/test_mac_os_arm64_runtime_install.py new file mode 100644 index 0000000..9d429ef --- /dev/null +++ b/tests/test_mac_os_arm64_runtime_install.py @@ -0,0 +1,30 @@ +import logging +import sys +import tempfile +from pathlib import Path + +from core_lib.common.exception import JavaRuntimeException +from core_lib.runtime.mojang import download_java_runtimes, get_support_runtime_manifest + + +def test_mac_os_runtime_install(tmp_path): + destination = tmp_path / "java-runtime-epsilon" + logger = logging.getLogger("Launcher.CoreLib") + logger.setLevel(logging.DEBUG) + print("Installing runtime...") + + component = "java-runtime-epsilon" + + download_java_runtimes( + component, + destination + ) + + executable_name = "java" + candidates = sorted(destination.rglob(executable_name)) + + print(f"{candidates=}") + + assert any(path.is_file() for path in candidates), ( + f"Installed runtime has no {executable_name}: {destination}" + ) diff --git a/tests/test_profile_sorting.py b/tests/test_profile_sorting.py new file mode 100644 index 0000000..dc3b34d --- /dev/null +++ b/tests/test_profile_sorting.py @@ -0,0 +1,55 @@ +from datetime import datetime, timezone + +from manager.profile import ProfileSummary, sort_profile_summaries + + +def profile( + profile_id: str, + name: str, + last_used: datetime | None = None, +) -> ProfileSummary: + return ProfileSummary( + display_name=name, + id=profile_id, + name=name, + version_id="1.21.9", + version_type="release", + icon="", + last_used=last_used, + ) + + +def test_sort_profiles_by_name() -> None: + profiles = [profile("z", "Zulu"), profile("a", "alpha"), profile("b", "Beta")] + + ordered = sort_profile_summaries(profiles, "ByName") + + assert [item.id for item in ordered] == ["a", "b", "z"] + + +def test_sort_profiles_by_last_played() -> None: + profiles = [ + profile("old", "Old", datetime(2025, 1, 1, tzinfo=timezone.utc)), + profile("never", "Never"), + profile("new", "New", datetime(2026, 1, 1, tzinfo=timezone.utc)), + ] + + ordered = sort_profile_summaries(profiles, "ByLastPlayed") + + assert [item.id for item in ordered] == ["new", "old", "never"] + + +def test_last_played_profile_id_is_first_when_timestamp_is_missing() -> None: + profiles = [profile("first", "First"), profile("current", "Current")] + + ordered = sort_profile_summaries(profiles, "ByLastPlayed", "current") + + assert [item.id for item in ordered] == ["current", "first"] + + +def test_unknown_sorting_preserves_file_order() -> None: + profiles = [profile("b", "Beta"), profile("a", "Alpha")] + + ordered = sort_profile_summaries(profiles, "FutureSortingMode") + + assert [item.id for item in ordered] == ["b", "a"] diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..a8f1e29 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,171 @@ +from pathlib import Path +from enum import Enum +from typing import Literal + +import pytest +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +from manager.settings import ( + ConfigValidationError, + ModelRegistrationError, + SettingsError, + SettingsManager, +) +from manager.settings_models import AccountSettings + + +class AppSettings(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str + workers: int = Field(ge=1, le=8) + + +def write_toml(path: Path, content: str) -> Path: + path.write_text(content, encoding="utf-8") + return path + + +def test_load_registered_model(tmp_path: Path) -> None: + path = write_toml(tmp_path / "settings.toml", '[app]\nname = "demo"\nworkers = 4\n') + manager = SettingsManager(path) + manager.register("app", AppSettings) + manager.load() + + settings = manager.get("app", AppSettings) + assert settings.name == "demo" + assert settings.workers == 4 + + +def test_decorator_registration_and_validation(tmp_path: Path) -> None: + manager = SettingsManager() + + @manager.model("plugin") + class PluginSettings(BaseModel): + enabled: bool + + manager.validate({"plugin": {"enabled": True}}) + assert manager.registered_sections == ("plugin",) + + +def test_invalid_config_reports_section(tmp_path: Path) -> None: + path = write_toml(tmp_path / "settings.toml", '[app]\nname = "demo"\nworkers = 99\n') + manager = SettingsManager(path) + manager.register("app", AppSettings) + + with pytest.raises(ConfigValidationError) as error: + manager.load() + + assert "app" in error.value.errors + + +def test_unknown_section_is_rejected(tmp_path: Path) -> None: + path = write_toml(tmp_path / "settings.toml", "[unknown]\nvalue = 1\n") + manager = SettingsManager(path) + + with pytest.raises(SettingsError, match="unknown"): + manager.load() + + +def test_duplicate_registration_is_rejected() -> None: + manager = SettingsManager() + manager.register("app", AppSettings) + + with pytest.raises(ModelRegistrationError): + manager.register("app", AppSettings) + + +def test_literal_choices_are_exposed_and_validated() -> None: + class UiSettings(BaseModel): + theme: Literal["light", "dark", "system"] + + manager = SettingsManager() + manager.register("ui", UiSettings) + + assert manager.choices("ui", "theme") == ("light", "dark", "system") + with pytest.raises(ConfigValidationError): + manager.validate({"ui": {"theme": "unknown"}}) + + +def test_enum_choices_use_toml_values() -> None: + class LogLevel(str, Enum): + DEBUG = "debug" + INFO = "info" + + class LogSettings(BaseModel): + level: LogLevel + + manager = SettingsManager() + manager.register("log", LogSettings) + + assert manager.choices("log", "level") == ("debug", "info") + manager.validate({"log": {"level": "debug"}}) + + +def test_nested_model_and_nested_choices(tmp_path: Path) -> None: + class WindowSettings(BaseModel): + mode: Literal["windowed", "fullscreen"] + width: int = Field(ge=640) + + class UiSettings(BaseModel): + window: WindowSettings + + path = write_toml( + tmp_path / "settings.toml", + '[ui.window]\nmode = "fullscreen"\nwidth = 1920\n', + ) + manager = SettingsManager(path) + manager.register("ui", UiSettings) + manager.load() + + ui = manager.get("ui", UiSettings) + assert ui.window.width == 1920 + assert manager.choices("ui", "window.mode") == ("windowed", "fullscreen") + + +def test_invalid_nested_model_is_rejected() -> None: + class ChildSettings(BaseModel): + count: int = Field(ge=1) + + class ParentSettings(BaseModel): + child: ChildSettings + + manager = SettingsManager() + manager.register("parent", ParentSettings) + + with pytest.raises(ConfigValidationError) as error: + manager.validate({"parent": {"child": {"count": 0}}}) + + assert error.value.errors["parent"].errors()[0]["loc"] == ("child", "count") + + +def test_defaults_set_save_and_reload(tmp_path: Path) -> None: + class GeneralSettings(BaseModel): + language: Literal["en", "zh-TW"] = "zh-TW" + + path = tmp_path / "data" / "settings.toml" + manager = SettingsManager(path) + manager.register("general", GeneralSettings) + manager.load_defaults() + manager.set("general", {"language": "en"}) + + assert manager.save() == path + assert 'language = "en"' in path.read_text(encoding="utf-8") + + reloaded = SettingsManager(path) + reloaded.register("general", GeneralSettings) + reloaded.load() + assert reloaded.get("general", GeneralSettings).language == "en" + + +def test_account_client_id_is_a_valid_uuid() -> None: + manager = SettingsManager() + manager.register("account", AccountSettings) + manager.load_defaults() + + custom_id = "12345678-1234-5678-9abc-123456789abc" + updated = manager.set("account", {"client_id": custom_id}) + assert str(updated.client_id) == custom_id + + with pytest.raises(ValidationError): + manager.set("account", {"client_id": "not-a-client-id"}) diff --git a/window.py b/window.py index 43e795e..d964a50 100644 --- a/window.py +++ b/window.py @@ -138,6 +138,7 @@ class LauncherMainWindow(QMainWindow): # Dialog self.download_dialog = ProgressDialog(self) + self.download_dialog.setWindowTitle(self.app.tr_text("Downloads")) # Homepage self.home_page = QWidget() @@ -394,6 +395,17 @@ class LauncherMainWindow(QMainWindow): def show_info(self, widget): messagebox.info(self, self.app.tr_text("Info"), message=widget) + @Slot(dict) + def show_plain_error_text(self, data): + message = data.get("message") + content = data.get("content") + messagebox.error_with_plain_text( + self, + self.app.tr_text("Error"), + message=message, + content=content, + ) + def set_current_page(self, page: QWidget, related_button: QToolButton): self.central.setCurrentWidget(page) related_button.setFocus() @@ -438,6 +450,11 @@ class LauncherMainWindow(QMainWindow): Qt.ConnectionType.QueuedConnection, ) + widget_signal.show_plain_error_text.connect( + self.show_plain_error_text, + Qt.ConnectionType.QueuedConnection, + ) + widget_signal.show_and_print_error_message.connect( self.show_and_print_error )