diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-07-03 16:34:32 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-07-03 16:34:32 +0300 |
| commit | 6a8facd03d3881adadd5bf98904a88faba96d8e3 (patch) | |
| tree | 5046fdd753c6c592fbae4999b8139c9afb1b87c1 | |
| parent | b30650d31fbb609de3fd015f85230013d6a58689 (diff) | |
| download | fungus-launcher-6a8facd03d3881adadd5bf98904a88faba96d8e3.tar.gz fungus-launcher-6a8facd03d3881adadd5bf98904a88faba96d8e3.tar.xz | |
start splitting more non-UI code into non-UI modules
| -rw-r--r-- | fungus/add_game_dialog.py | 57 | ||||
| -rw-r--r-- | fungus/dialogs.py | 92 | ||||
| -rw-r--r-- | fungus/main_window.py | 90 | ||||
| -rw-r--r-- | fungus/meson.build | 1 | ||||
| -rw-r--r-- | fungus/run_manager.py | 195 | ||||
| -rw-r--r-- | fungus/shortcuts.py | 254 |
6 files changed, 409 insertions, 280 deletions
diff --git a/fungus/add_game_dialog.py b/fungus/add_game_dialog.py index c0f816d..f2a565e 100644 --- a/fungus/add_game_dialog.py +++ b/fungus/add_game_dialog.py @@ -6,6 +6,7 @@ import gi # type: ignore gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') +gi.require_version("GdkPixbuf", "3.0") import os import shutil @@ -30,6 +31,10 @@ from fungus.constants import ( prefixes_dir, ) +from fungus.shortcuts import ( + set_default_icon, + find_largest_resolution, +) from fungus.utils import ( EntryTooltipMixin, format_title, @@ -530,16 +535,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): def set_image_shortcut_icon(self): """Set the default icon (fungus_png) as the shortcut icon preview.""" - image_path = fungus_png - shutil.copyfile(image_path, self.icon_temp) - - pixbuf = GdkPixbuf.Pixbuf.new_from_file(self.icon_temp) - scaled_pixbuf = pixbuf.scale_simple(50, 50, GdkPixbuf.InterpType.BILINEAR) - - image = Gtk.Image.new_from_file(self.icon_temp) - image.set_from_pixbuf(scaled_pixbuf) - - return image + return set_default_icon(self.icon_temp) def on_button_shortcut_icon_clicked(self, widget): """Extract an icon from the game executable or let the user pick one.""" @@ -667,28 +663,8 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.set_sensitive(True) def find_largest_resolution(self, directory): - """Find the image file with the largest pixel area in *directory*.""" - largest_image = None - largest_resolution = (0, 0) # (width, height) - - # Define a set of valid image extensions - valid_image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff'} - - for file_name in os.listdir(directory): - file_path = os.path.join(directory, file_name) - if os.path.isfile(file_path): - # Check if the file has a valid image extension - if os.path.splitext(file_name)[1].lower() in valid_image_extensions: - 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: - log.debug("Unable to open %s", file_path) - - return largest_image + """Delegate to the shared largest-resolution finder.""" + return find_largest_resolution(directory) def update_preview(self, dialog): """Show a scaled thumbnail preview in a file-chooser dialog.""" @@ -720,19 +696,18 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): dialog.set_preview_widget_active(False) def check_existing_shortcut(self): - """Mark the desktop/appmenu checkboxes if a shortcut for the current title already exists.""" - # Check if the shortcut already exists and mark or unmark the checkbox + """Mark the desktop/appmenu checkboxes if a shortcut already exists.""" title = self.entry_title.get_text().strip() if not title: - return # If there's no title, there's no shortcut to check + return - title_formatted = format_title(title) - desktop_file_path = f"{desktop_dir}/{title_formatted}.desktop" - applications_shortcut_path = f"{app_dir}/{title_formatted}.desktop" + # Build a minimal Game-like object for the lookup + gameid = format_title(title) + desktop_exists = os.path.exists(f"{desktop_dir}/{gameid}.desktop") + appmenu_exists = os.path.exists(f"{app_dir}/{gameid}.desktop") - # Mark the checkbox if the shortcut exists - self.checkbox_shortcut_desktop.set_active(os.path.exists(desktop_file_path)) - self.checkbox_shortcut_appmenu.set_active(os.path.exists(applications_shortcut_path)) + self.checkbox_shortcut_desktop.set_active(desktop_exists) + self.checkbox_shortcut_appmenu.set_active(appmenu_exists) def on_button_winecfg_clicked(self, widget): """Launch winecfg inside the Wine prefix via fungus_run.""" diff --git a/fungus/dialogs.py b/fungus/dialogs.py index 29a59df..4764464 100644 --- a/fungus/dialogs.py +++ b/fungus/dialogs.py @@ -123,6 +123,98 @@ class GameDirectoriesNotConfiguredDialog(Gtk.MessageDialog): self.destroy() +def create_error_dialog( + title: str, + primary: str, + secondary: str | None = None, + error_text: str | None = None, + *, + quit_app: bool = False, +) -> None: + """Build and display a modal error dialog. + + Parameters + ---------- + title : str + Dialog window title. + primary : str + Primary message (always shown, centred, line-wrapped). + secondary : str, optional + Secondary message shown below *primary*. Ignored when ``None``. + error_text : str, optional + Raw error output shown in a scrollable text view below the labels. + Ignored when ``None`` or empty. + quit_app : bool, default False + If ``True``, call ``Gtk.main_quit()`` and ``sys.exit()`` after + the dialog is dismissed. + """ + from gi.repository import Gtk # type: ignore + import sys + + from fungus.constants import fungus_png + + dialog = Gtk.Dialog(title=title) + dialog.set_resizable(False) + dialog.set_icon_from_file(fungus_png) + + content_area = dialog.get_content_area() + content_area.set_border_width(0) + content_area.set_halign(Gtk.Align.CENTER) + content_area.set_valign(Gtk.Align.CENTER) + content_area.set_vexpand(True) + content_area.set_hexpand(True) + + box_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) + box_top.set_margin_start(20) + box_top.set_margin_end(20) + box_top.set_margin_top(20) + box_top.set_margin_bottom(20) + + label = Gtk.Label(label=primary) + label.set_halign(Gtk.Align.CENTER) + label.set_line_wrap(True) + label.set_max_width_chars(60) + box_top.pack_start(label, True, True, 0) + + if secondary: + label2 = Gtk.Label(label=secondary) + label2.set_halign(Gtk.Align.CENTER) + box_top.pack_start(label2, True, True, 0) + + if error_text: + scrolled = Gtk.ScrolledWindow() + scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scrolled.set_min_content_height(120) + text_view = Gtk.TextView() + text_view.set_editable(False) + text_view.set_cursor_visible(False) + buffer = text_view.get_buffer() + buffer.set_text(error_text) + scrolled.add(text_view) + box_top.pack_start(scrolled, True, True, 0) + + button_ok = Gtk.Button(label="Ok") + button_ok.set_size_request(150, -1) + button_ok.connect("clicked", lambda w: dialog.response(Gtk.ResponseType.OK)) + + box_bottom = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) + box_bottom.set_margin_start(10) + box_bottom.set_margin_end(10) + box_bottom.set_margin_bottom(10) + box_bottom.pack_start(button_ok, True, True, 0) + + content_area.add(box_top) + content_area.add(box_bottom) + + dialog.show_all() + dialog.run() + dialog.destroy() + + if quit_app: + Gtk.main_quit() + sys.exit() + + class SteamRuntimeWarningDialog(Gtk.MessageDialog): """Warn the user that the UMU Steam Runtime is not available.""" diff --git a/fungus/main_window.py b/fungus/main_window.py index 179e94e..279a14e 100644 --- a/fungus/main_window.py +++ b/fungus/main_window.py @@ -10,16 +10,16 @@ import threading import gi gi.require_version('Gtk', '3.0') +gi.require_version("GdkPixbuf", "3.0") from gi.repository import Gtk, Gdk, GdkPixbuf, GLib # type: ignore from fungus.config_manager import ConfigManager from fungus.logger import get_logger +from fungus.shortcuts import create_shortcut, remove_shortcut, set_image_shortcut_icon from fungus.constants import ( - app_dir, backup_dir, fungus_backup, games_json, - desktop_dir, fungus_launcher_dir, fungus_png, fungus_run, @@ -1030,87 +1030,13 @@ class Main(Gtk.ApplicationWindow): # ── Shortcut & Icon Helpers ────────────────────────────────────────── def set_image_shortcut_icon(self, title, icons_path, icon_temp): - """Copy the icon for *title* into *icon_temp* for use in the add/edit dialog.""" - 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 + """Delegate to the shared shortcut icon helper.""" + return set_image_shortcut_icon(title, icons_path, icon_temp) def add_shortcut(self, game, shortcut_state, shortcut, icon_temp, icon_final): - """Create a .desktop shortcut for *game* (desktop or appmenu) if *shortcut_state* is True.""" - applications_shortcut_path = f"{app_dir}/{game.gameid}.desktop" - desktop_shortcut_path = f"{desktop_dir}/{game.gameid}.desktop" - - if shortcut == "desktop" and not shortcut_state: - self.remove_shortcut(game, shortcut) - if os.path.isfile(os.path.expanduser(icon_temp)): - os.rename(os.path.expanduser(icon_temp), icon_final) - return - if shortcut == "appmenu" and not shortcut_state: - self.remove_shortcut(game, shortcut) - if os.path.isfile(os.path.expanduser(icon_temp)): - os.rename(os.path.expanduser(icon_temp), icon_final) - return - - 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 appmenu_file: - appmenu_file.write(desktop_file_content) - os.chmod(applications_shortcut_path, 0o755) - - if shortcut == "desktop": - with open(desktop_shortcut_path, 'w') as desktop_file: - desktop_file.write(desktop_file_content) - os.chmod(desktop_shortcut_path, 0o755) + """Delegate to the shared shortcut creation helper.""" + create_shortcut(game, shortcut_state, shortcut, icon_temp, icon_final) def remove_shortcut(self, game, shortcut): - """Delete the .desktop shortcut for *game* (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": - if os.path.exists(applications_shortcut_path): - os.remove(applications_shortcut_path) - if shortcut == "desktop": - if os.path.exists(desktop_shortcut_path): - os.remove(desktop_shortcut_path) - if shortcut == "both": - if os.path.exists(applications_shortcut_path): - os.remove(applications_shortcut_path) - if os.path.exists(desktop_shortcut_path): - os.remove(desktop_shortcut_path) + """Delegate to the shared shortcut removal helper.""" + remove_shortcut(game, shortcut) diff --git a/fungus/meson.build b/fungus/meson.build index 913ef7a..9728149 100644 --- a/fungus/meson.build +++ b/fungus/meson.build @@ -24,6 +24,7 @@ py.install_sources( 'run_manager.py', 'proton_manager.py', 'settings_dialog.py', + 'shortcuts.py', 'umu_manager.py', 'utils.py', 'utils_pure.py', diff --git a/fungus/run_manager.py b/fungus/run_manager.py index 4c490c0..0f59359 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -32,7 +32,7 @@ from fungus.constants import ( from fungus.game_model import Game, load_games_json, save_games_json from fungus.path_manager import PathManager from fungus.utils import has_proton_installed, is_executable_in_whitelist -from fungus.dialogs import SandboxWarningDialog, SteamRuntimeWarningDialog +from fungus.dialogs import SandboxWarningDialog from fungus.umu_manager import proton_to_steamrt_variant compatibility_dir = os.path.expanduser("~/.local/share/Steam/compatibilitytools.d") @@ -421,9 +421,17 @@ class FungusRun: def show_error_dialog_steam_runtime(self): """Show error when UMU Steam Runtime is not available.""" - SteamRuntimeWarningDialog() - Gtk.main_quit() - sys.exit() + from fungus.dialogs import create_error_dialog + + create_error_dialog( + title="Fungus Launcher", + primary="The UMU Steam Runtime directory was not found.", + secondary=( + "Games using UMU-Launcher will not be able to run. " + "Please open Settings → UMU-Launcher and update the runtime." + ), + quit_app=True, + ) def _show_spawn_error(self, error_msg: str) -> None: """Show an error dialog when the process could not be spawned.""" @@ -431,68 +439,15 @@ class FungusRun: self.splash_window.destroy() self.splash_window = None - dialog = Gtk.Dialog(title="Fungus Launcher") - dialog.set_resizable(False) - dialog.set_icon_from_file(fungus_png) - - content_area = dialog.get_content_area() - content_area.set_border_width(0) - content_area.set_halign(Gtk.Align.CENTER) - content_area.set_valign(Gtk.Align.CENTER) - content_area.set_vexpand(True) - content_area.set_hexpand(True) - - box_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) - box_top.set_margin_start(20) - box_top.set_margin_end(20) - box_top.set_margin_top(20) - box_top.set_margin_bottom(20) - - label = Gtk.Label( - label="The game runner could not be started.", - ) - label.set_halign(Gtk.Align.CENTER) - label.set_line_wrap(True) - label.set_max_width_chars(60) + from fungus.dialogs import create_error_dialog - label2 = Gtk.Label( - label="Check the terminal output for details.", + create_error_dialog( + title="Fungus Launcher", + primary="The game runner could not be started.", + secondary="Check the terminal output for details.", + error_text=error_msg, + quit_app=True, ) - label2.set_halign(Gtk.Align.CENTER) - - box_top.pack_start(label, True, True, 0) - box_top.pack_start(label2, True, True, 0) - - if error_msg: - scrolled = Gtk.ScrolledWindow() - scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) - scrolled.set_min_content_height(120) - text_view = Gtk.TextView() - text_view.set_editable(False) - text_view.set_cursor_visible(False) - buffer = text_view.get_buffer() - buffer.set_text(error_msg) - scrolled.add(text_view) - box_top.pack_start(scrolled, True, True, 0) - - button_ok = Gtk.Button(label="Ok") - button_ok.set_size_request(150, -1) - button_ok.connect("clicked", lambda w: dialog.response(Gtk.ResponseType.OK)) - - box_bottom = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) - box_bottom.set_margin_start(10) - box_bottom.set_margin_end(10) - box_bottom.set_margin_bottom(10) - box_bottom.pack_start(button_ok, True, True, 0) - - content_area.add(box_top) - content_area.add(box_bottom) - - dialog.show_all() - dialog.run() - dialog.destroy() - Gtk.main_quit() - sys.exit() def _show_process_error(self, exit_code: int) -> bool: """Show process error in the splash window with accumulated output.""" @@ -519,106 +474,32 @@ class FungusRun: def show_error_dialog_no_proton(self): """Show error when no proton versions are installed at all.""" - dialog = Gtk.Dialog(title="Fungus Launcher") - dialog.set_resizable(False) - dialog.set_icon_from_file(fungus_png) - - content_area = dialog.get_content_area() - content_area.set_border_width(0) - content_area.set_halign(Gtk.Align.CENTER) - content_area.set_valign(Gtk.Align.CENTER) - content_area.set_vexpand(True) - content_area.set_hexpand(True) - - box_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) - box_top.set_margin_start(20) - box_top.set_margin_end(20) - box_top.set_margin_top(20) - box_top.set_margin_bottom(20) - - label = Gtk.Label(label="No Proton version is installed.") - label.set_halign(Gtk.Align.CENTER) - - label2 = Gtk.Label( - label="Please install one via Settings → Proton Manager.", - ) - label2.set_halign(Gtk.Align.CENTER) + from fungus.dialogs import create_error_dialog - box_top.pack_start(label, True, True, 0) - box_top.pack_start(label2, True, True, 0) - - button_ok = Gtk.Button(label="Ok") - button_ok.set_size_request(150, -1) - button_ok.connect("clicked", lambda w: dialog.response(Gtk.ResponseType.OK)) - - box_bottom = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) - box_bottom.set_margin_start(10) - box_bottom.set_margin_end(10) - box_bottom.set_margin_bottom(10) - box_bottom.pack_start(button_ok, True, True, 0) - - content_area.add(box_top) - content_area.add(box_bottom) - - dialog.show_all() - dialog.run() - dialog.destroy() - Gtk.main_quit() - sys.exit() + create_error_dialog( + title="Fungus Launcher", + primary="No Proton version is installed.", + secondary="Please install one via Settings → Proton Manager.", + quit_app=True, + ) def show_error_dialog(self, protonpath=None, network_error=False): """Show a generic error dialog for missing Proton or network errors.""" - dialog = Gtk.Dialog(title="Fungus Launcher") - dialog.set_resizable(False) - dialog.set_icon_from_file(fungus_png) - - content_area = dialog.get_content_area() - content_area.set_border_width(0) - content_area.set_halign(Gtk.Align.CENTER) - content_area.set_valign(Gtk.Align.CENTER) - content_area.set_vexpand(True) - content_area.set_hexpand(True) - - box_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) - box_top.set_margin_start(20) - box_top.set_margin_end(20) - box_top.set_margin_top(20) - box_top.set_margin_bottom(20) + from fungus.dialogs import create_error_dialog if network_error: - label = Gtk.Label(label="Internet connection error.") - label.set_halign(Gtk.Align.CENTER) - box_top.pack_start(label, True, True, 0) + primary = "Internet connection error." + secondary = None else: - label = Gtk.Label(label="%s was not found." % protonpath) - label.set_halign(Gtk.Align.CENTER) - - label2 = Gtk.Label( - label="Please install it or use another Proton version.", - ) - label2.set_halign(Gtk.Align.CENTER) - - box_top.pack_start(label, True, True, 0) - box_top.pack_start(label2, True, True, 0) - - button_ok = Gtk.Button(label="Ok") - button_ok.set_size_request(150, -1) - button_ok.connect("clicked", lambda w: dialog.response(Gtk.ResponseType.OK)) - - box_bottom = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) - box_bottom.set_margin_start(10) - box_bottom.set_margin_end(10) - box_bottom.set_margin_bottom(10) - box_bottom.pack_start(button_ok, True, True, 0) - - content_area.add(box_top) - content_area.add(box_bottom) - - dialog.show_all() - dialog.run() - dialog.destroy() - Gtk.main_quit() - sys.exit() + primary = f"{protonpath} was not found." + secondary = "Please install it or use another Proton version." + + create_error_dialog( + title="Fungus Launcher", + primary=primary, + secondary=secondary, + quit_app=True, + ) def load_env_from_file(self, filename=envar_dir): """Read key=value pairs from *filename* and merge them into os.environ. diff --git a/fungus/shortcuts.py b/fungus/shortcuts.py new file mode 100644 index 0000000..4462d96 --- /dev/null +++ b/fungus/shortcuts.py @@ -0,0 +1,254 @@ +"""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 + +import gi + +#gi.require_version("GdkPixbuf", "3.0") +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 |
