diff options
| author | fox <fox@fakecake.org> | 2026-07-03 17:30:46 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-03 17:30:46 +0300 |
| commit | f33457d29475ff8d23b720c4ee35760f86fe221f (patch) | |
| tree | 7c91755da2b10189f17c7a5347732ef5ee959f07 | |
| parent | ce298d6bdb315d2b5db3e03b0a40a2ec1331ed4b (diff) | |
| parent | 98219ca0720db057e434fd6e92852b6905ea34da (diff) | |
| download | fungus-launcher-f33457d29475ff8d23b720c4ee35760f86fe221f.tar.gz fungus-launcher-f33457d29475ff8d23b720c4ee35760f86fe221f.tar.xz | |
Merge branch 'dev' into 'master'
Dev See merge request git/fungus-launcher!33
| -rw-r--r-- | fungus/add_game_dialog.py | 87 | ||||
| -rw-r--r-- | fungus/dialogs.py | 119 | ||||
| -rw-r--r-- | fungus/main_window.py | 292 | ||||
| -rw-r--r-- | fungus/meson.build | 3 | ||||
| -rw-r--r-- | fungus/run_manager.py | 297 | ||||
| -rw-r--r-- | fungus/settings_dialog.py | 128 | ||||
| -rw-r--r-- | fungus/shortcuts.py | 251 | ||||
| -rw-r--r-- | fungus/splash_window.py | 169 |
8 files changed, 760 insertions, 586 deletions
diff --git a/fungus/add_game_dialog.py b/fungus/add_game_dialog.py index c0f816d..a1161f3 100644 --- a/fungus/add_game_dialog.py +++ b/fungus/add_game_dialog.py @@ -22,14 +22,16 @@ from fungus.logger import get_logger log = get_logger(__name__) from fungus.constants import ( - app_dir, - desktop_dir, fungus_png, fungus_run, icons_dir, prefixes_dir, ) +from fungus.shortcuts import ( + set_default_icon, + find_largest_resolution, +) from fungus.utils import ( EntryTooltipMixin, format_title, @@ -116,14 +118,6 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.grid_runner.set_margin_end(10) self.grid_runner.set_margin_top(10) - self.grid_shortcut = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL) - self.grid_shortcut.set_row_spacing(10) - self.grid_shortcut.set_column_spacing(10) - self.grid_shortcut.set_margin_start(10) - self.grid_shortcut.set_margin_end(10) - self.grid_shortcut.set_margin_top(10) - self.grid_shortcut.set_margin_bottom(10) - self.grid_shortcut_icon = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL) self.grid_shortcut_icon.set_row_spacing(10) self.grid_shortcut_icon.set_column_spacing(10) @@ -266,19 +260,6 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.button_run.connect("clicked", self.on_button_run_clicked) self.button_run.set_tooltip_text("Run a file inside the prefix") - # Button for creating shortcut - self.label_shortcut = Gtk.Label(label="Shortcut") - self.label_shortcut.set_margin_start(10) - self.label_shortcut.set_margin_end(10) - self.label_shortcut.set_margin_top(10) - self.label_shortcut.set_halign(Gtk.Align.START) - self.checkbox_shortcut_desktop = Gtk.CheckButton(label="Desktop") - self.checkbox_shortcut_desktop.set_tooltip_text( - "Add or remove a shortcut from the Desktop.") - self.checkbox_shortcut_appmenu = Gtk.CheckButton(label="App Menu") - self.checkbox_shortcut_appmenu.set_tooltip_text( - "Add or remove a shortcut from the Application Menu.") - # Button for selection shortcut icon self.button_shortcut_icon = Gtk.Button() self.button_shortcut_icon.set_size_request(120, -1) @@ -358,23 +339,15 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.grid_runner.attach(self.combobox_runner, 0, 1, 1, 1) self.combobox_runner.set_hexpand(True) - self.label_shortcut.set_hexpand(True) - self.grid_shortcut.add(self.checkbox_shortcut_desktop) - self.grid_shortcut.add(self.checkbox_shortcut_appmenu) self.grid_shortcut_icon.add(self.button_shortcut_icon) self.grid_shortcut_icon.set_valign(Gtk.Align.CENTER) - self.box_shortcut = Gtk.Box() - self.box_shortcut.pack_start(self.grid_shortcut, False, False, 0) - self.box_shortcut.pack_end(self.grid_shortcut_icon, False, False, 0) - page1.add(self.grid_launcher) page1.add(self.grid_title) page1.add(self.grid_path) page1.add(self.grid_prefix) page1.add(self.grid_runner) - page1.add(self.label_shortcut) - page1.add(self.box_shortcut) + page1.add(self.grid_shortcut_icon) self.grid_protonfix.attach(self.label_protonfix, 0, 0, 1, 1) self.grid_protonfix.attach(self.entry_protonfix, 0, 1, 3, 1) @@ -530,16 +503,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 +631,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.""" @@ -719,21 +663,6 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): else: 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 - title = self.entry_title.get_text().strip() - if not title: - return # If there's no title, there's no shortcut to check - - title_formatted = format_title(title) - desktop_file_path = f"{desktop_dir}/{title_formatted}.desktop" - applications_shortcut_path = f"{app_dir}/{title_formatted}.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)) - def on_button_winecfg_clicked(self, widget): """Launch winecfg inside the Wine prefix via fungus_run.""" self.set_sensitive(False) diff --git a/fungus/dialogs.py b/fungus/dialogs.py index 29a59df..72bf5fe 100644 --- a/fungus/dialogs.py +++ b/fungus/dialogs.py @@ -123,6 +123,125 @@ class GameDirectoriesNotConfiguredDialog(Gtk.MessageDialog): self.destroy() +class UmuLauncherNotInstalledDialog(Gtk.MessageDialog): + """Warn the user that UMU-Launcher is not installed and offer to open Settings.""" + + def __init__(self, parent: Gtk.Window): + secondary = ( + "UMU-Launcher is required to launch games but is not currently installed. " + "Please install it via Settings → UMU-Launcher before launching." + ) + super().__init__( + parent=parent, + flags=Gtk.DialogFlags.MODAL, + message_type=Gtk.MessageType.WARNING, + buttons=Gtk.ButtonsType.NONE, + text="UMU-Launcher Not Installed", + ) + self.format_secondary_text(secondary) + self.set_resizable(False) + self.set_icon_from_file(fungus_png) + + self.add_button("Open Settings", Gtk.ResponseType.YES) + self.add_button("Cancel", Gtk.ResponseType.CANCEL) + self.set_default_response(Gtk.ResponseType.YES) + + self.result = self.run() + 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..83ae2b1 100644 --- a/fungus/main_window.py +++ b/fungus/main_window.py @@ -6,7 +6,6 @@ import os import shutil import subprocess import sys -import threading import gi gi.require_version('Gtk', '3.0') @@ -14,21 +13,23 @@ 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, icons_dir, umu_run, fungus_version, + desktop_dir, + app_dir, ) from fungus.dialogs import ( GameDirectoriesNotConfiguredDialog, + UmuLauncherNotInstalledDialog, show_warning_dialog, ) from fungus.game_model import ( @@ -40,10 +41,7 @@ from fungus.game_model import ( ) from fungus.settings_dialog import SettingsDialog from fungus.utils import format_title, is_safe_prefix_path -from fungus.umu_manager import ( - check_and_install_if_needed, - is_umu_installed, -) + log = get_logger(__name__) @@ -117,6 +115,8 @@ class Main(Gtk.ApplicationWindow): self.menu_item_delete.connect("activate", self.on_context_menu_delete) self.context_menu.append(self.menu_item_delete) + self.context_menu.append(Gtk.SeparatorMenuItem()) + self.menu_item_hide = Gtk.MenuItem(label="Hide") self.menu_item_hide.connect("activate", self.on_context_menu_hide) self.context_menu.append(self.menu_item_hide) @@ -125,6 +125,8 @@ class Main(Gtk.ApplicationWindow): self.menu_item_favorite.connect("activate", self.on_context_menu_favorite) self.context_menu.append(self.menu_item_favorite) + self.context_menu.append(Gtk.SeparatorMenuItem()) + self.menu_item_game = Gtk.MenuItem(label="Open game location") self.menu_item_game.connect("activate", self.on_context_menu_game) self.context_menu.append(self.menu_item_game) @@ -133,6 +135,16 @@ class Main(Gtk.ApplicationWindow): self.menu_item_prefix.connect("activate", self.on_context_menu_prefix) self.context_menu.append(self.menu_item_prefix) + self.context_menu.append(Gtk.SeparatorMenuItem()) + + self.menu_item_desktop = Gtk.MenuItem(label="Add to Desktop") + self.menu_item_desktop.connect("activate", self.on_context_menu_desktop) + self.context_menu.append(self.menu_item_desktop) + + self.menu_item_appmenu = Gtk.MenuItem(label="Add to App Menu") + self.menu_item_appmenu.connect("activate", self.on_context_menu_appmenu) + self.context_menu.append(self.menu_item_appmenu) + self.context_menu.show_all() self.small_interface() @@ -352,6 +364,19 @@ class Main(Gtk.ApplicationWindow): self.menu_item_prefix.set_sensitive(False) self.current_prefix = None + # Shortcut menu items — toggle label based on existence + desktop_path = f"{desktop_dir}/{game.gameid}.desktop" + appmenu_path = f"{app_dir}/{game.gameid}.desktop" + if os.path.exists(desktop_path): + self.menu_item_desktop.get_child().set_text("Remove from Desktop") + else: + self.menu_item_desktop.get_child().set_text("Add to Desktop") + + if os.path.exists(appmenu_path): + self.menu_item_appmenu.get_child().set_text("Remove from App Menu") + else: + self.menu_item_appmenu.get_child().set_text("Add to App Menu") + self.context_menu.popup_at_pointer(event) # ── Game List Rendering ────────────────────────────────────────────── @@ -577,6 +602,44 @@ class Main(Gtk.ApplicationWindow): return subprocess.run(["xdg-open", self.current_prefix], check=True) + def on_context_menu_desktop(self, menu_item): + """Toggle the desktop shortcut for the selected game.""" + selected = self.flowbox.get_selected_children() + if not selected: + return + + game = selected[0].game + if not game: + return + + desktop_path = f"{desktop_dir}/{game.gameid}.desktop" + if os.path.exists(desktop_path): + remove_shortcut(game, "desktop") + else: + icon_final = f'{icons_dir}/{game.gameid}.ico' + create_shortcut(game, True, "desktop", "", icon_final) + + self.update_list() + + def on_context_menu_appmenu(self, menu_item): + """Toggle the application menu shortcut for the selected game.""" + selected = self.flowbox.get_selected_children() + if not selected: + return + + game = selected[0].game + if not game: + return + + appmenu_path = f"{app_dir}/{game.gameid}.desktop" + if os.path.exists(appmenu_path): + remove_shortcut(game, "appmenu") + else: + icon_final = f'{icons_dir}/{game.gameid}.ico' + create_shortcut(game, True, "appmenu", "", icon_final) + + self.update_list() + # ── Button Handlers (Add / Edit / Delete / Play / Kill / Settings) ─── def on_button_settings_clicked(self, widget): @@ -680,105 +743,6 @@ class Main(Gtk.ApplicationWindow): self.select_first_child() - # ── UMU-Launcher Install ────────────────────────────────────────────── - - def _show_umu_missing_dialog(self, game): - """Show a dialog asking the user to install UMU-Launcher.""" - dialog = Gtk.MessageDialog( - parent=self, - flags=Gtk.DialogFlags.MODAL, - message_type=Gtk.MessageType.WARNING, - buttons=Gtk.ButtonsType.NONE, - text="UMU-Launcher is not installed", - ) - dialog.format_secondary_text( - "UMU-Launcher is required to launch games. " - "Would you like to download it now?" - ) - dialog.add_button("Cancel", Gtk.ResponseType.CANCEL) - dialog.add_button("Download", Gtk.ResponseType.YES) - dialog.set_default_response(Gtk.ResponseType.YES) - - response = dialog.run() - dialog.destroy() - - if response == Gtk.ResponseType.YES: - self._download_and_install_umu(game) - - def _download_and_install_umu(self, game): - """Download UMU-Launcher in a background thread with a progress dialog.""" - progress_window = Gtk.Window() - progress_window.set_transient_for(self) - progress_window.set_decorated(False) - progress_window.set_modal(True) - progress_window.set_resizable(False) - progress_window.set_default_size(320, -1) - - box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12) - box.set_margin_start(20) - box.set_margin_end(20) - box.set_margin_top(20) - box.set_margin_bottom(20) - - label = Gtk.Label(label="Downloading UMU-Launcher...") - label.set_halign(Gtk.Align.CENTER) - - self._umu_progress = Gtk.ProgressBar() - self._umu_progress.set_fraction(0.0) - self._umu_progress.set_text("0%") - self._umu_progress.set_show_text(True) - - cancel_button = Gtk.Button(label="Cancel") - cancel_button.set_halign(Gtk.Align.CENTER) - - box.pack_start(label, False, False, 0) - box.pack_start(self._umu_progress, False, False, 0) - box.pack_start(cancel_button, False, False, 0) - progress_window.add(box) - progress_window.show_all() - - cancelled = [False] - - def on_cancel(_btn): - cancelled[0] = True - GLib.idle_add(progress_window.destroy) - - cancel_button.connect("clicked", on_cancel) - - def on_download_progress(percent): - if cancelled[0]: - return - GLib.idle_add(self._umu_progress.set_fraction, percent / 100.0) - GLib.idle_add(self._umu_progress.set_text, f"{percent}%") - - def download_thread(): - success, status = check_and_install_if_needed(progress_callback=on_download_progress) - GLib.idle_add(progress_window.destroy) - GLib.idle_add(self._on_umu_download_done, success, status, game) - - thread = threading.Thread(target=download_thread, daemon=True) - thread.start() - - def _on_umu_download_done(self, success, status, game): - """Callback when UMU download completes.""" - if success: - # Continue with game launch - self._launch_game(game) - else: - error_dialog = Gtk.MessageDialog( - parent=self, - flags=Gtk.DialogFlags.MODAL, - message_type=Gtk.MessageType.ERROR, - buttons=Gtk.ButtonsType.OK, - text="Download failed", - ) - error_dialog.format_secondary_text( - "Could not download UMU-Launcher. " - "Please check your internet connection and try again." - ) - error_dialog.run() - error_dialog.destroy() - def _launch_game(self, game, igpu: bool = False): """Launch the given game via fungus_run. @@ -825,8 +789,16 @@ class Main(Gtk.ApplicationWindow): return # Check for UMU-Launcher before launching - if not is_umu_installed(): - self._show_umu_missing_dialog(game) + if not os.path.isfile(umu_run): + dialog = UmuLauncherNotInstalledDialog(self) + if dialog.result == Gtk.ResponseType.YES: + settings_dialog = SettingsDialog(self) + settings_dialog.connect( + "response", + self.on_settings_dialog_response, + settings_dialog, + ) + settings_dialog.show() return self._launch_game(game) @@ -889,19 +861,17 @@ class Main(Gtk.ApplicationWindow): playtime, hidden, favorite, ) - desktop_shortcut_state = add_game_dialog.checkbox_shortcut_desktop.get_active() - appmenu_shortcut_state = add_game_dialog.checkbox_shortcut_appmenu.get_active() - icon_temp = os.path.expanduser(add_game_dialog.icon_temp) icon_final = f'{add_game_dialog.icons_path}/{title_formatted}.ico' + # Copy icon to final location (shortcut creation is now a context-menu action) + if os.path.isfile(icon_temp): + shutil.copyfile(icon_temp, icon_final) + self.backup_games() save_games_json(games_json, [*self.games, game]) self.games.append(game) - self.add_shortcut(game, desktop_shortcut_state, "desktop", icon_temp, icon_final) - self.add_shortcut(game, appmenu_shortcut_state, "appmenu", icon_temp, icon_final) - self.add_item_list(game) self.update_list() self.select_game_by_title(title) @@ -936,11 +906,9 @@ class Main(Gtk.ApplicationWindow): icon_temp = os.path.expanduser(edit_game_dialog.icon_temp) icon_final = f'{edit_game_dialog.icons_path}/{title_formatted}.ico' - desktop_shortcut_state = edit_game_dialog.checkbox_shortcut_desktop.get_active() - appmenu_shortcut_state = edit_game_dialog.checkbox_shortcut_appmenu.get_active() - - self.add_shortcut(game, desktop_shortcut_state, "desktop", icon_temp, icon_final) - self.add_shortcut(game, appmenu_shortcut_state, "appmenu", icon_temp, icon_final) + # Copy icon to final location (shortcut creation is now a context-menu action) + if os.path.isfile(icon_temp): + shutil.copyfile(icon_temp, icon_final) save_games_json(games_json, self.games) self.update_list() @@ -1030,87 +998,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 bcbbe2c..f6aece2 100644 --- a/fungus/meson.build +++ b/fungus/meson.build @@ -18,11 +18,14 @@ py.install_sources( 'dark_theme.py', 'dialogs.py', 'game_model.py', + 'logger.py', 'main_window.py', 'path_manager.py', 'run_manager.py', 'proton_manager.py', 'settings_dialog.py', + 'shortcuts.py', + 'splash_window.py', 'umu_manager.py', 'utils.py', 'utils_pure.py', diff --git a/fungus/run_manager.py b/fungus/run_manager.py index 4c490c0..a485495 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -14,6 +14,7 @@ from threading import Thread, Event from typing import ClassVar from fungus.logger import get_logger +from fungus.splash_window import SplashWindow log = get_logger(__name__) @@ -24,7 +25,6 @@ from gi.repository import Gtk, GLib # type: ignore from fungus.config_manager import ConfigManager from fungus.constants import ( envar_dir, - fungus_png, games_json, share_dir, umu_run, @@ -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") @@ -118,8 +118,8 @@ class FungusRun: self.game = game self.igpu = igpu self.process = None - self.splash_window = None - self.error_output = [] + self.splash_window: SplashWindow | None = None + self.error_output: list[str] = [] self._cleanup_event = Event() # signals cleanup thread to stop self.load_config() @@ -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,194 +439,54 @@ 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.""" if not self.splash_window: self.show_splash_window() - # Update window title with exit code if self.splash_window: - current_title = self.splash_window.get_title() or "" - self.splash_window.set_title(f"{current_title} — exited with code {exit_code}") - - # Show accumulated stderr in the text view - if self.error_output: - error_text = "\n".join(self.error_output) - self._append_output(f"\n--- stderr ({len(self.error_output)} lines) ---") - self._append_output(error_text) - - # Reveal output view and close button - self.scrolled_output.set_visible(True) - self.close_button.set_visible(True) - self.close_button.set_sensitive(True) + self.splash_window.show_error(exit_code, self.error_output) return False 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) - - 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)) + from fungus.dialogs import create_error_dialog - 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. @@ -733,72 +601,27 @@ class FungusRun: except psutil.NoSuchProcess: pass - def show_splash_window(self): + def show_splash_window(self) -> None: """Create and display the splash window with window title and output view.""" title = self.game.title or self.game.gameid or "" - self.splash_window = Gtk.Window(title=title) - self.splash_window.set_decorated(True) - self.splash_window.set_resizable(True) - self.splash_window.set_default_size(840, 400) - self.splash_window.set_icon_from_file(fungus_png) - - frame = Gtk.Frame() - frame.set_label_align(0.5, 0.5) - frame.set_shadow_type(Gtk.ShadowType.ETCHED_IN) - - grid = Gtk.Grid() - grid.set_hexpand(True) - grid.set_vexpand(True) - grid.set_row_spacing(10) - frame.add(grid) - - # Live output text view (hidden until output arrives) - self.output_buffer = Gtk.TextBuffer() - self.text_view = Gtk.TextView(buffer=self.output_buffer) - self.text_view.set_editable(False) - self.text_view.set_cursor_visible(False) - self.text_view.set_monospace(True) - self.text_view.set_margin_top(5) - self.text_view.set_margin_bottom(5) - self.text_view.set_margin_start(10) - self.text_view.set_margin_end(10) - self.text_view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) - self.text_view.get_style_context().add_class("output-view") - - self.scrolled_output = Gtk.ScrolledWindow() - self.scrolled_output.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) - self.scrolled_output.set_min_content_height(120) - self.scrolled_output.set_hexpand(True) - self.scrolled_output.set_vexpand(True) - self.scrolled_output.set_visible(False) - self.scrolled_output.add(self.text_view) - grid.attach(self.scrolled_output, 0, 1, 1, 1) - - # Close button (hidden until error) - self.close_button = Gtk.Button(label="Close") - self.close_button.set_sensitive(False) - self.close_button.set_size_request(150, -1) - self.close_button.connect("clicked", self._on_splash_close) - grid.attach(self.close_button, 0, 2, 1, 1) - - self.splash_window.add(frame) - self.splash_window.show_all() + + def on_close() -> None: + Gtk.main_quit() + sys.exit(0) + + self.splash_window = SplashWindow(title, on_close) + self.splash_window.show() def _on_splash_close(self, _widget): """Close the splash window and quit the application.""" if self.splash_window: - self.splash_window.destroy() + self.splash_window.close() self.splash_window = None - Gtk.main_quit() - sys.exit(0) def _append_output(self, line: str) -> None: - """Append a line to the output text buffer.""" - buf = self.output_buffer - end = buf.get_end_iter() - buf.insert(end, line + "\n") - # Scroll to bottom - self.text_view.scroll_to_iter(end, 0.0, True, 0.0, 1.0) + """Delegate to the splash window.""" + if self.splash_window: + self.splash_window.append_output(line) def on_output(self, source, condition): """GLib I/O watch callback — reads lines from stdout/stderr. @@ -837,10 +660,9 @@ class FungusRun: return True def _show_output_in_splash(self, line: str) -> None: - """Append a line to the splash output text view.""" - if self.splash_window and self.scrolled_output: - self.scrolled_output.set_visible(True) - self._append_output(line) + """Delegate to the splash window.""" + if self.splash_window: + self.splash_window.append_output(line) def check_game_output(self, clean_line): """Detect when the game has started and close the splash window. @@ -858,10 +680,9 @@ class FungusRun: GLib.timeout_add_seconds(0, self.close_splash_window) def close_splash_window(self): - """Destroy the splash window and reset the reference.""" + """Hide the splash window.""" if self.splash_window: - self.splash_window.destroy() - self.splash_window = None + self.splash_window.hide() def on_sigusr1(self, signum, frame): """Handle SIGUSR1: kill children, then terminate ourselves via SIGTERM.""" diff --git a/fungus/settings_dialog.py b/fungus/settings_dialog.py index f04bb08..0f54654 100644 --- a/fungus/settings_dialog.py +++ b/fungus/settings_dialog.py @@ -18,7 +18,7 @@ from fungus.constants import ( ) from fungus.config_manager import ConfigManager from fungus.dialogs import show_warning_dialog -from fungus.utils import EntryTooltipMixin +from fungus.utils import EntryTooltipMixin, pick_folder from fungus.umu_manager import ( check_and_install_if_needed, get_installed_umu_version, @@ -144,32 +144,32 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.progress_umu.set_hexpand(True) # ── Steam Runtime section ───────────────────────────────────────── - self.label_umu_runtime = Gtk.Label(label="Steam Runtime") - self.label_umu_runtime.set_halign(Gtk.Align.START) - - self.label_umu_runtime_status = Gtk.Label(label="Not checked") - self.label_umu_runtime_status.set_halign(Gtk.Align.START) - self.label_umu_runtime_status.set_margin_start(10) - self.label_umu_runtime_status.set_max_width_chars(20) - self.label_umu_runtime_status.set_ellipsize(Pango.EllipsizeMode.END) - - self.label_umu_runtime_variant = Gtk.Label(label="Expected: steamrt3") - self.label_umu_runtime_variant.set_halign(Gtk.Align.START) - self.label_umu_runtime_variant.set_margin_start(10) - self.label_umu_runtime_variant.set_max_width_chars(20) - self.label_umu_runtime_variant.set_ellipsize(Pango.EllipsizeMode.END) - self.label_umu_runtime_variant.set_sensitive(False) # greyed out until runner selected - - self.button_umu_runtime = Gtk.Button(label="Update Runtime") - self.button_umu_runtime.set_image( + self.label_steam_runtime = Gtk.Label(label="Steam Runtime") + self.label_steam_runtime.set_halign(Gtk.Align.START) + + self.label_steam_runtime_status = Gtk.Label(label="Not checked") + self.label_steam_runtime_status.set_halign(Gtk.Align.START) + self.label_steam_runtime_status.set_margin_start(10) + self.label_steam_runtime_status.set_max_width_chars(20) + self.label_steam_runtime_status.set_ellipsize(Pango.EllipsizeMode.END) + + self.label_steam_runtime_variant = Gtk.Label(label="Expected: steamrt3") + self.label_steam_runtime_variant.set_halign(Gtk.Align.START) + self.label_steam_runtime_variant.set_margin_start(10) + self.label_steam_runtime_variant.set_max_width_chars(20) + self.label_steam_runtime_variant.set_ellipsize(Pango.EllipsizeMode.END) + self.label_steam_runtime_variant.set_sensitive(False) # greyed out until runner selected + + self.button_steam_runtime = Gtk.Button(label="Update Runtime") + self.button_steam_runtime.set_image( Gtk.Image.new_from_icon_name("system-run-symbolic", Gtk.IconSize.BUTTON)) - self.button_umu_runtime.set_image_position(Gtk.PositionType.LEFT) - self.button_umu_runtime.connect("clicked", self.on_button_umu_runtime_clicked) - self.button_umu_runtime.set_size_request(140, -1) + self.button_steam_runtime.set_image_position(Gtk.PositionType.LEFT) + self.button_steam_runtime.connect("clicked", self.on_button_steam_runtime_clicked) + self.button_steam_runtime.set_size_request(140, -1) - self.progress_umu_runtime = Gtk.ProgressBar() - self.progress_umu_runtime.set_visible(False) - self.progress_umu_runtime.set_hexpand(True) + self.progress_steam_runtime = Gtk.ProgressBar() + self.progress_steam_runtime.set_visible(False) + self.progress_steam_runtime.set_hexpand(True) self.label_miscellaneous = Gtk.Label(label="Miscellaneous") self.label_miscellaneous.set_halign(Gtk.Align.START) @@ -312,18 +312,18 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): grid_umu.attach(self.progress_umu, 0, 4, 2, 1) # Steam Runtime section - self.label_umu_runtime_last = Gtk.Label(label="Last checked: -") - self.label_umu_runtime_last.set_halign(Gtk.Align.START) - self.label_umu_runtime_last.set_margin_start(10) - self.label_umu_runtime_last.set_max_width_chars(30) - self.label_umu_runtime_last.set_ellipsize(Pango.EllipsizeMode.END) - - grid_umu.attach(self.label_umu_runtime, 0, 5, 1, 1) - grid_umu.attach(self.label_umu_runtime_variant, 0, 6, 1, 1) - grid_umu.attach(self.label_umu_runtime_status, 0, 7, 1, 1) - grid_umu.attach(self.label_umu_runtime_last, 0, 8, 1, 1) - grid_umu.attach(self.button_umu_runtime, 0, 9, 1, 1) - grid_umu.attach(self.progress_umu_runtime, 0, 10, 2, 1) + self.label_steam_runtime_last = Gtk.Label(label="Last checked: -") + self.label_steam_runtime_last.set_halign(Gtk.Align.START) + self.label_steam_runtime_last.set_margin_start(10) + self.label_steam_runtime_last.set_max_width_chars(30) + self.label_steam_runtime_last.set_ellipsize(Pango.EllipsizeMode.END) + + grid_umu.attach(self.label_steam_runtime, 0, 5, 1, 1) + grid_umu.attach(self.label_steam_runtime_variant, 0, 6, 1, 1) + grid_umu.attach(self.label_steam_runtime_status, 0, 7, 1, 1) + grid_umu.attach(self.label_steam_runtime_last, 0, 8, 1, 1) + grid_umu.attach(self.button_steam_runtime, 0, 9, 1, 1) + grid_umu.attach(self.progress_steam_runtime, 0, 10, 2, 1) grid_miscellaneous.attach(self.checkbox_discrete_gpu, 0, 2, 1, 1) grid_miscellaneous.attach(self.checkbox_show_hidden, 0, 3, 1, 1) @@ -392,6 +392,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.show_all() self.progress_umu.set_visible(False) + self.progress_steam_runtime.set_visible(False) self.track_modifications(self.box) @@ -483,22 +484,9 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): def on_button_add_gamedir_clicked(self, widget): """Open a folder chooser and append the selected directory to the game directories list.""" - filechooser = Gtk.FileChooserNative( - title="Select a game directory", - transient_for=self, - action=Gtk.FileChooserAction.SELECT_FOLDER, - accept_label="Open", - cancel_label="Cancel", - ) - - response = filechooser.run() - - if response == Gtk.ResponseType.ACCEPT: - folder = filechooser.get_filename() - if folder and not any(row[0] == folder for row in self.liststore_game_dirs): - self.liststore_game_dirs.append([folder]) - - filechooser.destroy() + folder = pick_folder("Select a game directory", self) + if folder and not any(row[0] == folder for row in self.liststore_game_dirs): + self.liststore_game_dirs.append([folder]) def populate_combobox_with_runners(self): """Fill the Proton runner combobox with available runners.""" @@ -514,11 +502,11 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): runner = self.combobox_runner.get_active_text() if runner: variant = proton_to_steamrt_variant(runner) - self.label_umu_runtime_variant.set_text(f"Expected: {variant}") - self.label_umu_runtime_variant.set_sensitive(True) + self.label_steam_runtime_variant.set_text(f"Expected: {variant}") + self.label_steam_runtime_variant.set_sensitive(True) else: - self.label_umu_runtime_variant.set_text("Expected: steamrt3") - self.label_umu_runtime_variant.set_sensitive(False) + self.label_steam_runtime_variant.set_text("Expected: steamrt3") + self.label_steam_runtime_variant.set_sensitive(False) def on_entry_changed(self, widget, entry): """Remove the 'required' CSS class once the entry has text.""" @@ -709,13 +697,13 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): error_dialog.run() error_dialog.destroy() - def on_button_umu_runtime_clicked(self, widget): + def on_button_steam_runtime_clicked(self, widget): """Trigger Steam Runtime download/update in a background thread.""" widget.set_sensitive(False) - self.progress_umu_runtime.set_visible(True) - self.progress_umu_runtime.set_fraction(0.0) - self.progress_umu_runtime.set_text("0%") - self.label_umu_runtime_status.set_text("Updating…") + self.progress_steam_runtime.set_visible(True) + self.progress_steam_runtime.set_fraction(0.0) + self.progress_steam_runtime.set_text("0%") + self.label_steam_runtime_status.set_text("Updating…") def runtime_thread(): runner = self.get_default_runner() @@ -724,10 +712,10 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): return def update_progress(line): - GLib.idle_add(self.progress_umu_runtime.set_text, line.strip()) + GLib.idle_add(self.progress_steam_runtime.set_text, line.strip()) def progress_cb(percent): - GLib.idle_add(self.progress_umu_runtime.set_fraction, percent / 100.0) + GLib.idle_add(self.progress_steam_runtime.set_fraction, percent / 100.0) GLib.idle_add(update_progress, "Updating…") def on_success(): @@ -742,12 +730,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): def _on_runtime_done(self, success: bool, message: str) -> bool: """Callback after Steam Runtime update completes.""" - self.button_umu_runtime.set_sensitive(True) - self.progress_umu_runtime.set_visible(False) - self.label_umu_runtime_status.set_text(message) + self.button_steam_runtime.set_sensitive(True) + self.progress_steam_runtime.set_visible(False) + self.label_steam_runtime_status.set_text(message) if success: - self.progress_umu_runtime.set_fraction(1.0) + self.progress_steam_runtime.set_fraction(1.0) else: error_dialog = Gtk.MessageDialog( parent=self.parent, @@ -840,9 +828,9 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): # Load Steam Runtime last-check time last_check = get_steamrt_last_check() if last_check: - self.label_umu_runtime_last.set_text(f"Last checked: {last_check}") + self.label_steam_runtime_last.set_text(f"Last checked: {last_check}") else: - self.label_umu_runtime_last.set_text("Last checked: -") + self.label_steam_runtime_last.set_text("Last checked: -") def load_liststore_from_file(self, filename=envar_dir): """Read environment variable lines from *filename* and populate the liststore.""" diff --git a/fungus/shortcuts.py b/fungus/shortcuts.py new file mode 100644 index 0000000..ae2a193 --- /dev/null +++ b/fungus/shortcuts.py @@ -0,0 +1,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 diff --git a/fungus/splash_window.py b/fungus/splash_window.py new file mode 100644 index 0000000..7edbbc6 --- /dev/null +++ b/fungus/splash_window.py @@ -0,0 +1,169 @@ +"""Splash window for game launch output. + +Provides a ``SplashWindow`` class that displays a modal window with +live stdout/stderr output during game launch, and can show error +information (exit code, accumulated stderr) when the process fails. +""" + +from __future__ import annotations + +from collections.abc import Callable + +import gi + +gi.require_version("Gtk", "3.0") +from gi.repository import Gtk # type: ignore + +from fungus.constants import fungus_png + + +class SplashWindow: + """A splash window showing live game output and error information.""" + + def __init__(self, title: str, on_close: Callable[[], None]) -> None: + """Create the splash window. + + Parameters + ---------- + title : str + Window title (usually the game name). + on_close : callable + Callback invoked when the user clicks the Close button. + """ + self._on_close = on_close + self._window = Gtk.Window(title=title) + + self._buffer = None + self._text_view = None + self._scrolled = None + self._close_button = None + + self._build() + + # ── UI construction ─────────────────────────────────────────────────── + + def _build(self) -> None: + """Build the splash window UI.""" + self._window.set_decorated(True) + self._window.set_resizable(True) + self._window.set_default_size(840, 400) + self._window.set_icon_from_file(fungus_png) + + frame = Gtk.Frame() + frame.set_label_align(0.5, 0.5) + frame.set_shadow_type(Gtk.ShadowType.ETCHED_IN) + + grid = Gtk.Grid() + grid.set_hexpand(True) + grid.set_vexpand(True) + grid.set_row_spacing(10) + frame.add(grid) + + # Live output text view (hidden until output arrives) + self._buffer = Gtk.TextBuffer() + self._text_view = Gtk.TextView(buffer=self._buffer) + self._text_view.set_editable(False) + self._text_view.set_cursor_visible(False) + self._text_view.set_monospace(True) + self._text_view.set_margin_top(5) + self._text_view.set_margin_bottom(5) + self._text_view.set_margin_start(10) + self._text_view.set_margin_end(10) + self._text_view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) + self._text_view.get_style_context().add_class("output-view") + + self._scrolled = Gtk.ScrolledWindow() + self._scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + self._scrolled.set_min_content_height(120) + self._scrolled.set_hexpand(True) + self._scrolled.set_vexpand(True) + self._scrolled.set_visible(False) + self._scrolled.add(self._text_view) + grid.attach(self._scrolled, 0, 1, 1, 1) + + # Close button (hidden until error) + self._close_button = Gtk.Button(label="Close") + self._close_button.set_sensitive(False) + self._close_button.set_size_request(150, -1) + self._close_button.connect("clicked", self._on_close_clicked) + grid.attach(self._close_button, 0, 2, 1, 1) + + self._window.add(frame) + self._window.show_all() + + # ── Public API ──────────────────────────────────────────────────────── + + def append_output(self, line: str) -> None: + """Append a line of output to the text view. + + Parameters + ---------- + line : str + Text line to append. + """ + if self._buffer is None or self._text_view is None: + return + + end = self._buffer.get_end_iter() + self._buffer.insert(end, line + "\n") + self._text_view.scroll_to_iter(end, 0.0, True, 0.0, 1.0) + + # Reveal output view on first output + if self._scrolled is not None: + self._scrolled.set_visible(True) + + def show_error(self, exit_code: int, stderr_lines: list[str]) -> None: + """Show error information in the splash window. + + Parameters + ---------- + exit_code : int + Non-zero process exit code. + stderr_lines : list[str] + Accumulated stderr output. + """ + assert self._window is not None + + # Update window title with exit code + current_title = self._window.get_title() or "" + self._window.set_title(f"{current_title} — exited with code {exit_code}") + + # Show accumulated stderr in the text view + if stderr_lines and self._buffer is not None: + error_text = "\n".join(stderr_lines) + self.append_output(f"\n--- stderr ({len(stderr_lines)} lines) ---") + self.append_output(error_text) + + # Reveal output view and close button + if self._scrolled is not None: + self._scrolled.set_visible(True) + if self._close_button is not None: + self._close_button.set_visible(True) + self._close_button.set_sensitive(True) + + def close(self) -> None: + """Destroy the splash window and invoke the close callback.""" + if self._window is not None: + self._window.destroy() # type: ignore[union-attr] + self._on_close() + + def show(self) -> None: + """Show the splash window (no-op if already visible).""" + if self._window is not None: + self._window.show_all() + + def hide(self) -> None: + """Hide the splash window.""" + if self._window is not None: + self._window.hide() + + def destroy(self) -> None: + """Destroy the window and release all references.""" + if self._window is not None: + self._window.destroy() # type: ignore[union-attr] + + # ── Internal ────────────────────────────────────────────────────────── + + def _on_close_clicked(self, _widget: Gtk.Widget) -> None: + """Handle the Close button click.""" + self.close() |
