about summary refs log tree commit diff stats
path: root/fungus/utils_pure.py
blob: 88c156e8e8ba7c9959c4a7975474099dcdfc1b1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/python3

"""Pure utility functions — no GTK/GI dependencies.

These can be imported and tested in isolation.
"""

import os
import re
from pathlib import Path


def format_title(title):
    """Normalize a title into a slug-like identifier.

    Lowercases, strips, removes non-alphanumeric characters (except spaces),
    and collapses whitespace to single hyphens.
    """
    title = title.strip().lower()
    title = re.sub(r"[^a-z0-9 ]+", "", title)
    return re.sub(r"\s+", "-", title)


def is_valid_prefix_path(path: str) -> bool:
    """Check whether *path* lies within the configured prefixes directory.

    Returns ``True`` only if the resolved path is the prefixes directory
    itself or a descendant of it.
    """
    from fungus.constants import prefixes_dir

    expanded = os.path.expanduser(path)
    resolved = os.path.realpath(expanded)
    safe_root = os.path.realpath(prefixes_dir)

    return resolved == safe_root or resolved.startswith(safe_root + os.sep)


def is_safe_prefix_path(path: str) -> bool:
    """Check whether *path* is a safe target for recursive deletion.

    Returns ``True`` only if the resolved path lies within the fungus
    user-data or user-config directories (``~/.local/share/fungus-launcher``
    or ``~/.config/fungus-launcher``), or is one of those directories
    itself.
    """
    from fungus.path_manager import PathManager

    expanded = os.path.expanduser(path)
    resolved = os.path.realpath(expanded)

    safe_roots = [
        os.path.realpath(PathManager.user_data()),
        os.path.realpath(PathManager.user_config()),
    ]

    for root in safe_roots:
        if resolved == root or resolved.startswith(root + os.sep):
            return True

    return False


def _resolve_runner_to_directory(runner):
    """Resolve an old-style runner name to the actual directory on disk.

    If a matching directory exists in compatibilitytools.d, return it.
    Otherwise fall back to the newest installed version of that family,
    or None if nothing is available.
    """
    from fungus.constants import share_dir

    compat_path = Path(share_dir) / "Steam/compatibilitytools.d"
    if not compat_path.exists():
        return None

    # Direct directory names pass through unchanged
    if (compat_path / runner).is_dir():
        return runner

    old_aliases = {
        "Proton-GE Latest": "GE-Proton",
        "GE-Proton Latest (default)": "GE-Proton",
        "Proton-EM Latest": "Proton-EM",
        "UMU-Proton Latest": None,  # no directory equivalent
    }

    family = old_aliases.get(runner)
    if family is None:
        return None  # Linux-Native, Steam, or unknown — caller handles

    # Find matching directories in compatibilitytools.d
    matches = [
        d for d in compat_path.iterdir()
        if d.is_dir() and d.name.startswith(family)
    ]
    if not matches:
        return None  # user hasn't installed any version yet

    def sort_key(d):
        parts = re.split(r'(\d+)', d.name.replace(family, ''))
        return [int(p) if p.isdigit() else p for p in parts]

    matches.sort(key=sort_key, reverse=True)
    return matches[0].name


def has_proton_installed() -> bool:
    """Check whether any proton/compatibility tool directories exist on disk."""
    from fungus.constants import share_dir

    compat_path = Path(share_dir) / "Steam/compatibilitytools.d"
    if not compat_path.exists():
        return False

    for entry in compat_path.iterdir():
        if entry.is_dir() and entry.name not in ("LegacyRuntime",):
            return True
    return False


def is_executable_in_whitelist(exec_path: str, game_dirs: list[str]) -> bool:
    """Check whether *exec_path* resides inside one of the whitelisted directories.

    The executable directory (or the file itself) must be a prefix of, or equal
    to, at least one whitelisted directory.

    Returns ``True`` if *game_dirs* is empty (no whitelist configured) or if the
    executable path falls within a whitelisted directory.
    """
    if not game_dirs:
        return True  # no whitelist configured — allow everything

    exec_dir = os.path.realpath(os.path.dirname(os.path.abspath(exec_path)))

    for whitelisted in game_dirs:
        wl_real = os.path.realpath(whitelisted)
        match_exact = exec_dir == wl_real
        match_prefix = exec_dir.startswith(wl_real + os.sep)
        if match_exact or match_prefix:
            return True

    return False