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.
This commit is contained in:
Bananaman
2023-03-25 14:29:28 +01:00
parent 501747ee36
commit 732bb77192

View File

@@ -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,
)