#!/usr/bin/python3 """Main window — game list, sidebar, search, play/kill/edit/delete, context menus.""" import logging import os import shutil import subprocess import sys import threading import gi gi.require_version('Gtk', '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, desktop_dir, fungus_backup, fungus_launcher_dir, fungus_png, fungus_run, fungus_version, games_dir, games_json, icons_dir, umu_run, ) from fungus.dialogs import ( GameDirectoriesNotConfiguredDialog, UmuLauncherNotInstalledDialog, show_warning_dialog, ) from fungus.game_model import ( Game, GameLibrary, ) from fungus.dispatcher import GtkDispatcher from fungus.settings_dialog import SettingsDialog from fungus.utils import format_title, is_safe_prefix_path log = get_logger(__name__) class Main(Gtk.ApplicationWindow): def __init__(self, app): """Initialize the main window, build the UI, and load config.""" super().__init__(application=app, title="Fungus Launcher") self.set_icon_from_file(fungus_png) self.connect("delete-event", self.on_close) log.info("Fungus Launcher %s", fungus_version) self.start_maximized = False self.current_prefix = None self.games = [] self.flowbox_child = None self.dispatcher = GtkDispatcher(lambda d: GLib.timeout_add(50, d.pump)) self.last_click_time = 0 self.last_clicked_item = None self.double_click_time_threshold = 400 self.processes = {} self.working_directory = fungus_launcher_dir os.chdir(self.working_directory) self.provider = Gtk.CssProvider() self.provider.load_from_data(b""" .hbox-favorite { background-color: alpha(@theme_selected_bg_color, 0.25); } .hbox-normal { background-color: alpha(@theme_base_color, 0.5); } """) Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), self.provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self.load_config() # Store whether discrete GPU is globally enabled — used by # on_item_right_click to show/hide the "Play on iGPU" menu item. self._discrete_gpu = ConfigManager().get_bool("discrete-gpu", False) self.context_menu = Gtk.Menu() self.menu_item_title = Gtk.MenuItem(label="") self.menu_item_title.set_sensitive(False) self.context_menu.append(self.menu_item_title) self.menu_item_playtime = Gtk.MenuItem(label="") self.menu_item_playtime.set_sensitive(False) self.context_menu.append(self.menu_item_playtime) self.context_menu.append(Gtk.SeparatorMenuItem()) self.menu_item_play = Gtk.MenuItem(label="Play") self.menu_item_play.connect("activate", self.on_context_menu_play) self.context_menu.append(self.menu_item_play) self.menu_item_play_igpu = Gtk.MenuItem(label="Play on iGPU") self.menu_item_play_igpu.connect("activate", self.on_context_menu_play_igpu) self.menu_item_play_igpu.set_visible(False) self.context_menu.append(self.menu_item_play_igpu) self.menu_item_edit = Gtk.MenuItem(label="Edit") self.menu_item_edit.connect("activate", self.on_context_menu_edit) self.context_menu.append(self.menu_item_edit) self.menu_item_delete = Gtk.MenuItem(label="Delete") 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) self.menu_item_favorite = Gtk.MenuItem(label="Add to favorites") 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) self.menu_item_prefix = Gtk.MenuItem(label="Open prefix location") 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() # ── Lifecycle & Config ─────────────────────────────────────────────── def on_close(self, *_): """Handle the delete-event by quitting the application.""" self.get_application().quit() return False def on_destroy(self, *args): """Handle the destroy signal by quitting the application.""" self.dispatcher.stop() self.get_application().quit() def load_config(self): """Load start-maximized, show-hidden, and game-directories from config.""" cfg = ConfigManager() self.start_maximized = cfg.get_bool('start-maximized', False) self.show_hidden = cfg.get_bool('show-hidden', False) self.game_directories = cfg.get('game-directories', '').strip() # ── Interface Layout ───────────────────────────────────────────────── def small_interface(self): """Build the full main-window UI: layout, search, flowbox, buttons.""" self.set_default_size(-1, 610) self.set_resizable(False) # Create main box and its components self.box_main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.box_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.box_bottom = Gtk.Box() # Create button for adding games self.button_add = Gtk.Button() self.button_add.connect("clicked", self.on_button_add_clicked) self.button_add.set_can_focus(False) self.button_add.set_size_request(50, 50) self.button_add.set_image(Gtk.Image.new_from_icon_name("list-add-symbolic", Gtk.IconSize.BUTTON)) self.button_add.set_margin_top(10) self.button_add.set_margin_start(10) self.button_add.set_margin_bottom(10) # Create button for settings button_settings = Gtk.Button() button_settings.connect("clicked", self.on_button_settings_clicked) button_settings.set_can_focus(False) button_settings.set_size_request(50, 50) button_settings.set_image(Gtk.Image.new_from_icon_name("emblem-system-symbolic", Gtk.IconSize.BUTTON)) button_settings.set_margin_top(10) button_settings.set_margin_end(10) button_settings.set_margin_bottom(10) self.entry_search = Gtk.Entry() self.entry_search.set_placeholder_text("Search...") self.entry_search.connect("changed", self.on_search_changed) self.entry_search.set_size_request(300, 50) self.entry_search.set_margin_top(10) self.entry_search.set_margin_start(10) self.entry_search.set_margin_bottom(10) self.entry_search.set_margin_end(10) # Create scrolled window for game list scroll_box = Gtk.ScrolledWindow() scroll_box.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) scroll_box.set_margin_start(10) scroll_box.set_margin_top(10) scroll_box.set_margin_end(10) self.flowbox = Gtk.FlowBox() self.flowbox.set_selection_mode(Gtk.SelectionMode.SINGLE) self.flowbox.set_halign(Gtk.Align.FILL) self.flowbox.set_valign(Gtk.Align.START) self.flowbox.connect('child-activated', self.on_item_selected) self.flowbox.connect('button-release-event', self.on_item_release_event) def sort_games(child1, child2, _): g1 = child1.game g2 = child2.game if g1.favorite and not g2.favorite: return -1 if not g1.favorite and g2.favorite: return 1 return (g1.title > g2.title) - (g1.title < g2.title) self.flowbox.set_sort_func(sort_games, None) scroll_box.add(self.flowbox) self._maybe_migrate() self.library = GameLibrary() self.load_games() # Pack left and scrolled box into the top box self.box_top.pack_start(scroll_box, True, True, 0) # Pack buttons and other components into the bottom box self.box_bottom.pack_start(self.button_add, False, False, 0) self.box_bottom.pack_start(self.entry_search, True, True, 0) self.box_bottom.pack_end(button_settings, False, False, 0) # Pack top and bottom boxes into the main box self.box_main.pack_start(self.box_top, True, True, 0) self.box_main.pack_end(self.box_bottom, False, True, 0) self.add(self.box_main) self.menu_item_edit.set_sensitive(False) self.menu_item_delete.set_sensitive(False) self.select_first_child() self.flowbox.connect("button-press-event", self.on_item_right_click) self.connect("key-press-event", self.on_key_press_event) self.show_all() # ── Selection & Navigation ─────────────────────────────────────────── def select_first_child(self): """Select the first visible child in the flowbox.""" if self.flowbox.get_children(): self.flowbox.select_child(self.flowbox.get_children()[0]) self.on_item_selected(self.flowbox, self.flowbox.get_children()[0]) def get_item_at_event(self, event): """Return the FlowBoxChild at the given (x, y) coordinates.""" x, y = event.x, event.y return self.flowbox.get_child_at_pos(x, y) def select_game_by_title(self, title): """Select and display the game whose title matches *title*.""" # Selects an item from the FlowBox based on the title child = None for child in self.flowbox.get_children(): hbox = child.get_children()[0] # The first item is the hbox containing the label game_label = hbox.get_children()[1] # The second item is the title label if game_label.get_text() == title: # Selects the child in the FlowBox self.flowbox.select_child(child) break # Calls the item selection method to ensure the buttons are updated if child is not None: self.on_item_selected(self.flowbox, child) def on_item_release_event(self, widget, event): """Handle primary-button release — single or double click.""" if event.button == Gdk.BUTTON_PRIMARY: current_time = event.time current_item = self.get_item_at_event(event) if current_item: self.flowbox.select_child(current_item) if current_item == self.last_clicked_item and current_time - self.last_click_time < self.double_click_time_threshold: self.on_item_double_click(current_item) self.last_clicked_item = current_item self.last_click_time = current_time def on_item_right_click(self, widget, event): """Build and show the context menu on right-click.""" if event.button == Gdk.BUTTON_SECONDARY: item = self.get_item_at_event(event) if item: self.flowbox.emit('child-activated', item) self.flowbox.select_child(item) selected_children = self.flowbox.get_selected_children() selected_child = selected_children[0] game = selected_child.game title = game.title self.menu_item_title.get_child().set_text(title) games_data = self.library.load_all() for game_data in games_data: if game_data.gameid == game.gameid: game.playtime = game_data.playtime formatted = self.format_playtime(game.playtime) if not formatted: self.menu_item_playtime.hide() else: self.menu_item_playtime.show() self.menu_item_playtime.get_child().set_text(formatted) break if game.hidden: self.menu_item_hide.get_child().set_text("Remove from hidden") else: self.menu_item_hide.get_child().set_text("Hide") if game.favorite: self.menu_item_favorite.get_child().set_text("Remove from favorites") else: self.menu_item_favorite.get_child().set_text("Add to favorites") # All games use Proton variants now — always show game-related menu items self.menu_item_game.set_visible(True) self.menu_item_prefix.set_visible(True) # Show "Play on iGPU" only when global discrete GPU is enabled self.menu_item_play_igpu.set_visible(self._discrete_gpu) if os.path.dirname(game.path): self.menu_item_game.set_sensitive(True) self.current_game = os.path.dirname(game.path) else: self.menu_item_game.set_sensitive(False) self.current_game = None if os.path.isdir(game.prefix): self.menu_item_prefix.set_sensitive(True) self.current_prefix = game.prefix else: 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) # ── Migration ──────────────────────────────────────────────────────── def _maybe_migrate(self): """Migrate from monolithic games.json to per-game INI files, if needed. Runs silently on startup. If migration fails, logs the error and returns False so that load_games can fall back to the old format. """ from fungus.game_model import migrate_to_per_game, needs_migration if not needs_migration(games_json, games_dir): return True try: result = migrate_to_per_game(games_json, games_dir) log.info( "Migrated %d games, skipped %d duplicates, %d errors", result.migrated, result.skipped_duplicate, result.skipped_error, ) if result.errors: for err in result.errors: log.warning("Migration warning: %s", err) except Exception: log.exception("Migration failed; falling back to games.json") return False return True # ── Game List Rendering ────────────────────────────────────────────── def load_games(self): """Load games from the library, filter hidden ones, and render the flowbox.""" games_data = self.library.load_all() self.games.clear() for game in games_data: if not self.show_hidden and game.hidden: continue self.games.append(game) self.games = sorted(self.games, key=lambda x: x.title.lower()) self.filtered_games = self.games[:] self.flowbox.foreach(Gtk.Widget.destroy) for game in self.filtered_games: self.add_item_list(game) def add_item_list(self, game): """Create and append a FlowBoxChild (icon + label) for *game*.""" hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) if game.favorite: hbox.get_style_context().add_class("hbox-favorite") else: hbox.get_style_context().add_class("hbox-normal") game_icon = f'{icons_dir}/{game.gameid}.ico' game_label = Gtk.Label.new(game.title) if not os.path.isfile(game_icon): game_icon = fungus_png self.flowbox_child = Gtk.FlowBoxChild() pixbuf = GdkPixbuf.Pixbuf.new_from_file(game_icon) scaled_pixbuf = pixbuf.scale_simple(40, 40, GdkPixbuf.InterpType.BILINEAR) image = Gtk.Image.new_from_file(game_icon) image.set_from_pixbuf(scaled_pixbuf) image.set_margin_start(10) image.set_margin_end(10) image.set_margin_top(10) image.set_margin_bottom(10) game_label.set_margin_start(10) game_label.set_margin_end(10) game_label.set_margin_top(10) game_label.set_margin_bottom(10) hbox.pack_start(image, False, False, 0) hbox.pack_start(game_label, False, False, 0) self.flowbox_child.set_size_request(300, -1) self.flowbox.set_homogeneous(True) self.flowbox_child.set_valign(Gtk.Align.START) self.flowbox_child.set_halign(Gtk.Align.FILL) self.flowbox_child.add(hbox) self.flowbox_child.game = game self.flowbox.add(self.flowbox_child) # ── Search & Filter ────────────────────────────────────────────────── def on_search_changed(self, entry): """Filter flowbox children based on the search entry text.""" search_text = entry.get_text().lower() first_visible = None for child in self.flowbox.get_children(): game = child.game is_match = search_text in game.title.lower() child.set_visible(is_match) if is_match and first_visible is None: first_visible = child if first_visible: self.flowbox.select_child(first_visible) self.on_item_selected(self.flowbox, first_visible) def update_list(self): """Clear the flowbox, reload games from disk, and re-render.""" for child in self.flowbox.get_children(): self.flowbox.remove(child) self.games.clear() self.load_games() self.entry_search.set_text("") self.show_all() # ── Item Selection ─────────────────────────────────────────────────── def on_item_selected(self, flowbox, child): """Update context-menu sensitivity and play-button label on selection.""" if child is not None: self.menu_item_edit.set_sensitive(True) self.menu_item_delete.set_sensitive(True) else: self.menu_item_edit.set_sensitive(False) self.menu_item_delete.set_sensitive(False) self.menu_item_play.get_child().set_text("Play") def on_item_double_click(self, item): """Launch the game associated with the selected flowbox child.""" selected_children = self.flowbox.get_selected_children() if not selected_children: return selected_child = selected_children[0] self._launch_game(selected_child.game) # ── Playtime Formatting ────────────────────────────────────────────── def format_playtime(self, seconds): """Format seconds into a human-readable string (e.g. '2 hours 15 minutes').""" if not seconds: return None try: seconds = int(seconds) except (ValueError, TypeError): seconds = 0 hours = seconds // 3600 minutes = (seconds % 3600) // 60 if hours == 0 and minutes == 0: return None txt_hour = "hour" txt_hours = "hours" txt_minute = "minute" txt_minutes = "minutes" parts = [] if hours > 0: word = txt_hour if hours == 1 else txt_hours parts.append(f"{hours} {word}") if minutes > 0: word = txt_minute if minutes == 1 else txt_minutes parts.append(f"{minutes} {word}") return " ".join(parts) # ── Context Menu Handlers ──────────────────────────────────────────── def on_context_menu_play(self, menu_item): """Launch the currently selected game.""" selected_item = self.flowbox.get_selected_children()[0] self._launch_game(selected_item.game) def on_context_menu_play_igpu(self, menu_item): """Launch the currently selected game using the integrated GPU.""" selected_item = self.flowbox.get_selected_children()[0] self._launch_game(selected_item.game, igpu=True) def on_context_menu_edit(self, menu_item): """Open the edit dialog for the currently selected game.""" selected_item = self.flowbox.get_selected_children()[0] self.on_button_edit_clicked(selected_item) def on_context_menu_delete(self, menu_item): """Delete the currently selected game after confirmation.""" selected_item = self.flowbox.get_selected_children()[0] self.on_button_delete_clicked(selected_item) def on_context_menu_hide(self, menu_item): """Toggle the hidden flag on the selected game.""" selected = self.flowbox.get_selected_children() if not selected: return game = selected[0].game if not game: return game.hidden = not game.hidden self.library.update_field(game.gameid, "hidden", game.hidden) self.update_list() self.select_first_child() def on_context_menu_favorite(self, menu_item): """Toggle the favorite flag on the selected game.""" selected = self.flowbox.get_selected_children() if not selected: return game = selected[0].game if not game: return game.favorite = not game.favorite self.library.update_field(game.gameid, "favorite", game.favorite) self.update_list() for child in self.flowbox.get_children(): if hasattr(child, "game") and child.game.gameid == game.gameid: self.flowbox.select_child(child) self.flowbox.set_focus_child(child) break def on_context_menu_game(self, menu_item): """Open the game's directory with xdg-open.""" if not self.current_game: return subprocess.run(["xdg-open", self.current_game], check=True) def on_context_menu_prefix(self, menu_item): """Open the game's Wine prefix directory with xdg-open.""" if not self.current_prefix: 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): """Open the Settings dialog.""" settings_dialog = SettingsDialog(self, self.dispatcher) settings_dialog.connect("response", self.on_settings_dialog_response, settings_dialog) settings_dialog.show() def on_button_add_clicked(self, widget): """Open the Add Game dialog.""" file_path = "" from fungus.add_game_dialog import AddGame add_game_dialog = AddGame(self, file_path, dispatcher=self.dispatcher) add_game_dialog.connect("response", self.on_dialog_response, add_game_dialog) add_game_dialog.show() def on_button_edit_clicked(self, widget): """Open the Edit Game dialog pre-filled with the selected game's data.""" from fungus.add_game_dialog import AddGame file_path = "" selected_children = self.flowbox.get_selected_children() selected_child = selected_children[0] game = selected_child.game if game: edit_game_dialog = AddGame(self, file_path, is_editing=True, dispatcher=self.dispatcher) edit_game_dialog._prefix_status_label.set_visible(False) edit_game_dialog.connect("response", self.on_edit_dialog_response, edit_game_dialog, game) model_runner = edit_game_dialog.combobox_runner.get_model() index_runner = 0 game_runner = game.runner for i, row in enumerate(model_runner): if row[0] == game_runner: index_runner = i break if not game_runner: index_runner = 1 edit_game_dialog.combobox_runner.set_active(index_runner) edit_game_dialog.entry_title.set_text(game.title) edit_game_dialog.entry_path.set_text(game.path) edit_game_dialog.entry_prefix.set_text(game.prefix) edit_game_dialog.entry_launch_arguments.set_text(game.launch_arguments) edit_game_dialog.entry_game_arguments.set_text(game.game_arguments) edit_game_dialog.set_title("Edit %s" % game.title) edit_game_dialog.entry_protonfix.set_text(game.protonfix) edit_game_dialog.grid_launcher.set_visible(False) edit_game_dialog.populate_environment_from_game(game) image = self.set_image_shortcut_icon(game.title, edit_game_dialog.icons_path, edit_game_dialog.icon_temp) edit_game_dialog.button_shortcut_icon.set_image(image) edit_game_dialog.show() def on_button_delete_clicked(self, widget): """Delete the selected game after confirming with the user.""" self.reload_playtimes() selected_children = self.flowbox.get_selected_children() selected_child = selected_children[0] game = selected_child.game title = game.title if game: if show_warning_dialog( self, "Are you sure you want to delete %s? This will also remove its Wine prefix." % title, confirm=True, ): # Remove game and Wine prefix prefix_path = os.path.expanduser(game.prefix) if not is_safe_prefix_path(prefix_path): self.show_warning_dialog( self, "Cannot delete prefix: the path is too broad and would remove important files.", ) return try: shutil.rmtree(prefix_path) except PermissionError: try: os.system(f'chmod -R u+rwX "{prefix_path}"') shutil.rmtree(prefix_path) except Exception as e2: self.show_warning_dialog( self, "Failed to remove prefix.", str(e2) ) except FileNotFoundError: pass # Remove the shortcut self.remove_shortcut(game, "both") self._deleted_gameid = game.gameid self.library.delete(game.gameid) self.games = [g for g in self.games if g.gameid != game.gameid] self.library.save_all(self.games) self.update_list() self.select_first_child() def _launch_game(self, game, igpu: bool = False): """Launch the given game via fungus_run. Parameters ---------- game : Game The game to launch. igpu : bool If True, pass ``--igpu`` to override discrete GPU and use the integrated GPU for this invocation only. """ game_directory = os.path.dirname(game.path) cwd = game_directory if game_directory and os.path.isdir(game_directory) else None cmd = [sys.executable, fungus_run, "--game", game.gameid] if logging.root.level <= logging.DEBUG: cmd.insert(2, "--verbose") if igpu: cmd.append("--igpu") self.process = subprocess.Popen(cmd, cwd=cwd) GLib.child_watch_add(self.process.pid, self.on_process_exit) def on_button_play_clicked(self, widget): """Legacy entry point — delegates to _launch_game after validation.""" selected_children = self.flowbox.get_selected_children() if not selected_children: return game = selected_children[0].game # Validate that game-directories is configured before allowing launch if not self.game_directories: response = GameDirectoriesNotConfiguredDialog(self).result if response == Gtk.ResponseType.YES: settings_dialog = SettingsDialog(self) settings_dialog.connect( "response", self.on_settings_dialog_response, settings_dialog ) settings_dialog.show() return # Check for UMU-Launcher before launching 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) # ── Dialog Response Handlers ───────────────────────────────────────── def on_dialog_response(self, dialog, response_id, add_game_dialog): """Handle the Add Game dialog response — save the new game or clean up.""" if response_id == Gtk.ResponseType.OK: if not add_game_dialog.validate_fields(entry="path+prefix"): return True prefix = os.path.normpath(add_game_dialog.entry_prefix.get_text()) title = add_game_dialog.entry_title.get_text() title_formatted = format_title(title) protonfix = add_game_dialog.entry_protonfix.get_text() runner = add_game_dialog.combobox_runner.get_active_text() if prefix: if not os.path.isdir(prefix): os.makedirs(prefix, exist_ok=True) # Initialize the Wine prefix via UMU (background thread) gameid = protonfix if protonfix else title_formatted if gameid and runner: env = os.environ.copy() env["GAMEID"] = gameid env["WINEPREFIX"] = prefix env["PROTONPATH"] = runner umu_run_path = umu_run umu_env = env umu_title = title umu_dispatcher = self.dispatcher def _init_prefix(): try: subprocess.run( [umu_run_path, "wineprefixcreate", "/usr/bin/true"], env=umu_env, check=True, capture_output=True, ) log.info("Prefix initialized for '%s'", umu_title) umu_dispatcher.submit( add_game_dialog._set_prefix_status, "Prefix ready", True, ) except subprocess.CalledProcessError as e: log.error("Prefix initialization failed for '%s': %s", umu_title, e.stderr.decode()) umu_dispatcher.submit( add_game_dialog._set_prefix_status, "Prefix init failed", False, ) finally: umu_dispatcher.submit(add_game_dialog._close_after_prefix, response_id) add_game_dialog._set_prefix_status("Creating prefix…", None) threading.Thread(target=_init_prefix, daemon=True).start() return True # defer dialog close log.warning("Skipping prefix init for '%s' (GAMEID or runner missing)", title) if self.library.exists(title_formatted): self.show_warning_dialog( add_game_dialog, "%s already exists." % title, ) return True path = add_game_dialog.entry_path.get_text() launch_arguments = add_game_dialog.entry_launch_arguments.get_text() game_arguments = add_game_dialog.entry_game_arguments.get_text() playtime = 0 hidden = False favorite = False game = Game( title_formatted, title, path, prefix, launch_arguments, game_arguments, protonfix, runner, playtime, hidden, favorite, add_game_dialog._collect_environment_vars(), ) 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.library.save(game) self.games.append(game) self.add_item_list(game) self.update_list() self.select_game_by_title(title) else: if os.path.isfile(add_game_dialog.icon_temp): os.remove(add_game_dialog.icon_temp) if os.path.isdir(add_game_dialog.icon_directory): shutil.rmtree(add_game_dialog.icon_directory) add_game_dialog.destroy() add_game_dialog.destroy() return True def on_edit_dialog_response(self, dialog, response_id, edit_game_dialog, game): """Handle the Edit Game dialog response — persist changes or clean up.""" if response_id == Gtk.ResponseType.OK: if not edit_game_dialog.validate_fields(entry="path+prefix"): return True game.title = edit_game_dialog.entry_title.get_text() game.path = edit_game_dialog.entry_path.get_text() game.prefix = os.path.normpath(edit_game_dialog.entry_prefix.get_text()) game.launch_arguments = edit_game_dialog.entry_launch_arguments.get_text() game.game_arguments = edit_game_dialog.entry_game_arguments.get_text() game.protonfix = edit_game_dialog.entry_protonfix.get_text() game.runner = edit_game_dialog.combobox_runner.get_active_text() game.environment = edit_game_dialog._collect_environment_vars() title_formatted = format_title(game.title) # Runner is already set from combobox_runner — no launcher-type switching needed icon_temp = os.path.expanduser(edit_game_dialog.icon_temp) icon_final = f'{edit_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.library.save(game) self.update_list() self.select_game_by_title(game.title) else: if os.path.isfile(edit_game_dialog.icon_temp): os.remove(edit_game_dialog.icon_temp) if os.path.isdir(edit_game_dialog.icon_directory): shutil.rmtree(edit_game_dialog.icon_directory) edit_game_dialog.destroy() return True def on_settings_dialog_response(self, dialog, response_id, settings_dialog): """Handle the Settings dialog response — reload config or apply changes.""" if fungus_backup: subprocess.Popen([sys.executable, __file__]) self.destroy() self.load_config() settings_dialog.destroy() return if response_id == Gtk.ResponseType.OK: settings_dialog.update_config_file() settings_dialog.update_envar_file() if self.show_hidden != settings_dialog.checkbox_show_hidden.get_active(): self.load_config() self.update_list() self.load_config() settings_dialog.destroy() else: settings_dialog.destroy() def on_process_exit(self, pid, status): """Clear the stored process reference when it exits.""" if self.process and self.process.pid == pid: self.process = None # ── Keyboard Events ────────────────────────────────────────────────── def on_key_press_event(self, widget, event): """Handle keyboard shortcuts: Enter plays, keyboard moves between items.""" if event.keyval == Gdk.KEY_Return: selected_children = self.flowbox.get_selected_children() if selected_children: self._launch_game(selected_children[0].game) return True return False # ── Dialogs (Warning, Logs) ────────────────────────────────────────── def show_warning_dialog(self, parent, text1, text2=None): """Delegate to the shared ``show_warning_dialog`` utility.""" return show_warning_dialog(parent, text1, secondary=text2) # ── Game Data Operations ───────────────────────────────────────────── def reload_playtimes(self): """Reload playtime values from the library onto the in-memory game objects.""" try: games_data = self.library.load_all() except Exception: return playtime_map = {g.gameid: g.playtime for g in games_data} for game in self.games: if game.gameid in playtime_map: game.playtime = playtime_map[game.gameid] def save_games(self): """Persist the current in-memory game list to per-game INI files.""" games_to_save = self.games if hasattr(self, "_deleted_gameid"): games_to_save = [g for g in games_to_save if g.gameid != self._deleted_gameid] del self._deleted_gameid self.library.save_all(games_to_save) # ── Shortcut & Icon Helpers ────────────────────────────────────────── def set_image_shortcut_icon(self, title, icons_path, icon_temp): """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): """Delegate to the shared shortcut creation helper.""" create_shortcut(game, shortcut_state, shortcut, icon_temp, icon_final) def remove_shortcut(self, game, shortcut): """Delegate to the shared shortcut removal helper.""" remove_shortcut(game, shortcut)