From 732bb77192f59bc61fc77481383c086373a99417 Mon Sep 17 00:00:00 2001 From: Bananaman <38923130+Bananaman@users.noreply.github.com> Date: Sat, 25 Mar 2023 14:29:28 +0100 Subject: [PATCH] Refactor game launching, and fix Windows support The function was getting a bit convoluted to follow, and there was a maintenance burden of having to remember that "shell=True" should only be true if the argument is a single string to be passed exactly as-is to the shell. If it's a list, only the first value in the list would be ran as the shell command and the rest would be given as arguments to the shell itself. Therefore, it's been refactored to automatically determine shell-mode based on whether "args" is a list or a string. On Windows, we now generate a correctly escaped shell-string via "shlex". This ensures that we properly support spaces inside quoted launch arguments, by auto-escaping them on a per-argument basis. The extra pylint hint is needed because the import is detected as unused on non-Windows machines. --- src/game.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/game.py b/src/game.py index e9fbeab..9cd2995 100644 --- a/src/game.py +++ b/src/game.py @@ -19,6 +19,7 @@ import json import os +import shlex # pylint: disable=unused-import import subprocess import sys @@ -76,12 +77,21 @@ class game(Gtk.Box): # pylint: disable=invalid-name self.menu_button.get_popover().connect("notify::visible", self.hide_play) def launch(self): - # The host environment vars are automatically passed through by Popen. - subprocess.Popen( + # Generate launch arguments, either list (no shell) or a string (for shell). + args = ( ["flatpak-spawn", "--host", *self.executable] # Flatpak if os.getenv("FLATPAK_ID") == "hu.kramo.Cartridges" - else self.executable, # Others - shell=os.name == "nt", # Set shell to True on Windows + else shlex.join( + self.executable + ) # Windows (We need shell to support its "open" built-in). + if os.name == "nt" + else self.executable # Linux/Others + ) + + # The host environment vars are automatically passed through by Popen. + subprocess.Popen( + args, + shell=isinstance(args, str), start_new_session=True, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0, )