From ca1eac5eb9033b7dc016527d462ecada0c45cc11 Mon Sep 17 00:00:00 2001 From: wei Date: Tue, 10 Nov 2026 22:05:18 +0800 Subject: [PATCH] Update to 0.1.5-alpha - Add profile icon and launch background customization. Apply same image limitation as official Launcher. - Add game file hash verification settings. - Update CoreLib download library hash verification handling. CoreLib update to v0.1.8 --- app.py | 3 +- constant.py | 5 +- core_lib/__init__.py | 6 +-- core_lib/common/common.py | 22 ++++---- core_lib/game/asset.py | 14 ++--- core_lib/game/authentication.py | 12 ++--- core_lib/game/library.py | 3 +- core_lib/game/library_core.py | 79 ++++++++++++++++++++++----- core_lib/game/version_info.py | 10 ++-- core_lib/qt/hack.py | 63 ++++++++++++++++++++-- manager/game.py | 36 +++++++++---- manager/profile.py | 63 ++++++++++++++++++++++ manager/settings_models.py | 7 ++- pages/launch_profile.py | 45 ++++++++-------- pages/manage_profile.py | 82 ++++++++++++++++++++++++---- pages/settings.py | 88 +++++++++++++++++++++++++++++-- pyproject.toml | 2 +- resources/translations/en.json | 15 ++++++ resources/translations/zh-TW.json | 23 +++++++- 19 files changed, 479 insertions(+), 99 deletions(-) diff --git a/app.py b/app.py index da4f4b4..60ae0c1 100644 --- a/app.py +++ b/app.py @@ -26,7 +26,7 @@ from manager.account import AccountManager from manager.game import GameManager from manager.profile import ProfileManager from manager.settings import SettingsManager -from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, PluginSettings, PageBarSettings +from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, PluginSettings, PageBarSettings, GameSettings from manager.widgets import WidgetManager from window import LauncherMainWindow @@ -72,6 +72,7 @@ class Launcher(QApplication, LauncherObject): self.settings_manager.register("account", AccountSettings) self.settings_manager.register("plugins", PluginSettings) self.settings_manager.register("page-bar", PageBarSettings) + self.settings_manager.register("game", GameSettings) if self.root_settings_dir.is_file(): self.load_settings() else: diff --git a/constant.py b/constant.py index 95fa378..46dcb65 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.1.4-alpha" +LAUNCHER_VERSION = "0.1.5-alpha" LAUNCHER_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" @@ -26,7 +26,8 @@ It aims to maintain maximum compatibility with the official Minecraft ### Credits - [PySide6](https://pypi.org/project/PySide6/): GUI framework - [Nuitka](https://nuitka.net/): Build tool -- [Minecraft Wiki](https://minecraft.fandom.com/wiki/Main_Page): Account system and launcher development reference +- [Minecraft Wiki](https://minecraft.wiki/): Account system and launcher development reference + ([Writing a launcher](https://zh.minecraft.wiki/w/Tutorial:%E7%BC%96%E5%86%99%E5%90%AF%E5%8A%A8%E5%99%A8)) \n ### Developer - [Wei](https://repo.weispace.net/wei): Main developer diff --git a/core_lib/__init__.py b/core_lib/__init__.py index 71056b9..f74361a 100644 --- a/core_lib/__init__.py +++ b/core_lib/__init__.py @@ -1,4 +1,4 @@ -__version__ = '0.1.7' +__version__ = '0.1.8' __description__ = """ A library for Python-based block game launcher. @@ -184,7 +184,7 @@ from .game.library_core import ( collect_native_artifacts, download_libraries, unzip_natives, - check_libraries_exists, + check_libraries_exists_and_verify, check_natives_exists, check_full_libraries_exists, generate_classpath, @@ -527,7 +527,7 @@ __all__ = [ "collect_native_artifacts", "download_libraries", "unzip_natives", - "check_libraries_exists", + "check_libraries_exists_and_verify", "check_natives_exists", "check_full_libraries_exists", "generate_classpath", diff --git a/core_lib/common/common.py b/core_lib/common/common.py index cce1b98..3ca65df 100644 --- a/core_lib/common/common.py +++ b/core_lib/common/common.py @@ -186,7 +186,8 @@ def generate_random_suffix(): return "".join(random.choices(string.ascii_lowercase + string.digits, k=8)) def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None, - safe_download=True, max_temp_suffix_retry=5) -> FileObject | Exception: + safe_download=True, max_temp_suffix_retry=5, + *, timeout=5, verify_hash=True) -> FileObject | Exception: """ Download the file from url :param file: File (Objected) @@ -194,6 +195,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ :param progress_callback: Callback function called with progress information :param safe_download: Download the file at temp location. If hash matches, Replace the old one with the new one :param max_temp_suffix_retry: Maximum number of retries for generating a unique temp file suffix + :param timeout: Timeout for the download request :return: """ @@ -230,7 +232,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ try: target_file.invalidate_hash_cache() # Clean cache hash try: - with requests.get(target_file.url, stream=True) as r: + with requests.get(target_file.url, stream=True, timeout=timeout) as r: r.raise_for_status() current_chunk = 0 total_bytes = r.headers.get("content-length", None) @@ -255,18 +257,18 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ finally: target_file.invalidate_hash_cache() - if target_file.expected_sha256 and not target_file.verify_sha256(): + if verify_hash and target_file.expected_sha256 and not target_file.verify_sha256(): raise HashMismatchException("sha256", target_file.sha256, target_file.expected_sha256, target_file.posix_path) - elif target_file.expected_sha1 and not target_file.verify_sha1(): + elif verify_hash and target_file.expected_sha1 and not target_file.verify_sha1(): raise HashMismatchException("sha1", target_file.sha1, target_file.expected_sha1, target_file.posix_path) - elif target_file.expected_md5 and not target_file.verify_md5(): + elif verify_hash and target_file.expected_md5 and not target_file.verify_md5(): raise HashMismatchException("md5", target_file.md5, target_file.expected_md5, target_file.posix_path) - elif target_file.expected_sha512 and not target_file.verify_sha512(): + elif verify_hash and target_file.expected_sha512 and not target_file.verify_sha512(): raise HashMismatchException("sha512", target_file.sha512, target_file.expected_sha512, target_file.posix_path) - if any([target_file.expected_sha1, target_file.expected_md5, target_file.expected_sha256]): + if verify_hash and any([target_file.expected_sha1, target_file.expected_md5, target_file.expected_sha256, target_file.expected_sha512]): logger.debug("File hash is match as the expected hash.") else: logger.warning("Hash is not checked for file: {}".format(target_file.posix_path)) @@ -297,7 +299,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[ return file def download_multiple_files(files: List[FileObject], download_callback: Callable[[str], None]=None, - max_workers=THREADED_DOWNLOAD_MAX_WORKERS, progress_callback: Callable[str]=None) \ + max_workers=THREADED_DOWNLOAD_MAX_WORKERS, progress_callback: Callable[str]=None, *, verify_hash=True) \ -> tuple[list[FileObject], list[FileObject]]: """ Download multiple files @@ -315,7 +317,7 @@ def download_multiple_files(files: List[FileObject], download_callback: Callable files_count = 0 with ThreadPoolExecutor(max_workers=max_workers) as executor: - future_to_file = {executor.submit(download_file, file): file for file in files} + future_to_file = {executor.submit(download_file, file, verify_hash=verify_hash): file for file in files} for future in as_completed(future_to_file): file = future_to_file[future] @@ -438,4 +440,4 @@ def attempt(function: Callable, exceptions: Type[Exception], except exceptions as e: log_error(f"Attempt {i} failed: {e}") - return None \ No newline at end of file + return None diff --git a/core_lib/game/asset.py b/core_lib/game/asset.py index 67b0aa6..83523ca 100644 --- a/core_lib/game/asset.py +++ b/core_lib/game/asset.py @@ -63,7 +63,7 @@ def fetch_asset_manifest(target_version_manifest: dict, raw=False) -> tuple[dict "Unable to deserialize asset response data into dictionary: {} ".format(e) ) -def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Path) -> dict: +def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Path, *, verify_hash=True) -> dict: """ Fetch the asset manifest from target version's manifest and save it. :param target_version_manifest: @@ -89,7 +89,7 @@ def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Pa with file.path.open("wb") as f: f.write(data) - if sha1 and not file.verify_sha1(sha1): + if verify_hash and sha1 and not file.verify_sha1(sha1): raise HashMismatchException( "sha1", file.sha1, @@ -286,7 +286,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict] if old_asset.path.stat().st_size == size: logger.debug("Asset {} already exists. (no_hash_check=True)".format(target)) return True, None - elif sha1 and old_asset.verify("sha1", sha1): + elif not no_hash_check and sha1 and old_asset.verify("sha1", sha1): logger.debug("Asset {} already exists.".format(target)) return True, None @@ -294,7 +294,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict] return True, destination fails , _ = download_multiple_files(assets, progress_callback=progress_callback, - max_workers=ASSET_DOWNLOAD_MAX_WORKERS) + max_workers=ASSET_DOWNLOAD_MAX_WORKERS, verify_hash=not no_hash_check) download_ok = len(fails) == 0 @@ -311,7 +311,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict] return fails # Use thread pool to handle copy file process - with ThreadPoolExecutor(max_workers=ASSET_DOWNLOAD_MAX_WORKERS) as executor: + with ThreadPoolExecutor(max_workers=ASSET_DOWNLOAD_MAX_WORKERS, verify_hash=not no_hash_check) as executor: futures = [ executor.submit( __worker, @@ -395,7 +395,7 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha if index_path.is_file(): try: - if not index_sha1 or FileObject(index_path).verify_sha1(index_sha1): + if no_hash_check or not index_sha1 or FileObject(index_path).verify_sha1(index_sha1): cached = json.loads(index_path.read_text(encoding="utf-8")) if isinstance(cached, dict) and isinstance(cached.get("objects"), dict) and cached["objects"]: @@ -405,7 +405,7 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha logger.warning("Unable to read cached asset index: %s", index_path) if asset_manifest is None: - asset_manifest = fetch_and_save_asset_manifest(manifest, index_path) + asset_manifest = fetch_and_save_asset_manifest(manifest, index_path, verify_hash=not no_hash_check) # Download assets files assets, legacy_assets = collect_assets_from_manifest( diff --git a/core_lib/game/authentication.py b/core_lib/game/authentication.py index 2e58504..47441a0 100644 --- a/core_lib/game/authentication.py +++ b/core_lib/game/authentication.py @@ -11,7 +11,7 @@ from typing import Callable import requests from core_lib.common.exception import LauncherException, AuthenticationSessionException, AuthenticationConnectException, \ - AuthenticationException, LauncherHTTPException + AuthenticationException MICROSOFT_DEVICE_CODE_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode" MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token" @@ -28,8 +28,8 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho Handle authentication exceptions :param stage: :param request_handler: - :param request_type: Set this will change exception type when an error occurs. ("without_token" for process that - don't use token, "with_token" for process that use token. If with token, exception usually throw + :param request_type: Set this will change the exception type when an error occurs. ("without_token" for processes that + don't use token, "with_token" for processes that use token. If with token, exception usually throws AuthenticationSessionException. If not, throw AuthenticationException instead) :return: """ @@ -58,8 +58,8 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho except (TypeError, ValueError): pass - # Below are the xsts error code suggestions. Why return that value (error is integer not string) ? - # Maybe it makes international support more easily? + # Below are the xsts error code suggestions. Why return that value (error is integer, not string)? + # Maybe it makes international support more easy? xsts_suggestions = { 2148916233: "This Microsoft account does not have an Xbox profile. Sign in at xbox.com and create one, then try again.", 2148916235: "Xbox Live is not available for this account's country or region.", @@ -74,7 +74,7 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho ) from e server_message = response_data.get("Message") or response_data.get("error_description") - # This suggestions can make user happy instead of seeing an HTTP error code + # These suggestions can make user happy instead of seeing an HTTP error code suggestions = { 400: "The authentication request or session was rejected.", 401: "The login session is invalid or expired. Sign in again.", diff --git a/core_lib/game/library.py b/core_lib/game/library.py index c0e3813..cf66297 100644 --- a/core_lib/game/library.py +++ b/core_lib/game/library.py @@ -170,7 +170,8 @@ def get_natives_platform_info(): return platform_key_name, platform_rule_name, platform_arch_type -def is_native_allowed(lib_name, platform_key_name, platform_arch_type, unspecified_arch_policy: str = "x86_64") -> bool: +def is_native_allowed(lib_name, platform_key_name, platform_arch_type, + unspecified_arch_policy: str = "x86_64") -> bool: # Parse native key match = re.search(r":(natives-[^:]+)$", lib_name) diff --git a/core_lib/game/library_core.py b/core_lib/game/library_core.py index 45b44ff..aea145a 100644 --- a/core_lib/game/library_core.py +++ b/core_lib/game/library_core.py @@ -2,16 +2,17 @@ import logging import re import zipfile from pathlib import Path, PureWindowsPath -from typing import Callable +from typing import Callable, Literal 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 -from ..common.common import get_platform_info, FileObject, download_multiple_files, unzip, is_valid_zipfile +from ..common.common import get_platform_info, FileObject, download_multiple_files, unzip, is_valid_zipfile, \ + SUPPORTED_HASH_ALGORITHMS from .version_info import find_useful_part_in_specific_version_manifest from ..common.exception import UnsupportedPlatformException, NativeResolveException, DependencyException, \ - VersionDataKeyNotFoundException, DownloadException + VersionDataKeyNotFoundException, DownloadException, HashMismatchException logger = logging.getLogger("Launcher.CoreLib") @@ -234,7 +235,7 @@ def collect_native_artifacts(specific_version_manifest): return items -def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, float], None] = None) \ +def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, float], None] = None, *, verify_hash=True) \ -> tuple[list[FileObject], list[FileObject]]: """ Download libraries from a list that contains artifacts @@ -267,13 +268,17 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, full_path, url=url, sha1=sha1, + sha256=sha256, + sha512=sha512, ) if sha1 is None: logger.warning(f"File {full_path} has no SHA1 hash.") if file.exists: - if sha1 is not None: + if not verify_hash: + valid = full_path.is_file() + elif sha1 is not None: valid = file.verify("sha1", sha1) elif sha256 is not None: valid = file.verify("sha256", sha256) @@ -290,7 +295,7 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, files.append(file) - fails, finished = download_multiple_files(files, progress_callback=progress_callback) + fails, finished = download_multiple_files(files, progress_callback=progress_callback, verify_hash=verify_hash) successes.extend(finished) return fails, successes @@ -328,16 +333,32 @@ def unzip_natives(filtered, libraries_dir, destination: Path): logger.debug(f"Unzipped {full_path}.") -def check_libraries_exists(manifest: dict, libraries_dir: Path): +def check_libraries_exists_and_verify(manifest, libraries_dir, verify_hash=True, + allow_algorithms=None, *, throw_error_if_missing_hash=False): """ - Check if libraries are present in the libraries directory + Check if libraries are present in the libraries directory and verify their hash (if required) :param manifest: :param libraries_dir: + :param verify_hash: Whether to verify the hash of the library. Defaults to True. + :param throw_error_if_missing_hash: Whether to throw an error if a library is missing a hash. Defaults to False. + (Only working when verify_hash is True) + :param allow_algorithms: The allowed algorithms to use for hash verification. Defaults to SUPPORTED_HASH_ALGORITHMS + (in corelib.common.common) :return: not_found: list """ libraries = manifest.get("libraries", []) + if allow_algorithms is None: + allow_algorithms = SUPPORTED_HASH_ALGORITHMS + + if verify_hash and not allow_algorithms: + raise ValueError("algorithm must be provided if verify_hash is True") + + for alog in allow_algorithms or []: + if alog not in SUPPORTED_HASH_ALGORITHMS: + raise ValueError(f"Unsupported algorithm: {alog}") + if not libraries: raise VersionDataKeyNotFoundException( "Libraries not found in manifest.", @@ -379,12 +400,43 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path): logger.warning(f"Artifact {name} are not valid. Skipping...") continue - relative_path = artifact.get("path") + relative_path = artifact["path"] # Is safe because generate_formatted_artifact_with_name will check + # the "path" key. full_path = libraries_dir / Path(relative_path) if not full_path.is_file() or not full_path.exists(): logger.debug(f"Artifact {name} missing.") not_found.append(full_path) + continue + + if verify_hash: + expected = None + used_alog = None + + # Get expected hash + for alog in allow_algorithms or []: + expected = artifact.get(alog, None) + if expected: + used_alog = alog + break + + # Verify hash + if used_alog: + f = FileObject(full_path) + if not f.verify(used_alog, expected): + logger.debug(f"Hash mismatch for {full_path} with algorithm {used_alog}") + not_found.append(full_path) + continue + else: + logger.debug(f"Hash match for {full_path} with algorithm {used_alog}") + else: + if throw_error_if_missing_hash: + raise VersionDataKeyNotFoundException( + f"Library {name} does not provide any hash that type is allowed in {allow_algorithms}" + ) + + # Show warning if there's no support algorithm in the artifact + logger.warning(f"Library {name} does not provide any hash that type is allowed in {allow_algorithms}") return not_found @@ -518,16 +570,17 @@ def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *, - features: dict | None = None) -> bool: + features=None, verify_hash=True,) -> bool: natives_exist = check_natives_exists( manifest, libraries_dir, natives_dir, features=features, ) - missing_libraries = check_libraries_exists( + missing_libraries = check_libraries_exists_and_verify( manifest, libraries_dir, + verify_hash=verify_hash, ) return natives_exist and not missing_libraries @@ -604,7 +657,7 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives progress_callback: Callable[[str, float], None] = None, redownload_callback: Callable[ [list[FileObject]], tuple[bool, list[FileObject]]] = None, *, - features: dict | None = None) -> None: + features: dict | None = None, verify_hash=True) -> None: natives_dir = locate_natives_extract_dir_by_manifest(manifest, default_natives_dir, features=features) # libraries libraries = collect_library_artifacts(manifest) @@ -621,7 +674,7 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives ) # Start download - fails, successes = download_libraries(full, libraries_dir, progress_callback=progress_callback) + fails, successes = download_libraries(full, libraries_dir, progress_callback=progress_callback, verify_hash=verify_hash) download_ok = len(fails) == 0 diff --git a/core_lib/game/version_info.py b/core_lib/game/version_info.py index 5f77cc0..da717f4 100644 --- a/core_lib/game/version_info.py +++ b/core_lib/game/version_info.py @@ -517,7 +517,7 @@ def fetch_and_save_version_manifest(dest: Path, target_version: str=None, root_m return save_version_manifest(data, dest, sha1) def download_core_file(manifest: dict, destination: Path, is_server=False, raise_for_null_hash=True, - progress_callback: Callable[[str, float], None]=None) -> FileObject: + progress_callback: Callable[[str, float], None]=None, *, verify_hash=True) -> FileObject: """ Download core file from version manifest. :param manifest: @@ -532,7 +532,7 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise destination.parent.mkdir(parents=True, exist_ok=True) - if sha1 is None and raise_for_null_hash: + if verify_hash and sha1 is None and raise_for_null_hash: raise VersionDataKeyNotFoundException( "Core file hash is missing. Enable \"raise_for_null_hash\" flag to ignore this exception.\n" ) @@ -541,10 +541,10 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise file = FileObject(destination, url=url, sha1=sha1) - if file.exists and file.verify("sha1", sha1): + if destination.is_file() and (not verify_hash or file.verify("sha1", sha1)): logger.info(f"Client existed and sha1 matches.") elif url is not None: - download_file(file, progress_callback=progress_callback) + download_file(file, progress_callback=progress_callback, verify_hash=verify_hash) elif not url: raise VersionDataKeyNotFoundException( "Core file url is None. Unable to download it." @@ -567,7 +567,7 @@ def check_core_file_exists_and_verify(manifest: dict, core_file_path: Path, """ _, _, downloads, _, _, _, _ = find_useful_part_in_specific_version_manifest(manifest) - if not core_file_path.exists(): + if not core_file_path.exists() or not core_file_path.is_file(): logger.warning(f"Core file \"{core_file_path.as_posix()}\" does not exist.") return False diff --git a/core_lib/qt/hack.py b/core_lib/qt/hack.py index 8475eb5..eecb142 100644 --- a/core_lib/qt/hack.py +++ b/core_lib/qt/hack.py @@ -1,8 +1,9 @@ import base64 +import binascii from pathlib import Path -from PySide6.QtCore import QCoreApplication, QThread, QSize, Qt -from PySide6.QtGui import QScreen, QPixmap, QPainter, QPalette, QIcon, QColor, QImage +from PySide6.QtCore import QCoreApplication, QThread, QSize, Qt, QBuffer, QIODevice +from PySide6.QtGui import QScreen, QPixmap, QPainter, QPalette, QIcon, QColor, QImage, QImageReader from PySide6.QtWidgets import QMainWindow, QApplication, QWidget, QDialog @@ -124,4 +125,60 @@ def data_url_to_qt_image(data_url: str) -> QImage: return image -# ======================== AI generated END ======================== \ No newline at end of file +def base64_to_qicon(value: str) -> QIcon: + if value.startswith("data:"): + header, separator, value = value.partition(",") + if not separator or ";base64" not in header: + return QIcon() + + try: + data = base64.b64decode("".join(value.split()), validate=True) + except (ValueError, binascii.Error): + return QIcon() + + pixmap = QPixmap() + if not pixmap.loadFromData(data): + return QIcon() + + return QIcon(pixmap) + +def is_qt_supported_image(path: Path) -> tuple[bool, str | None]: + if not path.is_file(): + return False, None + + reader = QImageReader(str(path)) + reader.setDecideFormatFromContent(True) + + + if not reader.canRead(): + return False, None + image_format = bytes(reader.format()).decode("ascii").lower() or None + return not reader.read().isNull(), image_format + +def image_to_data_url(path: Path, mime_type: str) -> str: + encoded = base64.b64encode(path.read_bytes()).decode("ascii") + return f"data:{mime_type};base64,{encoded}" + + +def prepare_profile_icon(path: Path) -> tuple[str, bool]: + """Validate and encode a square profile icon as a 128px PNG.""" + reader = QImageReader(str(path)) + reader.setDecideFormatFromContent(True) + reader.setAutoTransform(True) + image = reader.read() + if image.isNull(): + raise ValueError("Image format is not supported.") + if image.width() != image.height() or image.width() < 128: + raise ValueError("Profile icons must be square and at least 128 x 128 pixels.") + resized = image.width() > 128 + if resized: + image = image.scaled(128, 128, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation) + buffer = QBuffer() + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + if not image.save(buffer, "PNG"): + raise ValueError("Unable to encode profile icon.") + encoded = base64.b64encode(bytes(buffer.data())).decode("ascii") + return f"data:image/png;base64,{encoded}", resized + +# ======================== AI generated END ======================== diff --git a/manager/game.py b/manager/game.py index a84471c..2211750 100644 --- a/manager/game.py +++ b/manager/game.py @@ -33,6 +33,7 @@ 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 from manager.profile import LaunchProfile, ProfileManager +from manager.settings_models import GameSettings from manager.widgets import SelectPathRequest, AskForRequest, SignalTransferItem MAX_DOWNLOAD_ATTEMPTS = 3 @@ -883,6 +884,9 @@ class GameFileManager: "download_assets": self.download_assets, } + def _verify_download_hash(self) -> bool: + return self.app.settings_manager.get("game", GameSettings).verify_hash_on_download + def get_manifest(self, target_version: str, manifest: dict | None, failed_message: str, vanilla: bool=False) -> dict | None: @@ -925,8 +929,10 @@ class GameFileManager: "Downloading dependencies..." ) + verify_hash = self._verify_download_hash() try: download_core_file(manifest, core_file_path, + verify_hash=verify_hash, raise_for_null_hash=True, progress_callback=callback) except Exception as e: @@ -953,10 +959,12 @@ class GameFileManager: "Downloading dependencies..." ) + verify_hash = self._verify_download_hash() try: download_full_libraries(manifest, libraries_dir, natives_dir, progress_callback=callback, - redownload_callback=self.redownload_files) + verify_hash=verify_hash, + redownload_callback=lambda files: self.redownload_files(files, verify_hash=verify_hash)) except Exception as e: self.widget_mgr.download_signal.failed.emit(task_id, str(e)) self.widget_mgr.signal.show_error_message.emit( @@ -988,16 +996,17 @@ class GameFileManager: "Downloading assets" ) + verify_hash = self._verify_download_hash() try: fails = download_assets( manifest, assets_dir, - no_hash_check=True, + no_hash_check=not verify_hash, progress_callback=callback, launcher_root=self.app.work_dir, ) - result, fails = self.redownload_files(fails) + result, fails = self.redownload_files(fails, verify_hash=verify_hash) if not result: if allow_missing: @@ -1048,7 +1057,7 @@ class GameFileManager: return thread - def redownload_files(self, files: list[FileObject]) -> tuple[bool, list[FileObject]]: + def redownload_files(self, files: list[FileObject], *, verify_hash=True) -> tuple[bool, list[FileObject]]: if not files: return True, [] @@ -1084,7 +1093,7 @@ class GameFileManager: self.widget_mgr.download_signal.log.emit(f"Attempt {retry_time}/{MAX_DOWNLOAD_ATTEMPTS}") - fails, successes = download_multiple_files(pending, + fails, successes = download_multiple_files(pending, verify_hash=verify_hash, progress_callback=callback) for file in successes: @@ -1191,11 +1200,15 @@ class GameFileManager: ) update_stage("downloading the Minecraft client") - if not check_core_file_exists_and_verify(vanilla, client_jar): + verify_hash = self._verify_download_hash() + if not (client_jar.is_file() and ( + not verify_hash or 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, + verify_hash=verify_hash, ) update_stage("copying embedded artifacts") @@ -1203,9 +1216,11 @@ class GameFileManager: update_stage("downloading installer dependencies") files = forge_like.collect_install_dependencies(plan, libraries_dir) - failures, _ = download_multiple_files(files, progress_callback=progress_callback) + failures, _ = download_multiple_files( + files, progress_callback=progress_callback, verify_hash=verify_hash, + ) if failures: - success, failures = self.redownload_files(failures) + success, failures = self.redownload_files(failures, verify_hash=verify_hash) if not success or failures: raise LoaderInstallError("Unable to download installer dependencies.") @@ -1285,6 +1300,7 @@ class LaunchManager: self.app = app self.manifest_mgr = manifest_manager self.widget_mgr = app.widget_manager + self.settings_mgr = app.settings_manager self.java_mgr = java_manager self.game_file_mgr = game_file_manager self.account_mgr = account_manager @@ -1383,7 +1399,9 @@ class LaunchManager: ) # Libraries - if not check_full_libraries_exists(version_manifest, libraries_dir, natives_dir): + verify_hash = self.settings_mgr.get("game", GameSettings).verify_hash_on_launch + if not check_full_libraries_exists(version_manifest, libraries_dir, + natives_dir, verify_hash=verify_hash): request = GameFileDownloadRequest( "download_libraries", (version_id, libraries_dir, natives_dir, version_manifest) diff --git a/manager/profile.py b/manager/profile.py index f998030..330c7ef 100644 --- a/manager/profile.py +++ b/manager/profile.py @@ -3,13 +3,17 @@ Profile Manager A Minecraft profile manager that completely support official Minecraft Launcher. """ +import base64 import copy from dataclasses import dataclass from pathlib import Path +from typing import Callable from PySide6.QtCore import QObject, Signal from datetime import datetime, timezone +from PySide6.QtGui import QIcon + from core_lib.common.exception import ProfileException, ProfileLoadException, ProfileSaveException from core_lib.game.profile import read_profile_file, is_profiles_valid, \ get_profile_sample, create_or_save_profile_file, list_profiles as list_profiles_raw, convert_profile_data_to_object, \ @@ -17,6 +21,7 @@ from core_lib.game.profile import read_profile_file, is_profiles_valid, \ get_current_profile_id, set_current_profile_id, remove_profile, duplicate_profile, \ set_last_used_time from core_lib.game.version_info import LATEST_VERSION_ALIASES +from core_lib.qt.hack import is_qt_supported_image, image_to_data_url, base64_to_qicon, prepare_profile_icon from manager.widgets import AskForRequest DEFAuLT_PROFILE_RELATIVE_PATH = Path("launcher_profiles.json") @@ -592,6 +597,51 @@ class ProfileManager(QObject): ) return False + def update_profile_icon(self, profile_id: str, filepath: Path, format_checker: Callable[[Path], * + tuple[bool, str | None]]=is_qt_supported_image): + if not self.is_loaded: + success, _ = self.load() + + if not success: + return False + + if profile_id is not None and not self.contains(profile_id, show_error=True): + return False + + if not filepath.exists() or not filepath.is_file(): + self.widget_manager.show_error(self.app.tr_text("Image file does not exist or is not a file")) + return False + + try: + result = None + file_format: str | None = None + if callable(format_checker): + result, file_format = format_checker(filepath) + if not result: + self.widget_manager.show_error(self.app.tr_text("Image format is not supported.")) + return False + + if file_format is None: + raise ValueError(self.app.tr_text("Image format is not supported.")) + + new_icon, resized = prepare_profile_icon(filepath) + if resized: + self.widget_manager.signal.show_info_message.emit(self.app.tr_text( + "This image exceeds 128 x 128 pixels and will be resized to 128 x 128." + )) + request = UpdateProfileRequest( + icon=new_icon + ) + + if not self.update_profile(profile_id, request): + return False + + self.profiles_changed.emit() + return True + except Exception as e: + self.widget_manager.signal.show_error_message.emit(self.app.tr_text(str(e))) + return False + def update_last_used_time( self, profile_id: str, @@ -803,3 +853,16 @@ def sort_profile_summaries( ordered.sort(key=lambda profile: profile.id != current_profile_id) return ordered + + +def _profile_icon(value: str, icon_dir: Path) -> QIcon: + icon = base64_to_qicon(value) + if icon.isNull() and not value.startswith("data:"): + try: + if value and Path(value).is_file(): + icon = QIcon(value) + except (OSError, ValueError): + pass + if icon.isNull(): + icon = QIcon(str(Path(icon_dir, "profile_default.png"))) + return icon diff --git a/manager/settings_models.py b/manager/settings_models.py index aa02e2e..1a07320 100644 --- a/manager/settings_models.py +++ b/manager/settings_models.py @@ -33,6 +33,7 @@ class AppearanceSettings(WarnExtraModel): model_config = ConfigDict() theme: str = "system" + launch_background: str = "" @field_validator("theme") @classmethod @@ -83,4 +84,8 @@ class PluginSettings(WarnExtraModel): class PageBarSettings(WarnExtraModel): focus_at_after_restart: bool = False last_focused_page: str = "" - page_bar_position: Literal["left", "right", "top", "bottom"] = "left" \ No newline at end of file + page_bar_position: Literal["left", "right", "top", "bottom"] = "left" + +class GameSettings(WarnExtraModel): + verify_hash_on_download: bool = True + verify_hash_on_launch: bool = True diff --git a/pages/launch_profile.py b/pages/launch_profile.py index c8e255c..e587a7f 100644 --- a/pages/launch_profile.py +++ b/pages/launch_profile.py @@ -8,8 +8,9 @@ from PySide6.QtWidgets import (QWidget, QVBoxLayout, QLabel, QHBoxLayout, QPushB from core_lib.qt.item_button import ItemButton from manager.game import LaunchManager, LaunchResult from core_lib.game.version_info import LATEST_VERSION_ALIASES -from manager.profile import ProfileSummary, LaunchProfile, ProfileManager +from manager.profile import ProfileSummary, LaunchProfile, ProfileManager, _profile_icon from manager.widgets import AskForRequest, WidgetManager +from manager.settings_models import AppearanceSettings from pages.process_log import ProcessLogWindow @@ -68,16 +69,8 @@ class ProfileButton(QFrame): self.name_label.setText(profile.display_name) self.version_label.setText(profile.version_id) - icon_path = profile.icon - - if not isinstance(icon_path, Path): - icon_path = Path(icon_path) - - if not icon_path.exists() or not icon_path.is_file(): - # Use default - icon_path = Path(self.app.icon_dir, "profile_default.png") - - self.icon_label.setPixmap(QIcon(icon_path.as_posix()).pixmap(36, 36)) + icon = profile.icon + self.icon_label.setPixmap(_profile_icon(icon, self.app.icon_dir).pixmap(36, 36)) def set_popup_open(self, opened: bool) -> None: self.arrow_label.setText("▴" if opened else "▾") @@ -121,8 +114,8 @@ class ProfileListItem(ItemButton): layout.addLayout(text_layout, 1) self.clicked.connect(lambda: self.selected.emit(self.profile)) - def set_icon(self, icon_path: Path) -> None: - self.icon_label.setPixmap(QIcon(icon_path.as_posix()).pixmap(36, 36)) + def set_icon(self, icon: QPixmap) -> None: + self.icon_label.setPixmap(icon) class ProfilePopup(QFrame): profile_selected = Signal(object) @@ -166,18 +159,9 @@ class ProfilePopup(QFrame): self.clean_profiles() for profile in profiles: - icon_path = profile.icon - - if not isinstance(icon_path, Path): - icon_path = Path(icon_path) - - if not icon_path.exists() or not icon_path.is_file(): - # Use default - icon_path = Path(self.app.icon_dir, "profile_default.png") - item = ProfileListItem(profile, self) item.selected.connect(self.profile_selected) - item.set_icon(icon_path) + item.set_icon(_profile_icon(profile.icon, self.app.icon_dir).pixmap(36, 36)) self.content_layout.addWidget(item) def clean_profiles(self) -> None: @@ -293,11 +277,26 @@ class LaunchProfilePage(QWidget): self.load_profiles, ) + def showEvent(self, event): + super().showEvent(event) + appearance = self.app.settings_manager.get("appearance", AppearanceSettings) + self.profile_frame.set_background( + appearance.launch_background, + Path(self.app.icon_dir, "profile_default.png"), + ) + class ProfileBackgroundFrame(QFrame): def __init__(self, image_path, parent=None): super().__init__(parent) self.background = QPixmap(str(image_path)) + def set_background(self, path, default_path): + background = QPixmap(str(path)) if path else QPixmap() + if background.isNull(): + background = QPixmap(str(default_path)) + self.background = background + self.update() + def paintEvent(self, event): super().paintEvent(event) diff --git a/pages/manage_profile.py b/pages/manage_profile.py index 5b1630b..73f87ec 100644 --- a/pages/manage_profile.py +++ b/pages/manage_profile.py @@ -3,15 +3,16 @@ from pathlib import Path from typing import Callable from PySide6.QtCore import Qt, QUrl, Signal -from PySide6.QtGui import QDesktopServices, QIcon +from PySide6.QtGui import QDesktopServices, QImageReader from PySide6.QtWidgets import ( QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox, QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget, ) +from core_lib.qt.hack import base64_to_qicon, prepare_profile_icon from core_lib.qt.item_button import ItemButton -from manager.profile import ProfileDetail, ProfileManager, ProfileSummary, UpdateProfileRequest +from manager.profile import ProfileDetail, ProfileManager, ProfileSummary, UpdateProfileRequest, _profile_icon from manager.game import AvailableVersion from pages.add_modded_version import AddModdedVersionDialog @@ -41,12 +42,9 @@ class ManageProfileItem(ItemButton): layout.setContentsMargins(12, 8, 12, 8) layout.setSpacing(12) - icon_path = Path(profile.icon) - if not icon_path.is_file(): - icon_path = Path(app.icon_dir, "profile_default.png") icon = QLabel() icon.setFixedSize(40, 40) - icon.setPixmap(QIcon(icon_path.as_posix()).pixmap(36, 36)) + icon.setPixmap(_profile_icon(profile.icon, app.icon_dir).pixmap(36, 36)) icon.setAlignment(Qt.AlignmentFlag.AlignCenter) texts = QVBoxLayout() @@ -91,6 +89,7 @@ class ManageProfileItem(ItemButton): menu.exec(global_position) + class ManageProfilePage(QWidget): """ Profile manage page @@ -109,6 +108,7 @@ class ManageProfilePage(QWidget): self.app = app self.profile_manager: ProfileManager = app.profile_manager self.manifest_manager = app.game_manager.manifest + self.widget_manager = app.widget_manager self.selected_profile_id: str | None = None self.profile_items: dict[str, ManageProfileItem] = {} self.version_options: list[AvailableVersion] = [] @@ -157,7 +157,26 @@ class ManageProfilePage(QWidget): form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) form.setVerticalSpacing(12) + # Icon & Name + self.profile_icon = QLabel() + self.profile_icon.setFixedSize(64, 64) + self.profile_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) self.name_edit = QLineEdit() + self.replace_icon_btn = QPushButton(self.app.tr_text("Replace Icon")) + self.reset_icon_btn = QPushButton(self.app.tr_text("Reset Icon")) + self.reset_icon_btn.clicked.connect(self._reset_icon) + + profile_head_h_layout = QHBoxLayout() + profile_head_v_layout = QVBoxLayout() + + profile_head_v_layout.addWidget(self.name_edit) + icon_actions = QHBoxLayout() + icon_actions.addWidget(self.replace_icon_btn) + icon_actions.addWidget(self.reset_icon_btn) + profile_head_v_layout.addLayout(icon_actions) + profile_head_h_layout.addWidget(self.profile_icon) + profile_head_h_layout.addLayout(profile_head_v_layout) + self.version_dropdown = QComboBox() self.version_dropdown.setObjectName("Dropdown") self.version_dropdown.setSizePolicy( @@ -172,22 +191,22 @@ class ManageProfilePage(QWidget): self.type_dropdown.setObjectName("Dropdown") self.game_dir_edit = QLineEdit() self.java_args_edit = QLineEdit() - self.icon_edit = QLineEdit() + self.icon_edit = QLineEdit(self.editor) + self.icon_edit.hide() self.width_spin = self._dimension_spin() self.height_spin = self._dimension_spin() - form.addRow(self.app.tr_text("Profile name"), self.name_edit) form.addRow(self.app.tr_text("Type"), self.type_dropdown) form.addRow(self.app.tr_text("Version"), self.version_dropdown) form.addRow(self.app.tr_text("Game directory"), self.game_dir_edit) form.addRow(self.app.tr_text("Java arguments"), self.java_args_edit) - form.addRow(self.app.tr_text("Icon"), self.icon_edit) resolution = QHBoxLayout() resolution.addWidget(self.width_spin) resolution.addWidget(QLabel("×")) resolution.addWidget(self.height_spin) form.addRow(self.app.tr_text("Resolution"), resolution) + editor_layout.addLayout(profile_head_h_layout) editor_layout.addLayout(form) file_actions = QHBoxLayout() @@ -228,6 +247,7 @@ class ManageProfilePage(QWidget): self.type_dropdown.currentIndexChanged.connect(self._filter_versions) self.profile_manager.profiles_changed.connect(self.refresh_profiles) + self.replace_icon_btn.clicked.connect(self._replace_icon) self.app.apply_qss(Path("manage_profile.qss"), self.setStyleSheet) self._load_type_dropdown() self.refresh_profiles() @@ -361,6 +381,9 @@ class ManageProfilePage(QWidget): def _set_detail(self, profile: ProfileDetail) -> None: self.name_edit.setText(profile.name) + profile_icon = _profile_icon(profile.icon, self.app.icon_dir) + self.profile_icon.setPixmap(profile_icon.pixmap(64, 64)) + option = next( (item for item in self.version_options if item.id == profile.version_id), None, @@ -611,3 +634,44 @@ class ManageProfilePage(QWidget): cleanup() raise return cleanup + + def _reset_icon(self): + if self.selected_profile_id is None: + return + self.icon_edit.clear() + self.profile_icon.setPixmap(_profile_icon("", self.app.icon_dir).pixmap(64, 64)) + + def _replace_icon(self): + profile_id = self.selected_profile_id + + if not profile_id or self.profile_manager.get_profile(profile_id) is None: + self.widget_manager.signal.show_warning_message.emit( + self.app.tr_text("Select a profile before replacing the icon") + ) + return + + formats = " ".join( + "*." + bytes(fmt).decode("ascii") + for fmt in QImageReader.supportedImageFormats() + ) + filename, _ = QFileDialog.getOpenFileName( + self, self.app.tr_text("Replace Icon"), "", + self.app.tr_text("Images") + f" ({formats});;" + self.app.tr_text("All files") + " (*)", + ) + if not filename: + return + try: + path = Path(filename) + value, resized = prepare_profile_icon(path) + icon = base64_to_qicon(value) + if icon.isNull(): + raise ValueError(self.app.tr_text("Image format is not supported.")) + except (OSError, ValueError) as error: + self.widget_manager.signal.show_error_message.emit(self.app.tr_text(str(error))) + return + if resized: + self.widget_manager.signal.show_info_message.emit(self.app.tr_text( + "This image exceeds 128 x 128 pixels and will be resized to 128 x 128." + )) + self.icon_edit.setText(value) + self.profile_icon.setPixmap(icon.pixmap(64, 64)) diff --git a/pages/settings.py b/pages/settings.py index 80a2502..6080212 100644 --- a/pages/settings.py +++ b/pages/settings.py @@ -2,8 +2,9 @@ import uuid from pathlib import Path from PySide6.QtCore import Qt +from PySide6.QtGui import QImageReader, QPixmap from PySide6.QtWidgets import ( - QComboBox, + QComboBox, QCheckBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, @@ -18,7 +19,7 @@ from PySide6.QtWidgets import ( from constant import LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD, \ LAUNCHER_DESCRIPTION_MARKDOWN, LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD from core_lib.qt import messagebox -from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings +from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, GameSettings from pages.plugins import PluginsDialog LANGUAGE_LABELS = { @@ -104,6 +105,7 @@ class SettingsPage(QWidget): self.main_page = self._create_main_page() self.general_page = self._create_general_page() + self.game_page = self._create_game_page() self.appearance_page = self._create_appearance_page() self.account_page = self._create_account_page() self.about_page = self._create_about_page() @@ -111,6 +113,7 @@ class SettingsPage(QWidget): for page in ( self.main_page, self.general_page, + self.game_page, self.appearance_page, self.account_page, self.about_page, @@ -147,12 +150,14 @@ class SettingsPage(QWidget): self.main_page = self._create_main_page() self.general_page = self._create_general_page() + self.game_page = self._create_game_page() self.appearance_page = self._create_appearance_page() self.account_page = self._create_account_page() self.about_page = self._create_about_page() for page in ( self.main_page, self.general_page, + self.game_page, self.appearance_page, self.account_page, self.about_page, @@ -189,6 +194,7 @@ class SettingsPage(QWidget): pages = ( (tr("General"), tr("Language and launcher directories"), "general_page"), + (tr("Game"), tr("Game file hash verification"), "game_page"), (tr("Appearance"), tr("Launcher theme"), "appearance_page"), (tr("Account"), tr("Microsoft authentication settings"), "account_page"), (tr("About"), tr("Version and project information"), "about_page"), @@ -239,6 +245,19 @@ class SettingsPage(QWidget): page.content_layout.addWidget(self.language_combo) return page + def _create_game_page(self) -> QWidget: + tr = self.app.tr_text + page = SettingsSubPage(tr("Game"), self._go_back) + current = self.settings.get("game", GameSettings) + self.verify_hash_on_download = QCheckBox(tr("Verify file hashes when downloading")) + self.verify_hash_on_download.setChecked(current.verify_hash_on_download) + self.verify_hash_on_launch = QCheckBox(tr("Verify library hashes before launch")) + self.verify_hash_on_launch.setChecked(current.verify_hash_on_launch) + for checkbox in (self.verify_hash_on_download, self.verify_hash_on_launch): + checkbox.toggled.connect(self._mark_settings_dirty) + page.content_layout.addWidget(checkbox) + return page + def _create_appearance_page(self) -> QWidget: tr = self.app.tr_text page = SettingsSubPage(tr("Appearance"), self._go_back) @@ -260,8 +279,67 @@ class SettingsPage(QWidget): help_label.setObjectName("settingsHelpText") help_label.setWordWrap(True) page.content_layout.addWidget(help_label) + page.content_layout.addWidget(QLabel(tr("Launch page background"))) + self.launch_background = current.launch_background + self.background_preview = QLabel() + self.background_preview.setFixedSize(320, 180) + self.background_preview.setAlignment(Qt.AlignmentFlag.AlignCenter) + page.content_layout.addWidget(self.background_preview) + self._update_background_preview() + background_actions = QHBoxLayout() + choose_background = QPushButton(tr("Choose background image")) + choose_background.clicked.connect(self._choose_launch_background) + reset_background = QPushButton(tr("Restore default background")) + reset_background.clicked.connect(self._reset_launch_background) + background_actions.addWidget(choose_background) + background_actions.addWidget(reset_background) + background_actions.addStretch() + page.content_layout.addLayout(background_actions) return page + def _update_background_preview(self): + path = self.launch_background or str(Path(self.app.icon_dir, "profile_default.png")) + pixmap = QPixmap(path) + self.background_preview.setPixmap(pixmap.scaled( + 320, 180, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + )) + + def _choose_launch_background(self): + formats = " ".join("*." + bytes(fmt).decode("ascii") + for fmt in QImageReader.supportedImageFormats()) + filename, _ = QFileDialog.getOpenFileName( + self, self.app.tr_text("Choose background image"), "", + self.app.tr_text("Images") + f" ({formats})", + ) + if not filename: + return + reader = QImageReader(filename) + reader.setDecideFormatFromContent(True) + reader.setAutoTransform(True) + image = reader.read() + if image.isNull(): + QMessageBox.warning(self, self.app.tr_text("Settings error"), + self.app.tr_text("Image format is not supported.")) + return + try: + directory = Path(self.app.work_dir) / "backgrounds" + directory.mkdir(parents=True, exist_ok=True) + destination = directory / f"{uuid.uuid4().hex}.png" + if not image.save(str(destination), "PNG"): + raise OSError(self.app.tr_text("Unable to save background image.")) + except OSError as error: + QMessageBox.warning(self, self.app.tr_text("Settings error"), str(error)) + return + self.launch_background = str(destination.resolve()) + self._update_background_preview() + self._mark_settings_dirty() + + def _reset_launch_background(self): + self.launch_background = "" + self._update_background_preview() + self._mark_settings_dirty() + def _create_account_page(self) -> QWidget: tr = self.app.tr_text page = SettingsSubPage(tr("Account"), self._go_back) @@ -323,6 +401,7 @@ class SettingsPage(QWidget): description_text = self.app.tr_text(LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD) description = QTextBrowser() + # description.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn) description.setObjectName("settingsDescription") description.setReadOnly(True) description.setOpenExternalLinks(True) @@ -424,7 +503,10 @@ class SettingsPage(QWidget): old_theme = self.settings.get("appearance", AppearanceSettings).theme data = { "general": {"language": self.language_combo.currentData()}, - "appearance": {"theme": self.theme_combo.currentData()}, + "game": {"verify_hash_on_download": self.verify_hash_on_download.isChecked(), + "verify_hash_on_launch": self.verify_hash_on_launch.isChecked()}, + "appearance": {"theme": self.theme_combo.currentData(), + "launch_background": self.launch_background}, "account": {"custom_client_id": client_id if client_id else None, "credentials_save_method": selected_credentials_method, "token_refresh_interval": diff --git a/pyproject.toml b/pyproject.toml index bfd7834..01dc2ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "testlauncher" -version = "0.1.4a0" +version = "0.1.5a0" description = "A lightweight Minecraft launcher." readme = "README.md" requires-python = ">=3.10" diff --git a/resources/translations/en.json b/resources/translations/en.json index 0522cf5..ff289b6 100644 --- a/resources/translations/en.json +++ b/resources/translations/en.json @@ -1,4 +1,19 @@ { + "Image file does not exist or is not a file": "Image file does not exist or is not a file", + "Unable to set profile icon. Icon may invalid.": "Unable to set profile icon. The icon may be invalid.", + "Launch page background": "Launch page background", + "Choose background image": "Choose background image", + "Restore default background": "Restore default background", + "Unable to save background image.": "Unable to save background image.", + "Replace Icon": "Replace Icon", + "Images": "Images", + "All files": "All files", + "Image format is not supported.": "Image format is not supported.", + "Select a profile before replacing the icon": "Select a profile before replacing the icon", + "Game": "Game", + "Game file hash verification": "Game file hash verification", + "Verify file hashes when downloading": "Verify file hashes when downloading", + "Verify library hashes before launch": "Verify library hashes before launch", "OK": "OK", "Old Alpha": "Old Alpha", "Old Beta": "Old Beta", diff --git a/resources/translations/zh-TW.json b/resources/translations/zh-TW.json index 4fe4230..777fbd2 100644 --- a/resources/translations/zh-TW.json +++ b/resources/translations/zh-TW.json @@ -1,4 +1,23 @@ { + "Reset Icon": "重設圖示", + "Profile icons must be square and at least 128 x 128 pixels.": "不支援此圖片:設定檔圖示必須是正方形,且尺寸至少為 128×128 像素。", + "This image exceeds 128 x 128 pixels and will be resized to 128 x 128.": "此圖片超過 128×128 像素,將縮小為 128×128。", + "Unable to encode profile icon.": "無法編碼設定檔圖示。", + "Image file does not exist or is not a file": "圖片檔案不存在或不是檔案", + "Unable to set profile icon. Icon may invalid.": "無法設定設定檔圖示,圖示可能無效。", + "Launch page background": "啟動頁背景", + "Choose background image": "選擇背景圖片", + "Restore default background": "恢復預設背景", + "Unable to save background image.": "無法儲存背景圖片。", + "Replace Icon": "替換圖示", + "Images": "圖片", + "All files": "所有檔案", + "Image format is not supported.": "圖片格式不支援或檔案已損壞。", + "Select a profile before replacing the icon": "請先選取要替換圖示的設定檔", + "Game": "遊戲", + "Game file hash verification": "遊戲檔案雜湊驗證", + "Verify file hashes when downloading": "下載時驗證檔案雜湊", + "Verify library hashes before launch": "啟動前驗證函式庫雜湊", "OK": "確定", "Old Alpha": "舊版 Alpha", "Old Beta": "舊版 Beta", @@ -402,6 +421,6 @@ "{loader} does not support Minecraft {version}.": "{loader} 不支援 Minecraft {version}。", "{account} is currently signed in.": "{account} 目前已登入。", "{account}'s session has expired.": "{account} 的工作階段已過期。", - "$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。", - "$ABOUT_THIS_LAUNCHER_MARKDOWN": "一個使用Python編寫的非官方 Minecraft 啟動器。\n旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n\n*本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。*\n\n\n\n### 鳴謝\n- [PySide6](https://pypi.org/project/PySide6/): GUI 框架\n- [Nuitka](https://nuitka.net/): 構建工具\n- [Minecraft Wiki](https://minecraft.fandom.com/wiki/Main_Page): 帳號系統和啟動器開發參考\n\n\n### 開發者\n- [Wei](https://repo.weispace.net/wei): 主要開發者" + "$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開發的專案。", + "$ABOUT_THIS_LAUNCHER_MARKDOWN": "一個使用Python編寫的非官方 Minecraft 啟動器。\n旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n\n*本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開發的專案。*\n\n\n\n### 鳴謝\n- [PySide6](https://pypi.org/project/PySide6/): GUI 框架\n- [Nuitka](https://nuitka.net/): 構建工具\n- [Minecraft Wiki](https://minecraft.wiki/): 帳號系統和啟動器開發參考 ([Writing a launcher](https://zh.minecraft.wiki/w/Tutorial:%E7%BC%96%E5%86%99%E5%90%AF%E5%8A%A8%E5%99%A8))\n\n\n### 開發者\n- [Wei](https://repo.weispace.net/wei): 主要開發者" }