about summary refs log tree commit diff stats
path: root/fungus/shortcuts.py
blob: ae2a193ce13efc2b7e46caa6b2639325b2285518 (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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Desktop shortcut and icon helpers for Fungus Launcher.

Provides functions to create and remove ``.desktop`` entries,
check whether a shortcut already exists, and prepare shortcut
icon previews (GTK-dependent).
"""

from __future__ import annotations

import os
import shutil
from typing import TYPE_CHECKING

from gi.repository import GdkPixbuf, Gtk  # type: ignore

from fungus.constants import (
    app_dir,
    desktop_dir,
    fungus_png,
    fungus_run,
    icons_dir,
)
from fungus.utils_pure import format_title

if TYPE_CHECKING:
    from fungus.game_model import Game


# ── .desktop shortcut management ──────────────────────────────────────────


def create_shortcut(
    game: Game,
    shortcut_state: bool,
    shortcut: str,
    icon_temp: str,
    icon_final: str,
) -> None:
    """Create or remove a ``.desktop`` shortcut for *game*.

    Parameters
    ----------
    game : Game
        The game entry.
    shortcut_state : bool
        If ``True`` a shortcut is created; if ``False`` it is removed.
    shortcut : str
        Either ``"desktop"``, ``"appmenu"``, or ``"both"``.
    icon_temp : str
        Temporary icon path (copied/renamed to *icon_final*).
    icon_final : str
        Final icon path on disk.
    """
    applications_shortcut_path = f"{app_dir}/{game.gameid}.desktop"
    desktop_shortcut_path = f"{desktop_dir}/{game.gameid}.desktop"

    if not shortcut_state:
        remove_shortcut(game, shortcut)
        # Move icon even when no shortcut is created
        if os.path.isfile(os.path.expanduser(icon_temp)):
            os.rename(os.path.expanduser(icon_temp), icon_final)
        return

    # Move icon to final location
    if os.path.isfile(os.path.expanduser(icon_temp)):
        os.rename(os.path.expanduser(icon_temp), icon_final)

    new_icon_path = f"{icons_dir}/{game.gameid}.ico"
    if not os.path.exists(new_icon_path):
        new_icon_path = fungus_png

    game_directory = os.path.dirname(game.path)

    desktop_file_content = (
        f'[Desktop Entry]\n'
        f'Name={game.title}\n'
        f'Exec={fungus_run} --game {game.gameid}\n'
        f'Icon={new_icon_path}\n'
        f'Type=Application\n'
        f'Categories=Game;\n'
        f'Path={game_directory}\n'
    )

    if not os.path.exists(app_dir):
        os.makedirs(app_dir)
    if not os.path.exists(desktop_dir):
        os.makedirs(desktop_dir)

    if shortcut == "appmenu":
        with open(applications_shortcut_path, "w") as fh:
            fh.write(desktop_file_content)
        os.chmod(applications_shortcut_path, 0o755)

    if shortcut == "desktop":
        with open(desktop_shortcut_path, "w") as fh:
            fh.write(desktop_file_content)
        os.chmod(desktop_shortcut_path, 0o755)


def remove_shortcut(game: Game, shortcut: str) -> None:
    """Delete the ``.desktop`` shortcut for *game*.

    Parameters
    ----------
    game : Game
        The game entry.
    shortcut : str
        Either ``"desktop"``, ``"appmenu"``, or ``"both"``.
    """
    applications_shortcut_path = f"{app_dir}/{game.gameid}.desktop"
    desktop_shortcut_path = f"{desktop_dir}/{game.gameid}.desktop"

    if shortcut in ("appmenu", "both"):
        if os.path.exists(applications_shortcut_path):
            os.remove(applications_shortcut_path)
    if shortcut in ("desktop", "both"):
        if os.path.exists(desktop_shortcut_path):
            os.remove(desktop_shortcut_path)


def shortcut_exists(game: Game, shortcut: str) -> bool:
    """Return ``True`` if a ``.desktop`` shortcut for *game* exists.

    Parameters
    ----------
    game : Game
        The game entry.
    shortcut : str
        Either ``"desktop"``, ``"appmenu"``, or ``"both"``.
    """
    applications_shortcut_path = f"{app_dir}/{game.gameid}.desktop"
    desktop_shortcut_path = f"{desktop_dir}/{game.gameid}.desktop"

    if shortcut == "appmenu":
        return os.path.exists(applications_shortcut_path)
    if shortcut == "desktop":
        return os.path.exists(desktop_shortcut_path)
    # "both" — exists if either exists
    return os.path.exists(applications_shortcut_path) or os.path.exists(
        desktop_shortcut_path
    )


# ── Pure utility ──────────────────────────────────────────────────────────


def find_largest_resolution(directory: str) -> str | None:
    """Find the image file with the largest pixel area in *directory*.

    Parameters
    ----------
    directory : str
        Directory to search.

    Returns
    -------
    str or None
        Path to the largest image file, or ``None`` if none found.
    """
    from PIL import Image

    largest_image: str | None = None
    largest_resolution = (0, 0)  # (width, height)

    valid_extensions = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff"}

    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if not os.path.isfile(file_path):
            continue
        if os.path.splitext(file_name)[1].lower() not in valid_extensions:
            continue
        try:
            with Image.open(file_path) as img:
                width, height = img.size
                if width * height > largest_resolution[0] * largest_resolution[1]:
                    largest_resolution = (width, height)
                    largest_image = file_path
        except OSError:
            pass

    return largest_image


# ── GTK-dependent icon helpers ────────────────────────────────────────────


def set_image_shortcut_icon(
    title: str,
    icons_path: str,
    icon_temp: str,
) -> Gtk.Image:
    """Prepare a scaled icon image for use in a dialog widget.

    Copies the stored icon for *title* into *icon_temp* (falling back
    to the default *fungus_png* if no icon exists), then creates and
    returns a scaled ``Gtk.Image`` widget.

    Parameters
    ----------
    title : str
        Game title (used to locate the stored icon).
    icons_path : str
        Directory where game icons are stored.
    icon_temp : str
        Path to write the temporary icon file.

    Returns
    -------
    Gtk.Image
        A scaled (50x50) image widget.
    """
    title_formatted = format_title(title)
    icon_path = os.path.join(icons_path, f"{title_formatted}.ico")

    if os.path.exists(icon_path):
        shutil.copyfile(icon_path, icon_temp)
    if not os.path.exists(icon_path):
        icon_temp = fungus_png

    pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon_temp)
    scaled_pixbuf = pixbuf.scale_simple(50, 50, GdkPixbuf.InterpType.BILINEAR)

    image = Gtk.Image.new_from_file(icon_temp)
    image.set_from_pixbuf(scaled_pixbuf)

    return image


def set_default_icon(icon_temp: str) -> Gtk.Image:
    """Set the default launcher icon as a scaled preview widget.

    Parameters
    ----------
    icon_temp : str
        Path to write the temporary icon file.

    Returns
    -------
    Gtk.Image
        A scaled (50x50) image widget.
    """
    shutil.copyfile(fungus_png, icon_temp)

    pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon_temp)
    scaled_pixbuf = pixbuf.scale_simple(50, 50, GdkPixbuf.InterpType.BILINEAR)

    image = Gtk.Image.new_from_file(icon_temp)
    image.set_from_pixbuf(scaled_pixbuf)

    return image