#!/usr/bin/python3 """AddGame dialog — add/edit game with runner selection, protonfix search, winecfg/winetricks, prefix search, shortcut creation.""" import gi # type: ignore gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') import os import shutil import subprocess import sys import threading import webbrowser from gi.repository import Gtk, Gdk, GdkPixbuf, GLib # type: ignore from PIL import Image from fungus.config_manager import ConfigManager from fungus.logger import get_logger log = get_logger(__name__) from fungus.constants import ( fungus_png, fungus_run, icons_dir, prefixes_dir, ) from fungus.dispatcher import GtkDispatcher from fungus.shortcuts import ( set_default_icon, find_largest_resolution, ) from fungus.utils import ( EntryTooltipMixin, format_title, is_valid_prefix_path, pick_folder, _validate_text, ) class AddGame(EntryTooltipMixin, Gtk.Dialog): def __init__(self, parent, file_path, is_editing=False, dispatcher=None): """Build the AddGame dialog UI with two notebook pages and wire up all handlers.""" self._is_editing = is_editing # Initialize the AddGame dialog super().__init__(title="New Game/App", parent=parent) # type: ignore[misc] self.set_resizable(False) self.set_modal(True) self.parent_window = parent self.dispatcher = dispatcher or GtkDispatcher(lambda _: None) self.set_icon_from_file(fungus_png) self.icon_directory = f"{icons_dir}/icon_temp/" if not os.path.exists(self.icon_directory): os.makedirs(self.icon_directory) self.icons_path = icons_dir self.icon_extracted = os.path.expanduser(f'{self.icons_path}/icon_temp/icon.ico') self.icon_converted = os.path.expanduser(f'{self.icons_path}/icon_temp/icon.png') self.icon_temp = f'{self.icons_path}/icon_temp.ico' self.box = self.get_content_area() self.box.set_margin_start(0) self.box.set_margin_end(0) self.box.set_margin_top(0) self.box.set_margin_bottom(0) self.content_area = self.get_content_area() self.content_area.set_border_width(0) self.content_area.set_halign(Gtk.Align.CENTER) self.content_area.set_valign(Gtk.Align.CENTER) self.content_area.set_vexpand(True) self.content_area.set_hexpand(True) box_buttons = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) self.grid_page1 = Gtk.Grid() self.grid_page1.set_column_homogeneous(True) self.grid_page1.set_column_spacing(10) self.grid_page2 = Gtk.Grid() self.grid_page2.set_column_homogeneous(True) self.grid_page2.set_column_spacing(10) self.grid_launcher = Gtk.Grid() self.grid_launcher.set_row_spacing(10) self.grid_launcher.set_column_spacing(10) self.grid_launcher.set_margin_start(10) self.grid_launcher.set_margin_end(10) self.grid_launcher.set_margin_top(10) self.grid_title = Gtk.Grid() self.grid_title.set_row_spacing(10) self.grid_title.set_column_spacing(10) self.grid_title.set_margin_start(10) self.grid_title.set_margin_end(10) self.grid_title.set_margin_top(10) self.grid_path = Gtk.Grid() self.grid_path.set_row_spacing(10) self.grid_path.set_column_spacing(10) self.grid_path.set_margin_start(10) self.grid_path.set_margin_end(10) self.grid_path.set_margin_top(10) self.grid_prefix = Gtk.Grid() self.grid_prefix.set_row_spacing(10) self.grid_prefix.set_column_spacing(10) self.grid_prefix.set_margin_start(10) self.grid_prefix.set_margin_end(10) self.grid_prefix.set_margin_top(10) self.grid_runner = Gtk.Grid() self.grid_runner.set_row_spacing(10) self.grid_runner.set_column_spacing(10) self.grid_runner.set_margin_start(10) self.grid_runner.set_margin_end(10) self.grid_runner.set_margin_top(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) self.grid_shortcut_icon.set_margin_start(10) self.grid_shortcut_icon.set_margin_end(10) self.grid_shortcut_icon.set_margin_top(10) self.grid_shortcut_icon.set_margin_bottom(5) # Status label for background prefix initialisation self._prefix_status_label = Gtk.Label(label="") self._prefix_status_label.set_visible(False) self._prefix_status_label.set_halign(Gtk.Align.START) self._prefix_status_label.set_markup("Click OK to create prefix") self._prefix_status_label.set_margin_start(10) self._prefix_status_label.set_margin_bottom(10) self.grid_protonfix = Gtk.Grid() self.grid_protonfix.set_row_spacing(10) self.grid_protonfix.set_column_spacing(10) self.grid_protonfix.set_margin_start(10) self.grid_protonfix.set_margin_end(10) self.grid_protonfix.set_margin_top(10) self.grid_launch_arguments = Gtk.Grid() self.grid_launch_arguments.set_row_spacing(10) self.grid_launch_arguments.set_column_spacing(10) self.grid_launch_arguments.set_margin_start(10) self.grid_launch_arguments.set_margin_end(10) self.grid_launch_arguments.set_margin_top(10) self.grid_game_arguments = Gtk.Grid() self.grid_game_arguments.set_row_spacing(10) self.grid_game_arguments.set_column_spacing(10) self.grid_game_arguments.set_margin_start(10) self.grid_game_arguments.set_margin_end(10) self.grid_game_arguments.set_margin_top(10) self.grid_tools = Gtk.Grid() self.grid_tools.set_row_spacing(10) self.grid_tools.set_column_spacing(10) self.grid_tools.set_margin_start(10) self.grid_tools.set_margin_end(10) self.grid_tools.set_margin_top(10) self.grid_tools.set_margin_bottom(10) css_provider = Gtk.CssProvider() css = """ .required { border-color: Red; } .invalid { border-color: DarkRed; } .combobox { border: 1px solid red; } .prefix-status-ready { color: green; } .prefix-status-error { color: red; } """ css_provider.load_from_data(css.encode('utf-8')) Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) # Widgets for title self.label_title = Gtk.Label(label="Title") self.label_title.set_halign(Gtk.Align.START) self.entry_title = Gtk.Entry() self.entry_title.connect("changed", self.on_entry_changed, self.entry_title) self.entry_title.connect("changed", self.update_prefix_entry) self.entry_title.connect("changed", _validate_text) self.entry_title.set_tooltip_text("Game Title") self.entry_title.set_has_tooltip(True) self.entry_title.connect("query-tooltip", self.on_entry_query_tooltip) # Widgets for path self.label_path = Gtk.Label(label="Path") self.label_path.set_halign(Gtk.Align.START) self.entry_path = Gtk.Entry() self.entry_path.connect("changed", self.on_entry_changed, self.entry_path) if file_path: self.entry_path.set_text(file_path) self.entry_path.set_tooltip_text("/path/to/the/exe") self.entry_path.set_has_tooltip(True) self.entry_path.connect("query-tooltip", self.on_entry_query_tooltip) self.button_pick_exe = Gtk.Button() self.button_pick_exe.set_image(Gtk.Image.new_from_icon_name("system-search-symbolic", Gtk.IconSize.BUTTON)) self.button_pick_exe.connect("clicked", self.on_button_pick_exe_clicked) self.button_pick_exe.set_size_request(50, -1) # Widgets for prefix self.label_prefix = Gtk.Label(label="Prefix") self.label_prefix.set_halign(Gtk.Align.START) self.entry_prefix = Gtk.Entry() self.entry_prefix.connect("changed", self.on_entry_changed, self.entry_prefix) self.entry_prefix.set_tooltip_text("/path/to/the/prefix") self.entry_prefix.set_has_tooltip(True) self.entry_prefix.connect("query-tooltip", self.on_entry_query_tooltip) self.button_browse_prefix = Gtk.Button() self.button_browse_prefix.set_image(Gtk.Image.new_from_icon_name("system-search-symbolic", Gtk.IconSize.BUTTON)) self.button_browse_prefix.connect("clicked", self.on_button_browse_prefix_clicked) self.button_browse_prefix.set_size_request(50, -1) # Widgets for runner self.label_runner = Gtk.Label(label="Proton") self.label_runner.set_halign(Gtk.Align.START) self.combobox_runner = Gtk.ComboBoxText() # Widgets for protonfix self.label_protonfix = Gtk.Label(label="Protonfix") self.label_protonfix.set_halign(Gtk.Align.START) self.entry_protonfix = Gtk.Entry() self.entry_protonfix.set_tooltip_text("UMU ID") self.entry_protonfix.set_has_tooltip(True) self.entry_protonfix.connect("query-tooltip", self.on_entry_query_tooltip) self.button_search_protonfix = Gtk.Button() self.button_search_protonfix.set_image( Gtk.Image.new_from_icon_name("emblem-web-symbolic", Gtk.IconSize.BUTTON)) self.button_search_protonfix.connect("clicked", self.on_button_search_protonfix_clicked) self.button_search_protonfix.set_size_request(50, -1) # Widgets for launch arguments self.label_launch_arguments = Gtk.Label(label="Launch Arguments") self.label_launch_arguments.set_halign(Gtk.Align.START) self.entry_launch_arguments = Gtk.Entry() self.entry_launch_arguments.set_tooltip_text("e.g.: PROTON_USE_WINED3D=1 gamescope -W 2560 -H 1440") self.entry_launch_arguments.set_has_tooltip(True) self.entry_launch_arguments.connect("query-tooltip", self.on_entry_query_tooltip) # Widgets for game arguments self.label_game_arguments = Gtk.Label(label="Game Arguments") self.label_game_arguments.set_halign(Gtk.Align.START) self.entry_game_arguments = Gtk.Entry() self.entry_game_arguments.set_tooltip_text("e.g.: -d3d11 -fullscreen") self.entry_game_arguments.set_has_tooltip(True) self.entry_game_arguments.connect("query-tooltip", self.on_entry_query_tooltip) # Button for Winecfg self.button_winecfg = Gtk.Button(label="Winecfg") self.button_winecfg.set_size_request(120, -1) self.button_winecfg.connect("clicked", self.on_button_winecfg_clicked) # Button for Winetricks self.button_winetricks = Gtk.Button(label="Winetricks") self.button_winetricks.set_size_request(120, -1) self.button_winetricks.connect("clicked", self.on_button_winetricks_clicked) # Button for Run self.button_run = Gtk.Button(label="Run") self.button_run.set_size_request(120, -1) self.button_run.connect("clicked", self.on_button_run_clicked) self.button_run.set_tooltip_text("Run a file inside the prefix") # Button for selection shortcut icon self.button_shortcut_icon = Gtk.Button() self.button_shortcut_icon.set_size_request(120, -1) self.button_shortcut_icon.connect("clicked", self.on_button_shortcut_icon_clicked) self.button_shortcut_icon.set_tooltip_text("Select an icon for the shortcut") # Button Cancel self.button_cancel = Gtk.Button(label="Cancel") self.button_cancel.set_image( Gtk.Image.new_from_icon_name("process-stop-symbolic", Gtk.IconSize.BUTTON)) self.button_cancel.set_image_position(Gtk.PositionType.LEFT) self.button_cancel.connect("clicked", lambda widget: self.response(Gtk.ResponseType.CANCEL)) self.button_cancel.set_size_request(150, -1) # Button Ok self.button_ok = Gtk.Button(label="Ok") self.button_ok.set_image( Gtk.Image.new_from_icon_name("dialog-ok-symbolic", Gtk.IconSize.BUTTON)) self.button_ok.set_image_position(Gtk.PositionType.LEFT) self.button_ok.connect("clicked", lambda widget: self.response(Gtk.ResponseType.OK)) self.button_ok.set_size_request(150, -1) # ── Environment tab widgets ─────────────────────────────────── self.liststore_environment = Gtk.ListStore(str) self.liststore_environment.append([""]) self.treeview_environment = Gtk.TreeView(model=self.liststore_environment) self.treeview_environment.set_has_tooltip(True) self.treeview_environment.connect("query-tooltip", self._on_env_query_tooltip) self.treeview_environment.connect("key-press-event", self.on_env_key_press) renderer_env = Gtk.CellRendererText() renderer_env.set_property("editable", True) renderer_env.set_property("ellipsize", 3) renderer_env.connect("edited", self.on_env_cell_edited) column_env = Gtk.TreeViewColumn("", renderer_env, text=0) self.treeview_environment.set_headers_visible(False) self.treeview_environment.append_column(column_env) scrolled_env = Gtk.ScrolledWindow() scrolled_env.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) scrolled_env.set_min_content_height(130) scrolled_env.add(self.treeview_environment) self._environment_vars: list[str] = [] self.load_config() self.default_prefix = prefixes_dir self.notebook = Gtk.Notebook() self.notebook.set_margin_start(10) self.notebook.set_margin_end(10) self.notebook.set_margin_top(10) self.notebook.set_margin_bottom(10) # notebook.set_show_border(False) self.box.add(self.notebook) page1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.tab_box1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) tab_label1 = Gtk.Label(label="Game/App") tab_label1.set_width_chars(8) tab_label1.set_xalign(0.5) self.tab_box1.pack_start(tab_label1, True, True, 0) self.tab_box1.set_hexpand(True) self.grid_page1.attach(page1, 0, 0, 1, 1) page1.set_hexpand(True) self.notebook.append_page(self.grid_page1, self.tab_box1) # ── Page 3: Environment ─────────────────────────────────────── page3 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) page3.set_hexpand(True) self.tab_box3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) tab_label3 = Gtk.Label(label="Environment") tab_label3.set_width_chars(12) tab_label3.set_xalign(0.5) self.tab_box3.pack_start(tab_label3, True, True, 0) self.tab_box3.set_hexpand(True) env_frame = Gtk.Frame() env_frame.set_shadow_type(Gtk.ShadowType.IN) env_frame.set_border_width(5) env_frame.add(scrolled_env) page3.pack_start(env_frame, True, True, 0) self.notebook.append_page(page3, self.tab_box3) page2 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.tab_box2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) tab_label2 = Gtk.Label(label="Tools") tab_label2.set_width_chars(8) tab_label2.set_xalign(0.5) self.tab_box2.pack_start(tab_label2, True, True, 0) self.tab_box2.set_hexpand(True) self.grid_page2.attach(page2, 0, 0, 1, 1) page2.set_hexpand(True) self.notebook.append_page(self.grid_page2, self.tab_box2) self.grid_title.attach(self.label_title, 0, 0, 4, 1) self.grid_title.attach(self.entry_title, 0, 1, 4, 1) self.entry_title.set_hexpand(True) self.grid_path.attach(self.label_path, 0, 0, 1, 1) self.grid_path.attach(self.entry_path, 0, 1, 3, 1) self.entry_path.set_hexpand(True) self.grid_path.attach(self.button_pick_exe, 3, 1, 1, 1) self.grid_prefix.attach(self.label_prefix, 0, 0, 1, 1) self.grid_prefix.attach(self.entry_prefix, 0, 1, 3, 1) self.entry_prefix.set_hexpand(True) self.grid_prefix.attach(self.button_browse_prefix, 3, 1, 1, 1) self.grid_runner.attach(self.label_runner, 0, 0, 1, 1) self.grid_runner.attach(self.combobox_runner, 0, 1, 1, 1) self.combobox_runner.set_hexpand(True) self.grid_shortcut_icon.add(self.button_shortcut_icon) self.grid_shortcut_icon.set_valign(Gtk.Align.CENTER) 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.grid_shortcut_icon) page1.add(self._prefix_status_label) self.grid_protonfix.attach(self.label_protonfix, 0, 0, 1, 1) self.grid_protonfix.attach(self.entry_protonfix, 0, 1, 3, 1) self.entry_protonfix.set_hexpand(True) self.grid_protonfix.attach(self.button_search_protonfix, 3, 1, 1, 1) self.grid_launch_arguments.attach(self.label_launch_arguments, 0, 0, 4, 1) self.grid_launch_arguments.attach(self.entry_launch_arguments, 0, 1, 4, 1) self.entry_launch_arguments.set_hexpand(True) self.grid_game_arguments.attach(self.label_game_arguments, 0, 0, 4, 1) self.grid_game_arguments.attach(self.entry_game_arguments, 0, 1, 4, 1) self.entry_game_arguments.set_hexpand(True) box_buttons.pack_start(self.button_winetricks, True, True, 0) box_buttons.pack_start(self.button_winecfg, True, True, 0) box_buttons.pack_start(self.button_run, True, True, 0) self.grid_tools.attach(box_buttons, 2, 0, 1, 4) page2.add(self.grid_protonfix) page2.add(self.grid_launch_arguments) page2.add(self.grid_game_arguments) page2.add(self.grid_tools) bottom_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) bottom_box.set_margin_start(10) bottom_box.set_margin_end(10) bottom_box.set_margin_bottom(10) self.button_cancel.set_hexpand(True) self.button_ok.set_hexpand(True) bottom_box.pack_start(self.button_cancel, True, True, 0) bottom_box.pack_start(self.button_ok, True, True, 0) self.box.add(bottom_box) self.populate_combobox_with_runners() model = self.combobox_runner.get_model() index_to_activate = 0 for i, row in enumerate(model): if row[0] == self.default_runner: index_to_activate = i break self.combobox_runner.set_active(index_to_activate) self.button_shortcut_icon.set_image(self.set_image_shortcut_icon()) self.tab_box1.show_all() self.tab_box2.show_all() self.tab_box3.show_all() self.show_all() def populate_combobox_with_runners(self): """Fill the Proton runner combobox with available runners.""" from fungus.utils import populate_combobox_with_runners as _pop _pop(self.combobox_runner) def on_entry_changed(self, widget, entry): """Remove the 'required' CSS class once the entry has text.""" if entry.get_text(): entry.get_style_context().remove_class("required") def load_config(self): """Load the default runner from the config file.""" cfg = ConfigManager() self.default_runner = cfg.get('default-runner', '') def update_prefix_entry(self, entry): """Auto-fill the prefix path using the formatted game title.""" # Auto-fill the prefix entry based on the game title title = entry.get_text().strip() if title: title_formatted = format_title(title) prefix = os.path.join(self.default_prefix, title_formatted) self.entry_prefix.set_text(prefix) else: self.entry_prefix.set_text("") def on_button_run_clicked(self, widget): """Open a file chooser and run the selected file inside the Wine prefix.""" self.set_sensitive(False) validation_result = self.validate_fields(entry="prefix") if not validation_result: self.set_sensitive(True) return filechooser = Gtk.FileChooserNative( title="Select a file to run inside the prefix", transient_for=self, action=Gtk.FileChooserAction.OPEN, accept_label="Open", cancel_label="Cancel", ) windows_filter = Gtk.FileFilter() windows_filter.set_name("Windows files") windows_filter.add_pattern("*.exe") windows_filter.add_pattern("*.msi") windows_filter.add_pattern("*.bat") windows_filter.add_pattern("*.lnk") windows_filter.add_pattern("*.reg") all_files_filter = Gtk.FileFilter() all_files_filter.set_name("All files") all_files_filter.add_pattern("*") filechooser.add_filter(windows_filter) filechooser.add_filter(all_files_filter) filechooser.set_filter(windows_filter) response = filechooser.run() if response == Gtk.ResponseType.ACCEPT: file_run = filechooser.get_filename() title = self.entry_title.get_text() title_formatted = format_title(title) fungus_run_path = fungus_run def run_command(): process = subprocess.Popen( [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", file_run], ) process.wait() self.dispatcher.submit(self.set_sensitive, True) self.dispatcher.submit(self.parent_window.set_sensitive, True) self.dispatcher.submit(self.blocking_window.destroy) self.blocking_window = Gtk.Window() self.blocking_window.set_transient_for(self.parent_window) self.blocking_window.set_decorated(False) self.blocking_window.set_modal(True) command_thread = threading.Thread(target=run_command) command_thread.start() else: self.set_sensitive(True) filechooser.destroy() def on_button_search_protonfix_clicked(self, widget): """Open the UMU component database in the default web browser.""" webbrowser.open("https://umu.openwinecomponents.org/") def set_image_shortcut_icon(self): """Set the default icon (fungus_png) as the shortcut icon preview.""" 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.""" self.set_sensitive(False) validation_result = self.validate_fields(entry="path") if not validation_result: self.set_sensitive(True) return path = self.entry_path.get_text() if os.path.isfile(path): if not os.path.exists(self.icon_directory): os.makedirs(self.icon_directory) try: command = f'icoextract "{path}" "{self.icon_extracted}"' result = subprocess.run(command, shell=True, text=True, capture_output=True, check=False) if result.returncode != 0: if "NoIconsAvailableError" in result.stderr or "PEFormatError" in result.stderr: log.debug("The file does not contain icons.") self.button_shortcut_icon.set_image(self.set_image_shortcut_icon()) else: log.error("Error extracting icon: %s", result.stderr) else: img = Image.open(self.icon_extracted) img.save(self.icon_converted) if os.path.isfile(self.icon_extracted): os.remove(self.icon_extracted) except Exception as e: log.error("An error occurred: %s", e) def is_valid_image(file_path): try: pixbuf = GdkPixbuf.Pixbuf.new_from_file(file_path) return pixbuf is not None except Exception: return False filechooser = Gtk.FileChooserNative.new( "Select an icon for the shortcut", self, Gtk.FileChooserAction.OPEN, "Open", "Cancel" ) filter_ico = Gtk.FileFilter() filter_ico.set_name("Image files") filter_ico.add_pattern("*.png") filter_ico.add_pattern("*.jpg") filter_ico.add_pattern("*.jpeg") filter_ico.add_pattern("*.jxl") filter_ico.add_pattern("*.bmp") filter_ico.add_pattern("*.gif") filter_ico.add_pattern("*.svg") filter_ico.add_pattern("*.ico") filechooser.add_filter(filter_ico) filechooser.set_current_folder(self.icon_directory) response = filechooser.run() if response == Gtk.ResponseType.ACCEPT: file_path = filechooser.get_filename() if not file_path or not is_valid_image(file_path): dialog_image = Gtk.Dialog(title="Fungus Launcher", transient_for=self, modal=True) dialog_image.set_resizable(False) dialog_image.set_icon_from_file(fungus_png) label = Gtk.Label() label.set_label("The selected file is not a valid image.") label.set_halign(Gtk.Align.CENTER) label2 = Gtk.Label() label2.set_label("Please choose another one.") label2.set_halign(Gtk.Align.CENTER) button_yes = Gtk.Button(label="Ok") button_yes.set_size_request(150, -1) button_yes.connect("clicked", lambda x: dialog_image.response(Gtk.ResponseType.YES)) content_area = dialog_image.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) 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_top.pack_start(label, True, True, 0) box_top.pack_start(label2, True, True, 0) box_bottom.pack_start(button_yes, True, True, 0) content_area.add(box_top) content_area.add(box_bottom) dialog_image.show_all() dialog_image.run() dialog_image.destroy() else: shutil.copyfile(file_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) self.button_shortcut_icon.set_image(image) filechooser.destroy() if os.path.isdir(self.icon_directory): shutil.rmtree(self.icon_directory) self.set_sensitive(True) def find_largest_resolution(self, directory): """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.""" if file_path := dialog.get_preview_filename(): try: # Create an image widget for the thumbnail pixbuf = GdkPixbuf.Pixbuf.new_from_file(file_path) # Resize the thumbnail if it's too large, maintaining the aspect ratio max_width = 400 max_height = 400 width = pixbuf.get_width() height = pixbuf.get_height() if width > max_width or height > max_height: # Calculate the new width and height while maintaining the aspect ratio ratio = min(max_width / width, max_height / height) new_width = int(width * ratio) new_height = int(height * ratio) pixbuf = pixbuf.scale_simple(new_width, new_height, GdkPixbuf.InterpType.BILINEAR) image = Gtk.Image.new_from_pixbuf(pixbuf) dialog.set_preview_widget(image) dialog.set_preview_widget_active(True) dialog.get_preview_widget().set_size_request(max_width, max_height) except GLib.Error: dialog.set_preview_widget_active(False) else: dialog.set_preview_widget_active(False) def on_button_winecfg_clicked(self, widget): """Launch winecfg inside the Wine prefix via fungus_run.""" self.set_sensitive(False) # Handle the click event of the Winecfg button validation_result = self.validate_fields(entry="prefix") if not validation_result: self.set_sensitive(True) return title = self.entry_title.get_text() title_formatted = format_title(title) fungus_run_path = fungus_run def run_command(): process = subprocess.Popen( [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", "winecfg"], ) process.wait() self.dispatcher.submit(self.set_sensitive, True) self.dispatcher.submit(self.parent_window.set_sensitive, True) self.dispatcher.submit(self.blocking_window.destroy) self.blocking_window = Gtk.Window() self.blocking_window.set_transient_for(self.parent_window) self.blocking_window.set_decorated(False) self.blocking_window.set_modal(True) command_thread = threading.Thread(target=run_command) command_thread.start() def on_button_winetricks_clicked(self, widget): """Launch winetricks inside the Wine prefix via fungus_run.""" self.set_sensitive(False) # Handle the click event of the Winetricks button validation_result = self.validate_fields(entry="prefix") if not validation_result: self.set_sensitive(True) return title = self.entry_title.get_text() title_formatted = format_title(title) fungus_run_path = fungus_run def run_command(): process = subprocess.Popen( [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", "winetricks"], ) process.wait() self.dispatcher.submit(self.set_sensitive, True) self.dispatcher.submit(self.parent_window.set_sensitive, True) self.dispatcher.submit(self.blocking_window.destroy) self.blocking_window = Gtk.Window() self.blocking_window.set_transient_for(self.parent_window) self.blocking_window.set_decorated(False) self.blocking_window.set_modal(True) command_thread = threading.Thread(target=run_command) command_thread.start() def on_button_pick_exe_clicked(self, widget): """Open a file chooser for the game executable and auto-extract an icon.""" if not self.entry_path.get_text(): initial_folder = os.path.expanduser("~/") else: initial_folder = os.path.dirname(self.entry_path.get_text()) filechooser = Gtk.FileChooserNative( title="Select the game's .exe", transient_for=self, action=Gtk.FileChooserAction.OPEN, accept_label="Open", cancel_label="Cancel", ) filechooser.set_current_folder(initial_folder) windows_filter = Gtk.FileFilter() windows_filter.set_name("Windows files") windows_filter.add_pattern("*.exe") windows_filter.add_pattern("*.msi") windows_filter.add_pattern("*.bat") windows_filter.add_pattern("*.lnk") windows_filter.add_pattern("*.reg") all_files_filter = Gtk.FileFilter() all_files_filter.set_name("All files") all_files_filter.add_pattern("*") filechooser.add_filter(windows_filter) filechooser.add_filter(all_files_filter) filechooser.set_filter(windows_filter) response = filechooser.run() if response == Gtk.ResponseType.ACCEPT: path = filechooser.get_filename() if not os.path.exists(self.icon_directory): os.makedirs(self.icon_directory) try: command = f'icoextract "{path}" "{self.icon_extracted}"' result = subprocess.run(command, shell=True, text=True, capture_output=True, check=False) if result.returncode != 0: if "NoIconsAvailableError" in result.stderr or "PEFormatError" in result.stderr: log.debug("The file does not contain icons.") self.button_shortcut_icon.set_image(self.set_image_shortcut_icon()) else: log.error("Error extracting icon: %s", result.stderr) else: img = Image.open(self.icon_extracted) img.save(self.icon_converted) if os.path.isfile(self.icon_extracted): os.remove(self.icon_extracted) largest_image = self.find_largest_resolution(self.icon_directory) if largest_image is not None: shutil.move(largest_image, os.path.expanduser(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) self.button_shortcut_icon.set_image(image) except Exception as e: log.error("An error occurred: %s", e) self.entry_path.set_text(path) if os.path.isdir(self.icon_directory): shutil.rmtree(self.icon_directory) filechooser.destroy() def on_button_browse_prefix_clicked(self, widget): """Open a folder chooser for the Wine prefix.""" current = self.entry_prefix.get_text() folder = pick_folder( title="Select a prefix location", transient_for=self, current_folder=current if current else os.path.expanduser("~/"), ) if folder: self.entry_prefix.set_text(folder) def validate_fields(self, entry): """Validate required fields and apply 'required' CSS styling on failure. *entry* controls which fields are checked: ``"prefix"`` — title + prefix ``"path"`` — title + path ``"path+prefix"`` — title + path + prefix """ # Validate the input fields for title, prefix and path title = self.entry_title.get_text() prefix = self.entry_prefix.get_text() path = self.entry_path.get_text() self.entry_title.get_style_context().remove_class("required") self.entry_prefix.get_style_context().remove_class("required") self.entry_prefix.get_style_context().remove_class("invalid") self.entry_path.get_style_context().remove_class("required") if entry == "prefix": if not title or not prefix: if not title: self.entry_title.get_style_context().add_class("required") self.notebook.set_current_page(0) if not prefix: self.entry_prefix.get_style_context().add_class("required") self.notebook.set_current_page(0) return False if not is_valid_prefix_path(prefix): self.entry_prefix.get_style_context().add_class("invalid") self.entry_prefix.set_tooltip_text( f"Prefix must be inside {prefixes_dir}" ) self.notebook.set_current_page(1) return False if entry == "path": if not title or not path: if not title: self.entry_title.get_style_context().add_class("required") self.notebook.set_current_page(0) if not path: self.entry_path.get_style_context().add_class("required") self.notebook.set_current_page(0) return False if entry == "path+prefix": if not title or not path or not prefix: if not title: self.entry_title.get_style_context().add_class("required") self.notebook.set_current_page(0) if not path: self.entry_path.get_style_context().add_class("required") self.notebook.set_current_page(0) if not prefix: self.entry_prefix.get_style_context().add_class("required") self.notebook.set_current_page(0) return False if not is_valid_prefix_path(prefix): self.entry_prefix.get_style_context().add_class("invalid") self.entry_prefix.set_tooltip_text( f"Prefix must be inside {prefixes_dir}" ) self.notebook.set_current_page(1) return False return True # ── Background prefix initialisation ───────────────────────────── def _set_prefix_status(self, message: str, success: bool | None) -> None: """Update the prefix-status label and the OK button state. Parameters ---------- message : str Status text to display. success : bool or None ``True`` = ready, ``False`` = failed, ``None`` = in progress. """ if not hasattr(self, "_prefix_status_label"): return self._prefix_status_label.set_visible(True) self._prefix_status_label.set_text(message) if success is True: self._prefix_status_label.get_style_context().add_class("prefix-status-ready") self._prefix_status_label.get_style_context().remove_class("prefix-status-error") self.button_ok.set_sensitive(True) elif success is False: self._prefix_status_label.get_style_context().add_class("prefix-status-error") self._prefix_status_label.get_style_context().remove_class("prefix-status-ready") self.button_ok.set_sensitive(True) # allow user to close and retry else: self._prefix_status_label.get_style_context().remove_class("prefix-status-ready") self._prefix_status_label.get_style_context().remove_class("prefix-status-error") self.button_ok.set_sensitive(False) def _close_after_prefix(self, response_id: int) -> None: """Close the dialog after prefix initialisation finishes.""" if hasattr(self, "blocking_window"): GLib.idle_add(self.blocking_window.destroy) GLib.idle_add(self.response, response_id) # ── Environment tab handlers ───────────────────────────────────── def populate_environment_from_game(self, game): """Pre-populate the environment liststore from a Game object.""" self.liststore_environment.clear() for env_var in game.environment: self.liststore_environment.append([env_var]) self.liststore_environment.append([""]) def _collect_environment_vars(self) -> list[str]: """Collect non-empty rows from the environment liststore.""" return [row[0] for row in self.liststore_environment if row[0].strip()] def on_env_cell_edited(self, widget, path, text): """Update the liststore cell on edit and normalize empty rows.""" self.liststore_environment[path][0] = text self._adjust_env_rows() def _adjust_env_rows(self): """Remove empty rows and ensure a trailing empty row.""" filled_rows = [row[0] for row in self.liststore_environment if row[0].strip() != ""] self.liststore_environment.clear() for value in filled_rows: self.liststore_environment.append([value]) self.liststore_environment.append([""]) def _on_env_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): """Tooltip handler for the environment variable treeview.""" return self.on_list_query_tooltip(widget, x, y, keyboard_mode, tooltip, self.liststore_environment) def on_env_key_press(self, widget, event): """Allow deleting environment variable rows via the Delete key (but not the last empty row).""" if event.keyval == Gdk.KEY_Delete: selection = widget.get_selection() model, treeiter = selection.get_selected() if not treeiter: return False path = model.get_path(treeiter) index = path.get_indices()[0] if index == len(model) - 1: return True model.remove(treeiter) return True return False