Add customize qss support for theme.
Fix an issue that causes all feature flags will not be added to the launch command regardless of it is enabled. Add some default themes.
This commit is contained in:
1 parent
1754b01230
commit
b7af7e3469
53 files changed
+1319
-130
No files matched your search
@@ -101,7 +101,7 @@ class FileObject:
|
||||
return self.sha512 == expected_hash if expected_hash else self.expected_sha512 == self.sha512
|
||||
|
||||
def verify_md5(self, expected_hash=None):
|
||||
return self.sha1 == expected_hash if expected_hash else self.expected_sha1 == self.sha1
|
||||
return self.md5 == expected_hash if expected_hash else self.expected_sha1 == self.md5
|
||||
|
||||
def verify(self, algorithm, expected_hash=None):
|
||||
if algorithm == "sha1":
|
||||
@@ -219,6 +219,8 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
|
||||
raise HashMismatchException("sha1", file.sha1, file.expected_sha1, file.posix_path)
|
||||
elif file.expected_md5 and not file.verify_md5():
|
||||
raise HashMismatchException("md5", file.md5, file.expected_md5, file.posix_path)
|
||||
elif file.expected_sha512 and not file.verify_sha512():
|
||||
raise HashMismatchException("sha512", file.sha512, file.expected_sha512, file.posix_path)
|
||||
|
||||
if any([file.expected_sha1, file.expected_md5, file.expected_sha256]):
|
||||
logger.debug("File hash is match as the expected hash.")
|
||||
|
||||
@@ -138,4 +138,10 @@ class ConfigValidationError(SettingsError):
|
||||
details = "\n".join(
|
||||
f"[{section}]\n{error}" for section, error in self.errors.items()
|
||||
)
|
||||
super().__init__(f"Invalid settings configuration:\n{details}")
|
||||
super().__init__(f"Invalid settings configuration:\n{details}")
|
||||
|
||||
class ArgumentError(LauncherException):
|
||||
user_message = "An error occurred while parsing arguments."
|
||||
|
||||
class ArgumentValueError(ArgumentError):
|
||||
user_message = "An invalid argument value was provided."
|
||||
@@ -48,6 +48,7 @@ class Account:
|
||||
avatar: str = ""
|
||||
type: str = "msa"
|
||||
user_properties: list = field(default_factory=list)
|
||||
xuid: str | None = None
|
||||
|
||||
|
||||
def _datetime_string(value: str | datetime.datetime, field_name: str) -> str:
|
||||
@@ -83,6 +84,7 @@ def create_account_data_from_object(account: Account) -> dict:
|
||||
"type": account.type,
|
||||
"userProperties": deepcopy(account.user_properties),
|
||||
"username": account.username,
|
||||
"xuid": account.xuid,
|
||||
}
|
||||
|
||||
SUPPORT_DATA_URL_IMAGE_TYPE = [
|
||||
@@ -427,6 +429,7 @@ def convert_account_data_to_object(accounts: dict, account_id: str) -> Account:
|
||||
avatar=data.get("avatar", ""),
|
||||
type=data.get("type", "msa"),
|
||||
user_properties=deepcopy(data.get("userProperties", [])),
|
||||
xuid=data.get("xuid"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+143
-20
@@ -2,13 +2,54 @@ import json
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
from core_lib.common.common import get_platform_info
|
||||
from core_lib.common.exception import LauncherException
|
||||
from core_lib.common.exception import LauncherException, ArgumentValueError
|
||||
from core_lib.game.library import get_natives_platform_info
|
||||
|
||||
logger = logging.getLogger("Launcher.CoreLib")
|
||||
|
||||
# =============== Features ===============
|
||||
@dataclass(frozen=True)
|
||||
class FeatureSpec:
|
||||
required_placeholders: tuple[str, ...] = ()
|
||||
validate: Callable[[dict], None] | None = None
|
||||
|
||||
|
||||
def validate_resolution(values: dict) -> None:
|
||||
for key in ("resolution_width", "resolution_height"):
|
||||
value = values[key]
|
||||
if type(value) is not int or value <= 0:
|
||||
raise ArgumentValueError(
|
||||
f"{key} must be a positive integer."
|
||||
)
|
||||
|
||||
|
||||
FEATURE_SPECS = {
|
||||
"has_custom_resolution": FeatureSpec(
|
||||
required_placeholders=(
|
||||
"resolution_width",
|
||||
"resolution_height",
|
||||
),
|
||||
validate=validate_resolution,
|
||||
),
|
||||
"is_demo_user": FeatureSpec(),
|
||||
"has_quick_plays_support": FeatureSpec(
|
||||
required_placeholders=("quickPlayPath",),
|
||||
),
|
||||
"is_quick_play_singleplayer": FeatureSpec(
|
||||
required_placeholders=("quickPlaySingleplayer",),
|
||||
),
|
||||
"is_quick_play_multiplayer": FeatureSpec(
|
||||
required_placeholders=("quickPlayMultiplayer",),
|
||||
),
|
||||
"is_quick_play_realms": FeatureSpec(
|
||||
required_placeholders=("quickPlayRealms",),
|
||||
),
|
||||
}
|
||||
# =============== Features end ===============
|
||||
|
||||
def compare_versions(left: str, right: str) -> int:
|
||||
left_parts = tuple(map(int, left.split(".")))
|
||||
right_parts = tuple(map(int, right.split(".")))
|
||||
@@ -104,12 +145,24 @@ def is_argument_allowed(argument: dict | str, allow_features: dict | None = None
|
||||
|
||||
return allowed
|
||||
|
||||
def replace_placeholders(argument, placeholders: dict) -> str:
|
||||
if argument:
|
||||
for key, value in placeholders.items():
|
||||
argument = argument.replace("${" + key + "}", "" if value is None else str(value))
|
||||
PLACEHOLDER_PATTERN = re.compile(r"\$\{([^{}]+)\}")
|
||||
|
||||
return argument
|
||||
def replace_placeholders(argument, placeholders: dict, *, strict: bool = False,) -> str:
|
||||
def replace(match: re.Match) -> str:
|
||||
key = match.group(1)
|
||||
|
||||
if key not in placeholders or placeholders[key] is None:
|
||||
if not strict:
|
||||
return match.group(0)
|
||||
|
||||
reason = "unknown" if key not in placeholders else "has no value"
|
||||
raise ArgumentValueError(
|
||||
f"Argument placeholder {reason}: {key}"
|
||||
)
|
||||
|
||||
return str(placeholders[key])
|
||||
|
||||
return PLACEHOLDER_PATTERN.sub(replace, argument)
|
||||
|
||||
|
||||
class ArgumentMappings:
|
||||
@@ -217,7 +270,9 @@ def find_game_and_jvm_args(arguments: dict | str) -> tuple[list, list]:
|
||||
return game_args, jvm_args
|
||||
|
||||
|
||||
def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappings, features: dict | None = None) -> \
|
||||
def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappings,
|
||||
features: dict | None = None, *, extra_placeholders: dict | None = None,
|
||||
strict_placeholders: bool = False) -> \
|
||||
list[str]:
|
||||
if features is None:
|
||||
features = {}
|
||||
@@ -230,6 +285,9 @@ def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappin
|
||||
|
||||
placeholders = mappings.generate_placeholders()
|
||||
|
||||
if extra_placeholders:
|
||||
placeholders.update(extra_placeholders)
|
||||
|
||||
for argument in arguments:
|
||||
# Check rules
|
||||
if not is_argument_allowed(argument, allow_features=features):
|
||||
@@ -237,7 +295,7 @@ def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappin
|
||||
|
||||
# Each argument (section) may contain multiple items, convert it to list before replace placeholder
|
||||
for item in convert_argument_to_multiple_string(argument):
|
||||
parsed = replace_placeholders(item, placeholders)
|
||||
parsed = replace_placeholders(item, placeholders, strict=strict_placeholders)
|
||||
parsed_arguments.append(parsed)
|
||||
|
||||
return parsed_arguments
|
||||
@@ -265,19 +323,80 @@ def append_missing_necessary_jvm_arguments(arguments: list, arg_maps: ArgumentMa
|
||||
|
||||
return result
|
||||
|
||||
def add_feature_arguments(arguments: dict, arg_maps: ArgumentMappings, features: dict | None = None) -> list[str]:
|
||||
result = []
|
||||
def find_match_feature_argument(arguments: list | str, feature) -> dict | None:
|
||||
if isinstance(arguments, str):
|
||||
arguments = shlex.split(arguments)
|
||||
|
||||
if features is None:
|
||||
return result
|
||||
for argument in arguments:
|
||||
# Check rules
|
||||
if not is_argument_allowed(argument, allow_features=feature):
|
||||
continue
|
||||
|
||||
if features.get("has_custom_resolution"):
|
||||
result.append(f"-Dminecraft.overrideResolution={features['resolution']}")
|
||||
# Only dict argument has feature rule
|
||||
if not isinstance(argument, dict):
|
||||
continue
|
||||
|
||||
return argument
|
||||
|
||||
return None
|
||||
|
||||
def generate_enabled_feature_arguments(arguments: list | str, arg_maps: ArgumentMappings,
|
||||
features: dict | None = None, feature_placeholders: dict | None=None,
|
||||
strict_placeholders=False) -> list[str]:
|
||||
enabled_features = dict(features or {})
|
||||
extra_values = dict(feature_placeholders or {})
|
||||
|
||||
values = arg_maps.generate_placeholders()
|
||||
values.update(extra_values)
|
||||
|
||||
for name, enabled in enabled_features.items():
|
||||
if type(enabled) is not bool:
|
||||
raise ArgumentValueError(
|
||||
f"Feature {name} must be a boolean."
|
||||
)
|
||||
|
||||
if not enabled:
|
||||
continue
|
||||
|
||||
spec = FEATURE_SPECS.get(name)
|
||||
|
||||
# Ignore unknown feature flag, hand it to parse_and_generate_arguments
|
||||
if spec is None:
|
||||
continue
|
||||
|
||||
for key in spec.required_placeholders:
|
||||
if key not in values or values[key] is None or values[key] == "":
|
||||
raise ArgumentValueError(
|
||||
f"Feature {name} requires placeholder {key}."
|
||||
)
|
||||
|
||||
if spec.validate:
|
||||
spec.validate(values)
|
||||
|
||||
return parse_and_generate_arguments(
|
||||
arguments,
|
||||
arg_maps,
|
||||
features=enabled_features,
|
||||
extra_placeholders=extra_values,
|
||||
strict_placeholders=strict_placeholders,
|
||||
)
|
||||
|
||||
def generate_feature_placeholders(maps: ArgumentMappings):
|
||||
if not isinstance(maps.resolution, tuple):
|
||||
width, height = None, None
|
||||
else:
|
||||
width = maps.resolution[0]
|
||||
height = maps.resolution[1] or None
|
||||
|
||||
return {
|
||||
"resolution_width": width,
|
||||
"resolution_height": height,
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_path: str, full_args: dict | str
|
||||
, features: dict | None = None, user_jvm_args: list[str] | None | str = None) -> list[str]:
|
||||
, features: dict | None = None, user_jvm_args: list[str] | None | str = None,
|
||||
strict_placeholders=False) -> list[str]:
|
||||
cmd = [java_path]
|
||||
game_args, jvm_args = find_game_and_jvm_args(full_args)
|
||||
|
||||
@@ -296,6 +415,7 @@ def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_pa
|
||||
default_args,
|
||||
arg_maps,
|
||||
features=features,
|
||||
strict_placeholders=strict_placeholders,
|
||||
)
|
||||
else:
|
||||
# Use jvm arguments that provided by user
|
||||
@@ -305,13 +425,17 @@ def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_pa
|
||||
jvm_args,
|
||||
arg_maps,
|
||||
features=features,
|
||||
strict_placeholders=strict_placeholders,
|
||||
)
|
||||
|
||||
parsed_game_args = parse_and_generate_arguments(
|
||||
feature_placeholders = generate_feature_placeholders(arg_maps)
|
||||
parsed_game_args = generate_enabled_feature_arguments(
|
||||
game_args,
|
||||
arg_maps,
|
||||
features=features,
|
||||
)
|
||||
feature_placeholders=feature_placeholders,
|
||||
strict_placeholders=strict_placeholders,
|
||||
) # Generate arguments that enabled by features and necessary arguments that from manifest
|
||||
|
||||
# Legacy Minecraft don't have jvm arguments exist in the version library. We need to generate by ourselves
|
||||
parsed_jvm_args = append_missing_necessary_jvm_arguments(
|
||||
@@ -322,7 +446,6 @@ def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_pa
|
||||
cmd.extend(parsed_jvm_args)
|
||||
cmd.append(main_class)
|
||||
cmd.extend(parsed_game_args)
|
||||
|
||||
return cmd
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from typing import Callable
|
||||
|
||||
import requests
|
||||
|
||||
from core_lib.common.exception import AuthenticationSessionException, AuthenticationConnectException, \
|
||||
from core_lib.common.exception import LauncherException, AuthenticationSessionException, AuthenticationConnectException, \
|
||||
AuthenticationException, LauncherHTTPException
|
||||
|
||||
MICROSOFT_DEVICE_CODE_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"
|
||||
@@ -259,7 +259,8 @@ def get_xbox_token_and_user_hash(access_token: str) -> tuple[str, str, dict]:
|
||||
data = auth_exception_handler(_request_handler, stage="Signing in to Xbox Live")
|
||||
return verify_data(data)
|
||||
|
||||
def get_xsts_token(xbox_token: str) -> tuple[str, dict]:
|
||||
def get_xsts_token(xbox_token: str, *,
|
||||
relying_party: str = "rp://api.minecraftservices.com/") -> tuple[str, dict]:
|
||||
"""
|
||||
Get xsts token
|
||||
:param xbox_token:
|
||||
@@ -270,9 +271,9 @@ def get_xsts_token(xbox_token: str) -> tuple[str, dict]:
|
||||
def _request_handler():
|
||||
r = requests.post(XSTS_AUTH_URL, json={
|
||||
"Properties": {"SandboxId": "RETAIL", "UserTokens": [xbox_token]},
|
||||
"RelyingParty": "rp://api.minecraftservices.com/",
|
||||
"RelyingParty": relying_party,
|
||||
"TokenType": "JWT",
|
||||
}, headers={"Accept": "application/json"})
|
||||
}, headers={"Accept": "application/json"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
@@ -295,6 +296,37 @@ def get_xsts_token(xbox_token: str) -> tuple[str, dict]:
|
||||
|
||||
return verify_data(data)
|
||||
|
||||
def extract_xuid(data: dict, user_hash: str) -> str | None:
|
||||
"""Read the numeric Xbox ID for the same user as the authentication chain."""
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
claims = data.get("DisplayClaims")
|
||||
users = claims.get("xui") if isinstance(claims, dict) else None
|
||||
if not isinstance(users, list):
|
||||
return None
|
||||
for user in users:
|
||||
if not isinstance(user, dict) or user.get("uhs") != user_hash:
|
||||
continue
|
||||
xuid = user.get("xid")
|
||||
if isinstance(xuid, str) and len(xuid) <= 20 and xuid.isascii() and xuid.isdecimal():
|
||||
if 0 < int(xuid) < 2 ** 64:
|
||||
return xuid
|
||||
return None
|
||||
|
||||
|
||||
def get_xbox_xuid(xbox_token: str, user_hash: str, xsts_data: dict) -> str | None:
|
||||
"""Best-effort XUID lookup without changing the Minecraft token's relying party."""
|
||||
xuid = extract_xuid(xsts_data, user_hash)
|
||||
if xuid is not None:
|
||||
return xuid
|
||||
try:
|
||||
_, xbox_data = get_xsts_token(xbox_token, relying_party="https://xboxlive.com")
|
||||
except (LauncherException, requests.RequestException):
|
||||
logger.warning("Unable to retrieve optional Xbox user ID; continuing without it.")
|
||||
return None
|
||||
return extract_xuid(xbox_data, user_hash)
|
||||
|
||||
|
||||
def get_minecraft_access_token(user_hash: str, xsts_token: str) -> tuple[str, dict]:
|
||||
"""
|
||||
Get minecraft access token
|
||||
|
||||
@@ -6,6 +6,7 @@ def create_messagebox(parent: QWidget | None, title: str, message: str,
|
||||
icon: QMessageBox.Icon = QMessageBox.Icon.Information,
|
||||
button: QMessageBox.StandardButton = QMessageBox.StandardButton.Ok) -> QMessageBox:
|
||||
msg = QMessageBox(parent)
|
||||
msg.setOption(QMessageBox.Option.DontUseNativeDialog, True)
|
||||
msg.setWindowTitle(title)
|
||||
msg.setText(message)
|
||||
msg.setIcon(icon)
|
||||
|
||||
@@ -155,9 +155,10 @@ class ProgressDialog(QDialog):
|
||||
row = self.rows[task_id]
|
||||
|
||||
row.status_label.setText(f"Failed: {error}")
|
||||
row.progress_bar.setStyleSheet(
|
||||
"QProgressBar::chunk { background-color: #c62828; }"
|
||||
)
|
||||
row.progress_bar.setProperty("failed", True)
|
||||
row.progress_bar.style().unpolish(row.progress_bar)
|
||||
row.progress_bar.style().polish(row.progress_bar)
|
||||
row.progress_bar.update()
|
||||
# Move to top
|
||||
self.download_layout.removeWidget(row)
|
||||
self.download_layout.insertWidget(0, row)
|
||||
|
||||
Reference in new issue
Block a user