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
This commit is contained in:
wei committed 2026-11-10 22:05:18 +08:00
1 parent fcd61b3755
commit ca1eac5eb9
19 files changed
+476 -96

No files matched your search

+2 -1
View File
@@ -26,7 +26,7 @@ from manager.account import AccountManager
from manager.game import GameManager from manager.game import GameManager
from manager.profile import ProfileManager from manager.profile import ProfileManager
from manager.settings import SettingsManager 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 manager.widgets import WidgetManager
from window import LauncherMainWindow from window import LauncherMainWindow
@@ -72,6 +72,7 @@ class Launcher(QApplication, LauncherObject):
self.settings_manager.register("account", AccountSettings) self.settings_manager.register("account", AccountSettings)
self.settings_manager.register("plugins", PluginSettings) self.settings_manager.register("plugins", PluginSettings)
self.settings_manager.register("page-bar", PageBarSettings) self.settings_manager.register("page-bar", PageBarSettings)
self.settings_manager.register("game", GameSettings)
if self.root_settings_dir.is_file(): if self.root_settings_dir.is_file():
self.load_settings() self.load_settings()
else: else:
+3 -2
View File
@@ -1,4 +1,4 @@
LAUNCHER_VERSION = "0.1.4-alpha" LAUNCHER_VERSION = "0.1.5-alpha"
LAUNCHER_NAME = "TapLauncher" LAUNCHER_NAME = "TapLauncher"
LAUNCHER_DIR_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher"
MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/"
@@ -26,7 +26,8 @@ It aims to maintain maximum compatibility with the official Minecraft
### Credits ### Credits
- [PySide6](https://pypi.org/project/PySide6/): GUI framework - [PySide6](https://pypi.org/project/PySide6/): GUI framework
- [Nuitka](https://nuitka.net/): Build tool - [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 \n
### Developer ### Developer
- [Wei](https://repo.weispace.net/wei): Main developer - [Wei](https://repo.weispace.net/wei): Main developer
+3 -3
View File
@@ -1,4 +1,4 @@
__version__ = '0.1.7' __version__ = '0.1.8'
__description__ = """ __description__ = """
A library for Python-based block game launcher. A library for Python-based block game launcher.
@@ -184,7 +184,7 @@ from .game.library_core import (
collect_native_artifacts, collect_native_artifacts,
download_libraries, download_libraries,
unzip_natives, unzip_natives,
check_libraries_exists, check_libraries_exists_and_verify,
check_natives_exists, check_natives_exists,
check_full_libraries_exists, check_full_libraries_exists,
generate_classpath, generate_classpath,
@@ -527,7 +527,7 @@ __all__ = [
"collect_native_artifacts", "collect_native_artifacts",
"download_libraries", "download_libraries",
"unzip_natives", "unzip_natives",
"check_libraries_exists", "check_libraries_exists_and_verify",
"check_natives_exists", "check_natives_exists",
"check_full_libraries_exists", "check_full_libraries_exists",
"generate_classpath", "generate_classpath",
+11 -9
View File
@@ -186,7 +186,8 @@ def generate_random_suffix():
return "".join(random.choices(string.ascii_lowercase + string.digits, k=8)) return "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None, 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 Download the file from url
:param file: File (Objected) :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 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 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 max_temp_suffix_retry: Maximum number of retries for generating a unique temp file suffix
:param timeout: Timeout for the download request
:return: :return:
""" """
@@ -230,7 +232,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
try: try:
target_file.invalidate_hash_cache() # Clean cache hash target_file.invalidate_hash_cache() # Clean cache hash
try: 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() r.raise_for_status()
current_chunk = 0 current_chunk = 0
total_bytes = r.headers.get("content-length", None) total_bytes = r.headers.get("content-length", None)
@@ -255,18 +257,18 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
finally: finally:
target_file.invalidate_hash_cache() 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, raise HashMismatchException("sha256", target_file.sha256, target_file.expected_sha256,
target_file.posix_path) 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) 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) 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, raise HashMismatchException("sha512", target_file.sha512, target_file.expected_sha512,
target_file.posix_path) 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.") logger.debug("File hash is match as the expected hash.")
else: else:
logger.warning("Hash is not checked for file: {}".format(target_file.posix_path)) 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 return file
def download_multiple_files(files: List[FileObject], download_callback: Callable[[str], None]=None, 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]]: -> tuple[list[FileObject], list[FileObject]]:
""" """
Download multiple files Download multiple files
@@ -315,7 +317,7 @@ def download_multiple_files(files: List[FileObject], download_callback: Callable
files_count = 0 files_count = 0
with ThreadPoolExecutor(max_workers=max_workers) as executor: 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): for future in as_completed(future_to_file):
file = future_to_file[future] file = future_to_file[future]
+7 -7
View File
@@ -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) "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. Fetch the asset manifest from target version's manifest and save it.
:param target_version_manifest: :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: with file.path.open("wb") as f:
f.write(data) f.write(data)
if sha1 and not file.verify_sha1(sha1): if verify_hash and sha1 and not file.verify_sha1(sha1):
raise HashMismatchException( raise HashMismatchException(
"sha1", "sha1",
file.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: if old_asset.path.stat().st_size == size:
logger.debug("Asset {} already exists. (no_hash_check=True)".format(target)) logger.debug("Asset {} already exists. (no_hash_check=True)".format(target))
return True, None 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)) logger.debug("Asset {} already exists.".format(target))
return True, None return True, None
@@ -294,7 +294,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict]
return True, destination return True, destination
fails , _ = download_multiple_files(assets, progress_callback=progress_callback, 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 download_ok = len(fails) == 0
@@ -311,7 +311,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict]
return fails return fails
# Use thread pool to handle copy file process # 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 = [ futures = [
executor.submit( executor.submit(
__worker, __worker,
@@ -395,7 +395,7 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha
if index_path.is_file(): if index_path.is_file():
try: 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")) cached = json.loads(index_path.read_text(encoding="utf-8"))
if isinstance(cached, dict) and isinstance(cached.get("objects"), dict) and cached["objects"]: 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) logger.warning("Unable to read cached asset index: %s", index_path)
if asset_manifest is None: 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 # Download assets files
assets, legacy_assets = collect_assets_from_manifest( assets, legacy_assets = collect_assets_from_manifest(
+6 -6
View File
@@ -11,7 +11,7 @@ from typing import Callable
import requests import requests
from core_lib.common.exception import LauncherException, AuthenticationSessionException, AuthenticationConnectException, \ 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_DEVICE_CODE_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"
MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token" 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 Handle authentication exceptions
:param stage: :param stage:
:param request_handler: :param request_handler:
:param request_type: Set this will change exception type when an error occurs. ("without_token" for process that :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 process that use token. If with token, exception usually throw don't use token, "with_token" for processes that use token. If with token, exception usually throws
AuthenticationSessionException. If not, throw AuthenticationException instead) AuthenticationSessionException. If not, throw AuthenticationException instead)
:return: :return:
""" """
@@ -58,8 +58,8 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho
except (TypeError, ValueError): except (TypeError, ValueError):
pass pass
# Below are the xsts error code suggestions. Why return that value (error is integer not string) ? # Below are the xsts error code suggestions. Why return that value (error is integer, not string)?
# Maybe it makes international support more easily? # Maybe it makes international support more easy?
xsts_suggestions = { xsts_suggestions = {
2148916233: "This Microsoft account does not have an Xbox profile. Sign in at xbox.com and create one, then try again.", 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.", 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 ) from e
server_message = response_data.get("Message") or response_data.get("error_description") 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 = { suggestions = {
400: "The authentication request or session was rejected.", 400: "The authentication request or session was rejected.",
401: "The login session is invalid or expired. Sign in again.", 401: "The login session is invalid or expired. Sign in again.",
+2 -1
View File
@@ -170,7 +170,8 @@ def get_natives_platform_info():
return platform_key_name, platform_rule_name, platform_arch_type 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 # Parse native key
match = re.search(r":(natives-[^:]+)$", lib_name) match = re.search(r":(natives-[^:]+)$", lib_name)
+66 -13
View File
@@ -2,16 +2,17 @@ import logging
import re import re
import zipfile import zipfile
from pathlib import Path, PureWindowsPath 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 .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, \ 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 is_native_allowed, is_legacy_native_allowed, remove_duplicate_artifacts
from .libraryx import normalize_library_to_common_struct 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 .version_info import find_useful_part_in_specific_version_manifest
from ..common.exception import UnsupportedPlatformException, NativeResolveException, DependencyException, \ from ..common.exception import UnsupportedPlatformException, NativeResolveException, DependencyException, \
VersionDataKeyNotFoundException, DownloadException VersionDataKeyNotFoundException, DownloadException, HashMismatchException
logger = logging.getLogger("Launcher.CoreLib") logger = logging.getLogger("Launcher.CoreLib")
@@ -234,7 +235,7 @@ def collect_native_artifacts(specific_version_manifest):
return items 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]]: -> tuple[list[FileObject], list[FileObject]]:
""" """
Download libraries from a list that contains artifacts Download libraries from a list that contains artifacts
@@ -267,13 +268,17 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str,
full_path, full_path,
url=url, url=url,
sha1=sha1, sha1=sha1,
sha256=sha256,
sha512=sha512,
) )
if sha1 is None: if sha1 is None:
logger.warning(f"File {full_path} has no SHA1 hash.") logger.warning(f"File {full_path} has no SHA1 hash.")
if file.exists: 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) valid = file.verify("sha1", sha1)
elif sha256 is not None: elif sha256 is not None:
valid = file.verify("sha256", sha256) valid = file.verify("sha256", sha256)
@@ -290,7 +295,7 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str,
files.append(file) 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) successes.extend(finished)
return fails, successes return fails, successes
@@ -328,16 +333,32 @@ def unzip_natives(filtered, libraries_dir, destination: Path):
logger.debug(f"Unzipped {full_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 manifest:
:param libraries_dir: :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: :return:
not_found: list not_found: list
""" """
libraries = manifest.get("libraries", []) 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: if not libraries:
raise VersionDataKeyNotFoundException( raise VersionDataKeyNotFoundException(
"Libraries not found in manifest.", "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...") logger.warning(f"Artifact {name} are not valid. Skipping...")
continue 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) full_path = libraries_dir / Path(relative_path)
if not full_path.is_file() or not full_path.exists(): if not full_path.is_file() or not full_path.exists():
logger.debug(f"Artifact {name} missing.") logger.debug(f"Artifact {name} missing.")
not_found.append(full_path) 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 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, *, 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( natives_exist = check_natives_exists(
manifest, manifest,
libraries_dir, libraries_dir,
natives_dir, natives_dir,
features=features, features=features,
) )
missing_libraries = check_libraries_exists( missing_libraries = check_libraries_exists_and_verify(
manifest, manifest,
libraries_dir, libraries_dir,
verify_hash=verify_hash,
) )
return natives_exist and not missing_libraries 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, progress_callback: Callable[[str, float], None] = None,
redownload_callback: Callable[ redownload_callback: Callable[
[list[FileObject]], tuple[bool, list[FileObject]]] = None, *, [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) natives_dir = locate_natives_extract_dir_by_manifest(manifest, default_natives_dir, features=features)
# libraries # libraries
libraries = collect_library_artifacts(manifest) libraries = collect_library_artifacts(manifest)
@@ -621,7 +674,7 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives
) )
# Start download # 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 download_ok = len(fails) == 0
+5 -5
View File
@@ -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) return save_version_manifest(data, dest, sha1)
def download_core_file(manifest: dict, destination: Path, is_server=False, raise_for_null_hash=True, 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. Download core file from version manifest.
:param 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) 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( raise VersionDataKeyNotFoundException(
"Core file hash is missing. Enable \"raise_for_null_hash\" flag to ignore this exception.\n" "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) 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.") logger.info(f"Client existed and sha1 matches.")
elif url is not None: 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: elif not url:
raise VersionDataKeyNotFoundException( raise VersionDataKeyNotFoundException(
"Core file url is None. Unable to download it." "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) _, _, 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.") logger.warning(f"Core file \"{core_file_path.as_posix()}\" does not exist.")
return False return False
+59 -2
View File
@@ -1,8 +1,9 @@
import base64 import base64
import binascii
from pathlib import Path from pathlib import Path
from PySide6.QtCore import QCoreApplication, QThread, QSize, Qt from PySide6.QtCore import QCoreApplication, QThread, QSize, Qt, QBuffer, QIODevice
from PySide6.QtGui import QScreen, QPixmap, QPainter, QPalette, QIcon, QColor, QImage from PySide6.QtGui import QScreen, QPixmap, QPainter, QPalette, QIcon, QColor, QImage, QImageReader
from PySide6.QtWidgets import QMainWindow, QApplication, QWidget, QDialog from PySide6.QtWidgets import QMainWindow, QApplication, QWidget, QDialog
@@ -124,4 +125,60 @@ def data_url_to_qt_image(data_url: str) -> QImage:
return image return image
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 ======================== # ======================== AI generated END ========================
+27 -9
View File
@@ -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 core_lib.runtime.mojang import download_java_runtimes, fetch_runtime_manifest, get_current_platform_runtime_key
from manager.account import AccountManager, LaunchAccount from manager.account import AccountManager, LaunchAccount
from manager.profile import LaunchProfile, ProfileManager from manager.profile import LaunchProfile, ProfileManager
from manager.settings_models import GameSettings
from manager.widgets import SelectPathRequest, AskForRequest, SignalTransferItem from manager.widgets import SelectPathRequest, AskForRequest, SignalTransferItem
MAX_DOWNLOAD_ATTEMPTS = 3 MAX_DOWNLOAD_ATTEMPTS = 3
@@ -883,6 +884,9 @@ class GameFileManager:
"download_assets": self.download_assets, "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, def get_manifest(self, target_version: str,
manifest: dict | None, failed_message: str, manifest: dict | None, failed_message: str,
vanilla: bool=False) -> dict | None: vanilla: bool=False) -> dict | None:
@@ -925,8 +929,10 @@ class GameFileManager:
"Downloading dependencies..." "Downloading dependencies..."
) )
verify_hash = self._verify_download_hash()
try: try:
download_core_file(manifest, core_file_path, download_core_file(manifest, core_file_path,
verify_hash=verify_hash,
raise_for_null_hash=True, raise_for_null_hash=True,
progress_callback=callback) progress_callback=callback)
except Exception as e: except Exception as e:
@@ -953,10 +959,12 @@ class GameFileManager:
"Downloading dependencies..." "Downloading dependencies..."
) )
verify_hash = self._verify_download_hash()
try: try:
download_full_libraries(manifest, libraries_dir, natives_dir, download_full_libraries(manifest, libraries_dir, natives_dir,
progress_callback=callback, 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: except Exception as e:
self.widget_mgr.download_signal.failed.emit(task_id, str(e)) self.widget_mgr.download_signal.failed.emit(task_id, str(e))
self.widget_mgr.signal.show_error_message.emit( self.widget_mgr.signal.show_error_message.emit(
@@ -988,16 +996,17 @@ class GameFileManager:
"Downloading assets" "Downloading assets"
) )
verify_hash = self._verify_download_hash()
try: try:
fails = download_assets( fails = download_assets(
manifest, manifest,
assets_dir, assets_dir,
no_hash_check=True, no_hash_check=not verify_hash,
progress_callback=callback, progress_callback=callback,
launcher_root=self.app.work_dir, 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 not result:
if allow_missing: if allow_missing:
@@ -1048,7 +1057,7 @@ class GameFileManager:
return thread 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: if not files:
return True, [] return True, []
@@ -1084,7 +1093,7 @@ class GameFileManager:
self.widget_mgr.download_signal.log.emit(f"Attempt {retry_time}/{MAX_DOWNLOAD_ATTEMPTS}") 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) progress_callback=callback)
for file in successes: for file in successes:
@@ -1191,11 +1200,15 @@ class GameFileManager:
) )
update_stage("downloading the Minecraft client") 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. # Keep client progress and its original errors in this installation task.
download_core_file( download_core_file(
vanilla, client_jar, raise_for_null_hash=True, vanilla, client_jar, raise_for_null_hash=True,
progress_callback=progress_callback, progress_callback=progress_callback,
verify_hash=verify_hash,
) )
update_stage("copying embedded artifacts") update_stage("copying embedded artifacts")
@@ -1203,9 +1216,11 @@ class GameFileManager:
update_stage("downloading installer dependencies") update_stage("downloading installer dependencies")
files = forge_like.collect_install_dependencies(plan, libraries_dir) 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: if failures:
success, failures = self.redownload_files(failures) success, failures = self.redownload_files(failures, verify_hash=verify_hash)
if not success or failures: if not success or failures:
raise LoaderInstallError("Unable to download installer dependencies.") raise LoaderInstallError("Unable to download installer dependencies.")
@@ -1285,6 +1300,7 @@ class LaunchManager:
self.app = app self.app = app
self.manifest_mgr = manifest_manager self.manifest_mgr = manifest_manager
self.widget_mgr = app.widget_manager self.widget_mgr = app.widget_manager
self.settings_mgr = app.settings_manager
self.java_mgr = java_manager self.java_mgr = java_manager
self.game_file_mgr = game_file_manager self.game_file_mgr = game_file_manager
self.account_mgr = account_manager self.account_mgr = account_manager
@@ -1383,7 +1399,9 @@ class LaunchManager:
) )
# Libraries # 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( request = GameFileDownloadRequest(
"download_libraries", "download_libraries",
(version_id, libraries_dir, natives_dir, version_manifest) (version_id, libraries_dir, natives_dir, version_manifest)
+63
View File
@@ -3,13 +3,17 @@ Profile Manager
A Minecraft profile manager that completely support official Minecraft Launcher. A Minecraft profile manager that completely support official Minecraft Launcher.
""" """
import base64
import copy import copy
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Callable
from PySide6.QtCore import QObject, Signal from PySide6.QtCore import QObject, Signal
from datetime import datetime, timezone from datetime import datetime, timezone
from PySide6.QtGui import QIcon
from core_lib.common.exception import ProfileException, ProfileLoadException, ProfileSaveException from core_lib.common.exception import ProfileException, ProfileLoadException, ProfileSaveException
from core_lib.game.profile import read_profile_file, is_profiles_valid, \ 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, \ 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, \ get_current_profile_id, set_current_profile_id, remove_profile, duplicate_profile, \
set_last_used_time set_last_used_time
from core_lib.game.version_info import LATEST_VERSION_ALIASES 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 from manager.widgets import AskForRequest
DEFAuLT_PROFILE_RELATIVE_PATH = Path("launcher_profiles.json") DEFAuLT_PROFILE_RELATIVE_PATH = Path("launcher_profiles.json")
@@ -592,6 +597,51 @@ class ProfileManager(QObject):
) )
return False 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( def update_last_used_time(
self, self,
profile_id: str, profile_id: str,
@@ -803,3 +853,16 @@ def sort_profile_summaries(
ordered.sort(key=lambda profile: profile.id != current_profile_id) ordered.sort(key=lambda profile: profile.id != current_profile_id)
return ordered 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
+5
View File
@@ -33,6 +33,7 @@ class AppearanceSettings(WarnExtraModel):
model_config = ConfigDict() model_config = ConfigDict()
theme: str = "system" theme: str = "system"
launch_background: str = ""
@field_validator("theme") @field_validator("theme")
@classmethod @classmethod
@@ -84,3 +85,7 @@ class PageBarSettings(WarnExtraModel):
focus_at_after_restart: bool = False focus_at_after_restart: bool = False
last_focused_page: str = "" last_focused_page: str = ""
page_bar_position: Literal["left", "right", "top", "bottom"] = "left" page_bar_position: Literal["left", "right", "top", "bottom"] = "left"
class GameSettings(WarnExtraModel):
verify_hash_on_download: bool = True
verify_hash_on_launch: bool = True
+22 -23
View File
@@ -8,8 +8,9 @@ from PySide6.QtWidgets import (QWidget, QVBoxLayout, QLabel, QHBoxLayout, QPushB
from core_lib.qt.item_button import ItemButton from core_lib.qt.item_button import ItemButton
from manager.game import LaunchManager, LaunchResult from manager.game import LaunchManager, LaunchResult
from core_lib.game.version_info import LATEST_VERSION_ALIASES 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.widgets import AskForRequest, WidgetManager
from manager.settings_models import AppearanceSettings
from pages.process_log import ProcessLogWindow from pages.process_log import ProcessLogWindow
@@ -68,16 +69,8 @@ class ProfileButton(QFrame):
self.name_label.setText(profile.display_name) self.name_label.setText(profile.display_name)
self.version_label.setText(profile.version_id) self.version_label.setText(profile.version_id)
icon_path = profile.icon icon = profile.icon
self.icon_label.setPixmap(_profile_icon(icon, self.app.icon_dir).pixmap(36, 36))
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))
def set_popup_open(self, opened: bool) -> None: def set_popup_open(self, opened: bool) -> None:
self.arrow_label.setText("▴" if opened else "▾") self.arrow_label.setText("▴" if opened else "▾")
@@ -121,8 +114,8 @@ class ProfileListItem(ItemButton):
layout.addLayout(text_layout, 1) layout.addLayout(text_layout, 1)
self.clicked.connect(lambda: self.selected.emit(self.profile)) self.clicked.connect(lambda: self.selected.emit(self.profile))
def set_icon(self, icon_path: Path) -> None: def set_icon(self, icon: QPixmap) -> None:
self.icon_label.setPixmap(QIcon(icon_path.as_posix()).pixmap(36, 36)) self.icon_label.setPixmap(icon)
class ProfilePopup(QFrame): class ProfilePopup(QFrame):
profile_selected = Signal(object) profile_selected = Signal(object)
@@ -166,18 +159,9 @@ class ProfilePopup(QFrame):
self.clean_profiles() self.clean_profiles()
for profile in 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 = ProfileListItem(profile, self)
item.selected.connect(self.profile_selected) 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) self.content_layout.addWidget(item)
def clean_profiles(self) -> None: def clean_profiles(self) -> None:
@@ -293,11 +277,26 @@ class LaunchProfilePage(QWidget):
self.load_profiles, 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): class ProfileBackgroundFrame(QFrame):
def __init__(self, image_path, parent=None): def __init__(self, image_path, parent=None):
super().__init__(parent) super().__init__(parent)
self.background = QPixmap(str(image_path)) 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): def paintEvent(self, event):
super().paintEvent(event) super().paintEvent(event)
+73 -9
View File
@@ -3,15 +3,16 @@ from pathlib import Path
from typing import Callable from typing import Callable
from PySide6.QtCore import Qt, QUrl, Signal from PySide6.QtCore import Qt, QUrl, Signal
from PySide6.QtGui import QDesktopServices, QIcon from PySide6.QtGui import QDesktopServices, QImageReader
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit, QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit,
QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox,
QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget, 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 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 manager.game import AvailableVersion
from pages.add_modded_version import AddModdedVersionDialog from pages.add_modded_version import AddModdedVersionDialog
@@ -41,12 +42,9 @@ class ManageProfileItem(ItemButton):
layout.setContentsMargins(12, 8, 12, 8) layout.setContentsMargins(12, 8, 12, 8)
layout.setSpacing(12) 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 = QLabel()
icon.setFixedSize(40, 40) 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) icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
texts = QVBoxLayout() texts = QVBoxLayout()
@@ -91,6 +89,7 @@ class ManageProfileItem(ItemButton):
menu.exec(global_position) menu.exec(global_position)
class ManageProfilePage(QWidget): class ManageProfilePage(QWidget):
""" """
Profile manage page Profile manage page
@@ -109,6 +108,7 @@ class ManageProfilePage(QWidget):
self.app = app self.app = app
self.profile_manager: ProfileManager = app.profile_manager self.profile_manager: ProfileManager = app.profile_manager
self.manifest_manager = app.game_manager.manifest self.manifest_manager = app.game_manager.manifest
self.widget_manager = app.widget_manager
self.selected_profile_id: str | None = None self.selected_profile_id: str | None = None
self.profile_items: dict[str, ManageProfileItem] = {} self.profile_items: dict[str, ManageProfileItem] = {}
self.version_options: list[AvailableVersion] = [] self.version_options: list[AvailableVersion] = []
@@ -157,7 +157,26 @@ class ManageProfilePage(QWidget):
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
form.setVerticalSpacing(12) 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.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 = QComboBox()
self.version_dropdown.setObjectName("Dropdown") self.version_dropdown.setObjectName("Dropdown")
self.version_dropdown.setSizePolicy( self.version_dropdown.setSizePolicy(
@@ -172,22 +191,22 @@ class ManageProfilePage(QWidget):
self.type_dropdown.setObjectName("Dropdown") self.type_dropdown.setObjectName("Dropdown")
self.game_dir_edit = QLineEdit() self.game_dir_edit = QLineEdit()
self.java_args_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.width_spin = self._dimension_spin()
self.height_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("Type"), self.type_dropdown)
form.addRow(self.app.tr_text("Version"), self.version_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("Game directory"), self.game_dir_edit)
form.addRow(self.app.tr_text("Java arguments"), self.java_args_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 = QHBoxLayout()
resolution.addWidget(self.width_spin) resolution.addWidget(self.width_spin)
resolution.addWidget(QLabel("×")) resolution.addWidget(QLabel("×"))
resolution.addWidget(self.height_spin) resolution.addWidget(self.height_spin)
form.addRow(self.app.tr_text("Resolution"), resolution) form.addRow(self.app.tr_text("Resolution"), resolution)
editor_layout.addLayout(profile_head_h_layout)
editor_layout.addLayout(form) editor_layout.addLayout(form)
file_actions = QHBoxLayout() file_actions = QHBoxLayout()
@@ -228,6 +247,7 @@ class ManageProfilePage(QWidget):
self.type_dropdown.currentIndexChanged.connect(self._filter_versions) self.type_dropdown.currentIndexChanged.connect(self._filter_versions)
self.profile_manager.profiles_changed.connect(self.refresh_profiles) 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.app.apply_qss(Path("manage_profile.qss"), self.setStyleSheet)
self._load_type_dropdown() self._load_type_dropdown()
self.refresh_profiles() self.refresh_profiles()
@@ -361,6 +381,9 @@ class ManageProfilePage(QWidget):
def _set_detail(self, profile: ProfileDetail) -> None: def _set_detail(self, profile: ProfileDetail) -> None:
self.name_edit.setText(profile.name) 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( option = next(
(item for item in self.version_options if item.id == profile.version_id), (item for item in self.version_options if item.id == profile.version_id),
None, None,
@@ -611,3 +634,44 @@ class ManageProfilePage(QWidget):
cleanup() cleanup()
raise raise
return cleanup 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))
+85 -3
View File
@@ -2,8 +2,9 @@ import uuid
from pathlib import Path from pathlib import Path
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtGui import QImageReader, QPixmap
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QComboBox, QComboBox, QCheckBox, QFileDialog,
QHBoxLayout, QHBoxLayout,
QLabel, QLabel,
QLineEdit, QLineEdit,
@@ -18,7 +19,7 @@ from PySide6.QtWidgets import (
from constant import LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD, \ from constant import LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD, \
LAUNCHER_DESCRIPTION_MARKDOWN, LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD LAUNCHER_DESCRIPTION_MARKDOWN, LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD
from core_lib.qt import messagebox 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 from pages.plugins import PluginsDialog
LANGUAGE_LABELS = { LANGUAGE_LABELS = {
@@ -104,6 +105,7 @@ class SettingsPage(QWidget):
self.main_page = self._create_main_page() self.main_page = self._create_main_page()
self.general_page = self._create_general_page() self.general_page = self._create_general_page()
self.game_page = self._create_game_page()
self.appearance_page = self._create_appearance_page() self.appearance_page = self._create_appearance_page()
self.account_page = self._create_account_page() self.account_page = self._create_account_page()
self.about_page = self._create_about_page() self.about_page = self._create_about_page()
@@ -111,6 +113,7 @@ class SettingsPage(QWidget):
for page in ( for page in (
self.main_page, self.main_page,
self.general_page, self.general_page,
self.game_page,
self.appearance_page, self.appearance_page,
self.account_page, self.account_page,
self.about_page, self.about_page,
@@ -147,12 +150,14 @@ class SettingsPage(QWidget):
self.main_page = self._create_main_page() self.main_page = self._create_main_page()
self.general_page = self._create_general_page() self.general_page = self._create_general_page()
self.game_page = self._create_game_page()
self.appearance_page = self._create_appearance_page() self.appearance_page = self._create_appearance_page()
self.account_page = self._create_account_page() self.account_page = self._create_account_page()
self.about_page = self._create_about_page() self.about_page = self._create_about_page()
for page in ( for page in (
self.main_page, self.main_page,
self.general_page, self.general_page,
self.game_page,
self.appearance_page, self.appearance_page,
self.account_page, self.account_page,
self.about_page, self.about_page,
@@ -189,6 +194,7 @@ class SettingsPage(QWidget):
pages = ( pages = (
(tr("General"), tr("Language and launcher directories"), "general_page"), (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("Appearance"), tr("Launcher theme"), "appearance_page"),
(tr("Account"), tr("Microsoft authentication settings"), "account_page"), (tr("Account"), tr("Microsoft authentication settings"), "account_page"),
(tr("About"), tr("Version and project information"), "about_page"), (tr("About"), tr("Version and project information"), "about_page"),
@@ -239,6 +245,19 @@ class SettingsPage(QWidget):
page.content_layout.addWidget(self.language_combo) page.content_layout.addWidget(self.language_combo)
return page 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: def _create_appearance_page(self) -> QWidget:
tr = self.app.tr_text tr = self.app.tr_text
page = SettingsSubPage(tr("Appearance"), self._go_back) page = SettingsSubPage(tr("Appearance"), self._go_back)
@@ -260,8 +279,67 @@ class SettingsPage(QWidget):
help_label.setObjectName("settingsHelpText") help_label.setObjectName("settingsHelpText")
help_label.setWordWrap(True) help_label.setWordWrap(True)
page.content_layout.addWidget(help_label) 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 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: def _create_account_page(self) -> QWidget:
tr = self.app.tr_text tr = self.app.tr_text
page = SettingsSubPage(tr("Account"), self._go_back) 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_text = self.app.tr_text(LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD)
description = QTextBrowser() description = QTextBrowser()
# description.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
description.setObjectName("settingsDescription") description.setObjectName("settingsDescription")
description.setReadOnly(True) description.setReadOnly(True)
description.setOpenExternalLinks(True) description.setOpenExternalLinks(True)
@@ -424,7 +503,10 @@ class SettingsPage(QWidget):
old_theme = self.settings.get("appearance", AppearanceSettings).theme old_theme = self.settings.get("appearance", AppearanceSettings).theme
data = { data = {
"general": {"language": self.language_combo.currentData()}, "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, "account": {"custom_client_id": client_id if client_id else None,
"credentials_save_method": selected_credentials_method, "credentials_save_method": selected_credentials_method,
"token_refresh_interval": "token_refresh_interval":
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "testlauncher" name = "testlauncher"
version = "0.1.4a0" version = "0.1.5a0"
description = "A lightweight Minecraft launcher." description = "A lightweight Minecraft launcher."
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
+15
View File
@@ -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", "OK": "OK",
"Old Alpha": "Old Alpha", "Old Alpha": "Old Alpha",
"Old Beta": "Old Beta", "Old Beta": "Old Beta",
+21 -2
View File
@@ -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": "確定", "OK": "確定",
"Old Alpha": "舊版 Alpha", "Old Alpha": "舊版 Alpha",
"Old Beta": "舊版 Beta", "Old Beta": "舊版 Beta",
@@ -402,6 +421,6 @@
"{loader} does not support Minecraft {version}.": "{loader} 不支援 Minecraft {version}。", "{loader} does not support Minecraft {version}.": "{loader} 不支援 Minecraft {version}。",
"{account} is currently signed in.": "{account} 目前已登入。", "{account} is currently signed in.": "{account} 目前已登入。",
"{account}'s session has expired.": "{account} 的工作階段已過期。", "{account}'s session has expired.": "{account} 的工作階段已過期。",
"$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。", "$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_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): 主要開發者"
} }