Skip to content

Commit

Permalink
style: update format
Browse files Browse the repository at this point in the history
  • Loading branch information
R1kaB3rN committed Dec 29, 2024
1 parent 3bad427 commit 9849c74
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 433 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ exclude = [
"subprojects",
]
# Same as Black.
line-length = 79
line-length = 88
indent-width = 4
target-version = "py310"

Expand Down
8 changes: 2 additions & 6 deletions umu/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def parse_args() -> Namespace | tuple[str, list[str]]: # noqa: D103
version=f"umu-launcher version {__version__} ({sys.version})",
help="show this version and exit",
)
parser.add_argument(
"--config", help=("path to TOML file (requires Python 3.11+)")
)
parser.add_argument("--config", help=("path to TOML file (requires Python 3.11+)"))
parser.add_argument(
"winetricks",
help=("run winetricks verbs (requires UMU-Proton or GE-Proton)"),
Expand All @@ -56,9 +54,7 @@ def parse_args() -> Namespace | tuple[str, list[str]]: # noqa: D103
sys.exit(1)

# Exit if argument is not a verb
if sys.argv[1].endswith("winetricks") and not is_winetricks_verb(
sys.argv[2:]
):
if sys.argv[1].endswith("winetricks") and not is_winetricks_verb(sys.argv[2:]):
sys.exit(1)

if sys.argv[1:][0] in opt_args:
Expand Down
4 changes: 1 addition & 3 deletions umu/umu_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ def format(self, record: LogRecord) -> str: # noqa: D102
color = Color.WARNING
case _:
color = Color.BOLD
record.levelname = (
f"{color}{Color.BOLD}{record.levelname}{Color.RESET}"
)
record.levelname = f"{color}{Color.BOLD}{record.levelname}{Color.RESET}"
return super().format(record)


Expand Down
11 changes: 3 additions & 8 deletions umu/umu_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@ def _check_env_toml(toml: dict[str, Any]) -> dict[str, Any]:
path: Path

if key not in toml[table]:
err: str = (
f"The following key in table '[{table}]' is required: '{key}'"
)
err: str = f"The following key in table '[{table}]' is required: '{key}'"
raise ValueError(err)

path = Path(toml[table][key]).expanduser()
Expand All @@ -95,17 +93,14 @@ def _check_env_toml(toml: dict[str, Any]) -> dict[str, Any]:
# can happen is when game options are appended at the end of the exe.
# Users should use `launch_args` for game options
if key == "exe" and not path.is_file():
err: str = (
f"Value for key '{key}' is not a file: '{toml[table][key]}'"
)
err: str = f"Value for key '{key}' is not a file: '{toml[table][key]}'"
raise FileNotFoundError(err)

if (key == "proton" and not path.is_dir()) or (
key == "prefix" and not path.is_dir()
):
err: str = (
f"Value for key '{key}' "
f"is not a directory: '{toml[table][key]}'"
f"Value for key '{key}' " f"is not a directory: '{toml[table][key]}'"
)
raise NotADirectoryError(err)

Expand Down
57 changes: 14 additions & 43 deletions umu/umu_proton.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@
SessionCaches = tuple[CacheTmpfs, CacheSubdir]


def get_umu_proton(
env: dict[str, str], session_pools: SessionPools
) -> dict[str, str]:
def get_umu_proton(env: dict[str, str], session_pools: SessionPools) -> dict[str, str]:
"""Attempt to use the latest Proton when configured.
When $PROTONPATH is not set or $PROTONPATH is 'GE-Proton', the launcher
Expand Down Expand Up @@ -66,10 +64,7 @@ def get_umu_proton(
TemporaryDirectory(dir=UMU_CACHE) as tmpcache,
):
tmpdirs: SessionCaches = (Path(tmp), Path(tmpcache))
if (
_get_latest(env, STEAM_COMPAT, tmpdirs, assets, session_pools)
is env
):
if _get_latest(env, STEAM_COMPAT, tmpdirs, assets, session_pools) is env:
return env
if _get_from_steamcompat(env, STEAM_COMPAT) is env:
return env
Expand Down Expand Up @@ -100,9 +95,7 @@ def _fetch_releases(
if os.environ.get("PROTONPATH") == "GE-Proton":
repo = "/repos/GloriousEggroll/proton-ge-custom/releases/latest"

resp = http_pool.request(
HTTPMethod.GET.value, f"{url}{repo}", headers=headers
)
resp = http_pool.request(HTTPMethod.GET.value, f"{url}{repo}", headers=headers)
if resp.status != HTTPStatus.OK:
return ()

Expand Down Expand Up @@ -153,12 +146,8 @@ def _fetch_proton(
hashsum = sha512()

# Verify the scheme from Github for resources
if not tar_url.startswith("https:") or not proton_hash_url.startswith(
"https:"
):
err: str = (
f"Scheme in URLs is not 'https:': {(tar_url, proton_hash_url)}"
)
if not tar_url.startswith("https:") or not proton_hash_url.startswith("https:"):
err: str = f"Scheme in URLs is not 'https:': {(tar_url, proton_hash_url)}"
raise ValueError(err)

# Digest file
Expand Down Expand Up @@ -233,9 +222,7 @@ def _fetch_proton(
HTTPStatus.PARTIAL_CONTENT,
HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
}:
err: str = (
f"{resp.getheader('Host')} returned the status: {resp.status}"
)
err: str = f"{resp.getheader('Host')} returned the status: {resp.status}"
raise HTTPError(err)

# Only write our file if we're resuming or downloading first time
Expand All @@ -245,9 +232,7 @@ def _fetch_proton(
hashsum = write_file_chunks(parts, resp, hashsum)
except TimeoutErrorUrllib3:
log.error("Aborting Proton install due to network error")
log.info(
"Moving '%s' to cache for future resumption", parts.name
)
log.info("Moving '%s' to cache for future resumption", parts.name)
log.debug("Moving: %s -> %s", parts, cache.parent)
move(parts, cache.parent)
raise
Expand Down Expand Up @@ -280,9 +265,7 @@ def _get_from_steamcompat(
existing Proton build of that same version will be used
"""
version: str = (
"GE-Proton"
if os.environ.get("PROTONPATH") == "GE-Proton"
else "UMU-Proton"
"GE-Proton" if os.environ.get("PROTONPATH") == "GE-Proton" else "UMU-Proton"
)

try:
Expand Down Expand Up @@ -338,9 +321,7 @@ def _get_latest(
tarball = assets[1][0]
proton = tarball.removesuffix(".tar.gz")
version = (
"GE-Proton"
if os.environ.get("PROTONPATH") == "GE-Proton"
else "UMU-Proton"
"GE-Proton" if os.environ.get("PROTONPATH") == "GE-Proton" else "UMU-Proton"
)

# Return if the latest Proton is already installed
Expand Down Expand Up @@ -434,9 +415,7 @@ def _install_proton(
parts: str = f"{tarball}.parts"
cached_parts: Path = cache.parent.joinpath(f"{tarball}.parts")
version: str = (
"GE-Proton"
if os.environ.get("PROTONPATH") == "GE-Proton"
else "UMU-Proton"
"GE-Proton" if os.environ.get("PROTONPATH") == "GE-Proton" else "UMU-Proton"
)

# TODO: Refactor when differential updates are implemented.
Expand All @@ -452,26 +431,20 @@ def _install_proton(
# Move our file and extract within our cache
if cached_parts.is_file():
# In this case, arc is already in cache and checksum'd
log.debug(
"Moving: %s -> %s", cached_parts, cached_parts.with_suffix("")
)
log.debug("Moving: %s -> %s", cached_parts, cached_parts.with_suffix(""))
move(cached_parts, cached_parts.with_suffix(""))
# Move the archive to our unique subdir
log.debug("Moving: %s -> %s", cached_parts.with_suffix(""), cache)
move(cached_parts.with_suffix(""), cache)
log.info("Extracting %s...", tarball)
# Extract within the subdir
extract_tarfile(
cache.joinpath(tarball), cache.joinpath(tarball).parent
)
extract_tarfile(cache.joinpath(tarball), cache.joinpath(tarball).parent)
else:
# The archive is in tmpfs. Remove the parts extension
move(tmpfs.joinpath(parts), tmpfs.joinpath(tarball))
move(tmpfs.joinpath(tarball), cache)
log.info("Extracting %s...", tarball)
extract_tarfile(
cache.joinpath(tarball), cache.joinpath(tarball).parent
)
extract_tarfile(cache.joinpath(tarball), cache.joinpath(tarball).parent)

# Move decompressed archive to compatibilitytools.d
log.info(
Expand All @@ -482,9 +455,7 @@ def _install_proton(
move(cache.joinpath(tarball.removesuffix(".tar.gz")), steam_compat)

steam_compat.joinpath("UMU-Latest").unlink(missing_ok=True)
steam_compat.joinpath("UMU-Latest").symlink_to(
tarball.removesuffix(".tar.gz")
)
steam_compat.joinpath("UMU-Latest").symlink_to(tarball.removesuffix(".tar.gz"))
log.debug("Linking: UMU-Latest -> %s", tarball.removesuffix(".tar.gz"))

if future:
Expand Down
56 changes: 15 additions & 41 deletions umu/umu_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@
def setup_pfx(path: str) -> None:
"""Prepare a Proton compatible WINE prefix."""
pfx: Path = Path(path).joinpath("pfx").expanduser()
steam: Path = (
Path(path).expanduser().joinpath("drive_c", "users", "steamuser")
)
steam: Path = Path(path).expanduser().joinpath("drive_c", "users", "steamuser")
# Login name of the user as determined by the password database (pwd)
user: str = getpwuid(os.getuid()).pw_name
wineuser: Path = Path(path).expanduser().joinpath("drive_c", "users", user)
Expand Down Expand Up @@ -115,10 +113,7 @@ def check_env(
err: str = "Environment variable is empty: WINEPREFIX"
raise ValueError(err)

if (
os.environ.get("UMU_NO_PROTON") != "1"
and "WINEPREFIX" not in os.environ
):
if os.environ.get("UMU_NO_PROTON") != "1" and "WINEPREFIX" not in os.environ:
pfx: Path = Path.home().joinpath("Games", "umu", env["GAMEID"])
pfx.mkdir(parents=True, exist_ok=True)
os.environ["WINEPREFIX"] = str(pfx)
Expand All @@ -142,9 +137,7 @@ def check_env(
os.environ.get("PROTONPATH")
and Path(STEAM_COMPAT, os.environ["PROTONPATH"]).is_dir()
):
os.environ["PROTONPATH"] = str(
STEAM_COMPAT.joinpath(os.environ["PROTONPATH"])
)
os.environ["PROTONPATH"] = str(STEAM_COMPAT.joinpath(os.environ["PROTONPATH"]))

# GE-Proton
if os.environ.get("PROTONPATH") == "GE-Proton":
Expand Down Expand Up @@ -173,9 +166,7 @@ def set_env(
) -> dict[str, str]:
"""Set various environment variables for the Steam Runtime."""
pfx: Path = Path(env["WINEPREFIX"]).expanduser().resolve(strict=True)
protonpath: Path = (
Path(env["PROTONPATH"]).expanduser().resolve(strict=True)
)
protonpath: Path = Path(env["PROTONPATH"]).expanduser().resolve(strict=True)
# Command execution usage
is_cmd: bool = isinstance(args, tuple)
# Command execution usage, but client wants to create a prefix. When an
Expand All @@ -202,9 +193,7 @@ def set_env(
# Make an absolute path to winetricks within GE-Proton or UMU-Proton.
# The launcher will change to the winetricks parent directory before
# creating the subprocess
exe: Path = Path(protonpath, "protonfixes", "winetricks").resolve(
strict=True
)
exe: Path = Path(protonpath, "protonfixes", "winetricks").resolve(strict=True)
env["EXE"] = str(exe)
args = (env["EXE"], args[1]) # type: ignore
env["STEAM_COMPAT_INSTALL_PATH"] = str(exe.parent)
Expand Down Expand Up @@ -235,19 +224,15 @@ def set_env(
env["STEAM_COMPAT_APP_ID"] = "0"

if match(r"^umu-[\d\w]+$", env["UMU_ID"]):
env["STEAM_COMPAT_APP_ID"] = env["UMU_ID"][
env["UMU_ID"].find("-") + 1 :
]
env["STEAM_COMPAT_APP_ID"] = env["UMU_ID"][env["UMU_ID"].find("-") + 1 :]
env["SteamAppId"] = env["STEAM_COMPAT_APP_ID"]
env["SteamGameId"] = env["SteamAppId"]

# PATHS
env["WINEPREFIX"] = str(pfx)
env["PROTONPATH"] = str(protonpath)
env["STEAM_COMPAT_DATA_PATH"] = env["WINEPREFIX"]
env["STEAM_COMPAT_SHADER_PATH"] = (
f"{env['STEAM_COMPAT_DATA_PATH']}/shadercache"
)
env["STEAM_COMPAT_SHADER_PATH"] = f"{env['STEAM_COMPAT_DATA_PATH']}/shadercache"
env["STEAM_COMPAT_TOOL_PATHS"] = f"{env['PROTONPATH']}:{UMU_LOCAL}"
env["STEAM_COMPAT_MOUNTS"] = env["STEAM_COMPAT_TOOL_PATHS"]

Expand Down Expand Up @@ -385,9 +370,7 @@ def get_window_ids(d: display.Display) -> set[str] | None:
try:
event: Event = d.next_event()
if event.type == X.CreateNotify:
return {
child.id for child in d.screen().root.query_tree().children
}
return {child.id for child in d.screen().root.query_tree().children}
except Exception as e:
log.exception(e)

Expand Down Expand Up @@ -436,19 +419,15 @@ def get_gamescope_baselayer_appid(
# Intern the atom for GAMESCOPECTRL_BASELAYER_APPID
atom = d.get_atom(GamescopeAtom.BaselayerAppId.value)
# Get the property value
prop: GetProperty | None = root_primary.get_full_property(
atom, Xatom.CARDINAL
)
prop: GetProperty | None = root_primary.get_full_property(atom, Xatom.CARDINAL)
# For GAMESCOPECTRL_BASELAYER_APPID, the value is a u32 array
if prop and prop.value and isinstance(prop.value, array):
# Convert data to a Python list for safety
baselayer_appid = prop.value.tolist()
return baselayer_appid
log.debug("%s property not found", GamescopeAtom.BaselayerAppId.value)
except Exception as e:
log.error(
"Error getting %s property", GamescopeAtom.BaselayerAppId.value
)
log.error("Error getting %s property", GamescopeAtom.BaselayerAppId.value)
log.exception(e)

return None
Expand Down Expand Up @@ -499,9 +478,7 @@ def set_gamescope_baselayer_appid(
)
return d
except Exception as e:
log.error(
"Error setting %s property", GamescopeAtom.BaselayerAppId.value
)
log.error("Error setting %s property", GamescopeAtom.BaselayerAppId.value)
log.exception(e)

return None
Expand Down Expand Up @@ -577,8 +554,8 @@ def monitor_baselayer_appid(
atom,
prop.value,
)
rearranged_gamescope_baselayer = (
rearrange_gamescope_baselayer_appid(prop.value)
rearranged_gamescope_baselayer = rearrange_gamescope_baselayer_appid(
prop.value
)

if rearranged_gamescope_baselayer:
Expand Down Expand Up @@ -649,9 +626,7 @@ def run_in_steammode(proc: Popen) -> int:
xdisplay(":0") as d_primary,
xdisplay(":1") as d_secondary,
):
gamescope_baselayer_sequence = get_gamescope_baselayer_appid(
d_primary
)
gamescope_baselayer_sequence = get_gamescope_baselayer_appid(d_primary)
# Dont do window fuckery if we're not inside gamescope
if (
gamescope_baselayer_sequence
Expand Down Expand Up @@ -700,8 +675,7 @@ def run_command(command: tuple[Path | str, ...]) -> int:
# Note: STEAM_MULTIPLE_XWAYLANDS is steam mode specific and is
# documented to be a legacy env var.
is_steammode: bool = (
is_gamescope_session
and os.environ.get("STEAM_MULTIPLE_XWAYLANDS") == "1"
is_gamescope_session and os.environ.get("STEAM_MULTIPLE_XWAYLANDS") == "1"
)

if not command:
Expand Down
Loading

0 comments on commit 9849c74

Please sign in to comment.