Exemplo n.º 1
0
    def on_game_quit(self):
        """Restore some settings and cleanup after game quit."""

        if self.prelaunch_executor and self.prelaunch_executor.is_running:
            logger.info("Stopping prelaunch script")
            self.prelaunch_executor.stop()

        self.heartbeat = None
        if self.state != self.STATE_STOPPED:
            logger.warning("Game still running (state: %s)", self.state)
            self.stop()

        # Check for post game script
        postexit_command = self.runner.system_config.get("postexit_command")
        if postexit_command:
            command_array = shlex.split(postexit_command)
            if system.path_exists(command_array[0]):
                logger.info("Running post-exit command: %s", postexit_command)
                postexit_thread = MonitoredCommand(
                    command_array,
                    include_processes=[os.path.basename(postexit_command)],
                    env=self.game_runtime_config["env"],
                    cwd=self.directory,
                )
                postexit_thread.start()

        quit_time = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
        logger.debug("%s stopped at %s", self.name, quit_time)
        self.lastplayed = int(time.time())
        self.save(save_config=False)

        os.chdir(os.path.expanduser("~"))

        if self.antimicro_thread:
            self.antimicro_thread.stop()

        if self.resolution_changed or self.runner.system_config.get(
                "reset_desktop"):
            DISPLAY_MANAGER.set_resolution(self.original_outputs)

        if self.compositor_disabled:
            self.set_desktop_compositing(True)

        if self.screen_saver_inhibitor_cookie is not None:
            SCREEN_SAVER_INHIBITOR.uninhibit(
                self.screen_saver_inhibitor_cookie)
            self.screen_saver_inhibitor_cookie = None

        if self.runner.system_config.get("use_us_layout"):
            with subprocess.Popen(["setxkbmap"], env=os.environ) as setxkbmap:
                setxkbmap.communicate()

        if self.runner.system_config.get("restore_gamma"):
            restore_gamma()

        self.process_return_codes()
Exemplo n.º 2
0
    def on_game_quit(self):
        """Restore some settings and cleanup after game quit."""

        if self.prelaunch_executor and self.prelaunch_executor.is_running:
            logger.info("Stopping prelaunch script")
            self.prelaunch_executor.stop()

        self.heartbeat = None
        if self.state != self.STATE_STOPPED:
            logger.warning("Game still running (state: %s)", self.state)
            self.stop()

        # Check for post game script
        postexit_command = self.runner.system_config.get("postexit_command")
        if system.path_exists(postexit_command):
            logger.info("Running post-exit command: %s", postexit_command)
            postexit_thread = MonitoredCommand(
                [postexit_command],
                include_processes=[os.path.basename(postexit_command)],
                env=self.game_runtime_config["env"],
                cwd=self.directory,
            )
            postexit_thread.start()

        if self.discord_presence.available:
            self.discord_presence.clear_discord_rich_presence()

        quit_time = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
        logger.debug("%s stopped at %s", self.name, quit_time)
        self.lastplayed = int(time.time())
        self.save(metadata_only=True)

        os.chdir(os.path.expanduser("~"))

        if self.resolution_changed or self.runner.system_config.get(
                "reset_desktop"):
            DISPLAY_MANAGER.set_resolution(self.original_outputs)

        if self.compositor_disabled:
            self.set_desktop_compositing(True)

        if self.runner.system_config.get("use_us_layout"):
            subprocess.Popen(["setxkbmap"], env=os.environ).communicate()

        if self.runner.system_config.get("restore_gamma"):
            restore_gamma()

        self.process_return_codes()
        if self.exit_main_loop:
            exit()
Exemplo n.º 3
0
    def __init__(self, installer, parent):
        super().__init__()
        self.target_path = None
        self.parent = parent
        self.service = parent.service if parent else None
        self.appid = parent.appid if parent else None
        self.game_dir_created = False  # Whether a game folder was created during the install
        # Extra files for installers, either None if the extras haven't been checked yet.
        # Or a list of IDs of extras to be downloaded during the install
        self.extras = None
        self.game_disc = None
        self.game_files = {}
        self.cancelled = False
        self.abort_current_task = None
        self.user_inputs = []
        self.current_command = 0  # Current installer command when iterating through them
        self.runners_to_install = []
        self.installer = LutrisInstaller(installer,
                                         self,
                                         service=self.service,
                                         appid=self.appid)
        if not self.installer.script:
            raise ScriptingError(
                _("This installer doesn't have a 'script' section"))
        script_errors = self.installer.get_errors()
        if script_errors:
            raise ScriptingError(
                _("Invalid script: \n{}").format("\n".join(script_errors)),
                self.installer.script)

        self.current_resolution = DISPLAY_MANAGER.get_current_resolution()
        self._check_binary_dependencies()
        self._check_dependency()
        if self.installer.creates_game_folder:
            self.target_path = self.get_default_target()
Exemplo n.º 4
0
def get_output_choices():
    """Return list of outputs for drop-downs"""
    displays = DISPLAY_MANAGER.get_display_names()
    output_choices = list(zip(displays, displays))
    output_choices.insert(0, ("Off", "off"))
    output_choices.insert(1, ("Primary", "primary"))
    return output_choices
Exemplo n.º 5
0
    def __init__(self, installer, parent):
        super().__init__()
        self.target_path = None
        self.parent = parent
        self.game_dir_created = False  # Whether a game folder was created during the install
        self.game_disc = None
        self.game_files = {}
        self.cancelled = False
        self.abort_current_task = None
        self.user_inputs = []
        self.current_command = 0  # Current installer command when iterating through them
        self.runners_to_install = []
        self.installer = LutrisInstaller(installer, self)
        if not self.installer.script:
            raise ScriptingError("This installer doesn't have a 'script' section")
        script_errors = self.installer.get_errors()
        if script_errors:
            raise ScriptingError(
                "Invalid script: \n{}".format("\n".join(script_errors)), self.installer.script
            )

        self.current_resolution = DISPLAY_MANAGER.get_current_resolution()
        self._check_binary_dependencies()
        self._check_dependency()
        if self.installer.creates_game_folder:
            self.target_path = self.get_default_target()
Exemplo n.º 6
0
def get_resolution_choices():
    """Return list of available resolutions as label, value tuples
    suitable for inclusion in drop-downs.
    """
    resolutions = DISPLAY_MANAGER.get_resolutions()
    resolution_choices = list(zip(resolutions, resolutions))
    resolution_choices.insert(0, ("Keep current", "off"))
    return resolution_choices
Exemplo n.º 7
0
def get_output_list():
    """Return a list of output with their index.
    This is used to indicate to SDL 1.2 which monitor to use.
    """
    choices = [("Off", "off")]
    displays = DISPLAY_MANAGER.get_display_names()
    for index, output in enumerate(displays):
        # Display name can't be used because they might not be in the right order
        # Using DISPLAYS to get the number of connected monitors
        choices.append((output, str(index)))
    return choices
Exemplo n.º 8
0
 def get_params(self):  # pylint: disable=too-many-branches
     params = []
     model = self.runner_config.get("model")
     cpumodel = self.runner_config.get("cpumodel")
     fmemory = self.runner_config.get("fmemory")
     ziiimem = self.runner_config.get("ziiimem")
     fdvolume = self.runner_config.get("fdvolume")
     fdspeed = self.runner_config.get("fdspeed")
     grafixcard = self.runner_config.get("grafixcard")
     grafixmemory = self.runner_config.get("grafixmemory")
     kickstart_file = self.runner_config.get("kickstart_file")
     if kickstart_file:
         params.append("--kickstart_file=%s" % kickstart_file)
     kickstart_ext_file = self.runner_config.get("kickstart_ext_file")
     if kickstart_ext_file:
         params.append("--kickstart_ext_file=%s" % kickstart_ext_file)
     if model:
         params.append("--amiga_model=%s" % model)
     if cpumodel:
         params.append("--cpu=%s" % cpumodel)
     if fmemory:
         params.append("--fast_memory=%s" % fmemory)
     if ziiimem:
         params.append("--zorro_iii_memory=%s" % ziiimem)
     if fdvolume:
         params.append("--floppy_drive_volume=%s" % fdvolume)
     if fdspeed:
         params.append("--floppy_drive_speed=%s" % fdspeed)
     if grafixcard:
         params.append("--graphics_card=%s" % grafixcard)
     if grafixmemory:
         params.append("--graphics_memory=%s" % grafixmemory)
     if self.runner_config.get("gfx_fullscreen_amiga"):
         width = int(DISPLAY_MANAGER.get_current_resolution()[0])
         params.append("--fullscreen")
         # params.append("--fullscreen_mode=fullscreen-window")
         params.append("--fullscreen_mode=fullscreen")
         params.append("--fullscreen_width=%d" % width)
     if self.runner_config.get("jitcompiler"):
         params.append("--jit_compiler=1")
     if self.runner_config.get("bsdsocket"):
         params.append("--bsdsocket_library=1")
     if self.runner_config.get("gamemode"):
         params.append("--game_mode=0")
     if self.runner_config.get("govwarning"):
         params.append("--governor_warning=0")
     if self.runner_config.get("scanlines"):
         params.append("--scanlines=1")
     return params
Exemplo n.º 9
0
    def play(self):
        """Runs the game"""
        rom = self.game_config.get("main_file") or ""
        machine = self.game_config.get("machine") or ""

        fullscreen = self.runner_config.get("fs") or "0"
        if fullscreen is True:
            fullscreen = "1"
        elif fullscreen is False:
            fullscreen = "0"

        stretch = self.runner_config.get("stretch") or "0"
        scaler = self.runner_config.get("scaler") or DEFAULT_MEDNAFEN_SCALER
        sound_device = self.runner_config.get("sound_device")

        xres, yres = DISPLAY_MANAGER.get_current_resolution()
        options = [
            "-fs",
            fullscreen,
            "-force_module",
            machine,
            "-sound.device",
            sound_device,
            "-" + machine + ".xres",
            xres,
            "-" + machine + ".yres",
            yres,
            "-" + machine + ".stretch",
            stretch,
            "-" + machine + ".special",
            scaler,
            "-" + machine + ".videoip",
            "1",
        ]
        joy_ids = self.find_joysticks()
        dont_map_controllers = self.runner_config.get("dont_map_controllers")
        if joy_ids and not dont_map_controllers:
            controls = self.set_joystick_controls(joy_ids, machine)
            for control in controls:
                options.append(control)

        if not system.path_exists(rom):
            return {"error": "FILE_NOT_FOUND", "file": rom}

        command = [self.get_executable()]
        for option in options:
            command.append(option)
        command.append(rom)
        return {"command": command}
Exemplo n.º 10
0
 def set_virtual_desktop(self, enabled):
     """Enable or disable wine virtual desktop.
     The Lutris virtual desktop is refered to as 'WineDesktop', in Wine the
     virtual desktop name is 'default'.
     """
     path = self.hkcu_prefix + "/Software/Wine/Explorer"
     if enabled:
         self.set_registry_key(path, "Desktop", "WineDesktop")
         default_resolution = "x".join(DISPLAY_MANAGER.get_current_resolution())
         logger.debug("Enabling wine virtual desktop with default resolution of %s", default_resolution)
         self.set_registry_key(
             self.hkcu_prefix + "/Software/Wine/Explorer/Desktops",
             "WineDesktop",
             default_resolution
         )
     else:
         self.clear_registry_key(path)
Exemplo n.º 11
0
    def play(self):
        """Runs the game"""
        rom = self.game_config.get("main_file") or ""
        machine = self.game_config.get("machine") or ""

        fullscreen = self.runner_config.get("fs") or "0"
        if fullscreen is True:
            fullscreen = "1"
        elif fullscreen is False:
            fullscreen = "0"

        stretch = self.runner_config.get("stretch") or "0"
        scaler = self.runner_config.get("scaler") or "hq4x"

        xres, yres = DISPLAY_MANAGER.get_current_resolution()
        options = [
            "-fs",
            fullscreen,
            "-force_module",
            machine,
            "-" + machine + ".xres",
            xres,
            "-" + machine + ".yres",
            yres,
            "-" + machine + ".stretch",
            stretch,
            "-" + machine + ".special",
            scaler,
            "-" + machine + ".videoip",
            "1",
        ]
        joy_ids = self.find_joysticks()
        dont_map_controllers = self.runner_config.get("dont_map_controllers")
        if joy_ids and not dont_map_controllers:
            controls = self.set_joystick_controls(joy_ids, machine)
            for control in controls:
                options.append(control)

        if not system.path_exists(rom):
            return {"error": "FILE_NOT_FOUND", "file": rom}

        command = [self.get_executable()]
        for option in options:
            command.append(option)
        command.append(rom)
        return {"command": command}
Exemplo n.º 12
0
 def set_virtual_desktop(self, enabled):
     """Enable or disable wine virtual desktop.
     The Lutris virtual desktop is refered to as 'WineDesktop', in Wine the
     virtual desktop name is 'default'.
     """
     path = self.hkcu_prefix + "/Software/Wine/Explorer"
     if enabled:
         self.set_registry_key(path, "Desktop", "WineDesktop")
         default_resolution = "x".join(DISPLAY_MANAGER.get_current_resolution())
         logger.debug("Enabling wine virtual desktop with default resolution of %s",
                      default_resolution)
         self.set_registry_key(
             self.hkcu_prefix + "/Software/Wine/Explorer/Desktops",
             "WineDesktop",
             default_resolution
         )
     else:
         self.clear_registry_key(path)
Exemplo n.º 13
0
 def restrict_to_display(self, display):
     outputs = DISPLAY_MANAGER.get_config()
     if display == "primary":
         display = None
         for output in outputs:
             if output.primary:
                 display = output.name
                 break
         if not display:
             logger.warning("No primary display set")
     else:
         found = any(output.name == display for output in outputs)
         if not found:
             logger.warning("Selected display %s not found", display)
             display = None
     if display:
         turn_off_except(display)
         time.sleep(3)
         return True
     return False
Exemplo n.º 14
0
 def get_params(self):
     params = []
     model = self.runner_config.get("model")
     fmemory = self.runner_config.get("fmemory")
     fdvolume = self.runner_config.get("fdvolume")
     fdspeed = self.runner_config.get("fdspeed")
     grafixcard = self.runner_config.get("grafixcard")
     grafixmemory = self.runner_config.get("grafixmemory")
     kickstart_file = self.runner_config.get("kickstart_file")
     if kickstart_file:
         params.append("--kickstart_file=%s" % kickstart_file)
     kickstart_ext_file = self.runner_config.get("kickstart_ext_file")
     if kickstart_ext_file:
         params.append("--kickstart_ext_file=%s" % kickstart_ext_file)
     if model:
         params.append("--amiga_model=%s" % model)
     if fmemory:
         params.append("--fast_memory=%s" % fmemory)
     if fdvolume:
         params.append("--floppy_drive_volume_empty=%s" % fdvolume)
     if fdspeed:
         params.append("--floppy_drive_volume_empty=%s" % fdspeed)
     if grafixcard:
         params.append("--graphics_card=%s" % grafixcard)
     if grafixmemory:
         params.append("--graphics_memory=%s" % grafixmemory)
     if self.runner_config.get("gfx_fullscreen_amiga"):
         width = int(DISPLAY_MANAGER.get_current_resolution()[0])
         params.append("--fullscreen")
         # params.append("--fullscreen_mode=fullscreen-window")
         params.append("--fullscreen_mode=fullscreen")
         params.append("--fullscreen_width=%d" % width)
     if self.runner_config.get("jitcompiler"):
         params.append("--jit_compiler=1")
     if self.runner_config.get("jitcompiler"):
         params.append("--bsdsocket_library=1")
     if self.runner_config.get("scanlines"):
         params.append("--scanlines=1")
     return params
Exemplo n.º 15
0
 def get_params(self):
     params = []
     model = self.runner_config.get("model")
     fmemory = self.runner_config.get("fmemory")
     fdvolume = self.runner_config.get("fdvolume")
     fdspeed = self.runner_config.get("fdspeed")
     grafixcard = self.runner_config.get("grafixcard")
     grafixmemory = self.runner_config.get("grafixmemory")
     kickstart_file = self.runner_config.get("kickstart_file")
     if kickstart_file:
         params.append("--kickstart_file=%s" % kickstart_file)
     kickstart_ext_file = self.runner_config.get("kickstart_ext_file")
     if kickstart_ext_file:
         params.append("--kickstart_ext_file=%s" % kickstart_ext_file)
     if model:
         params.append("--amiga_model=%s" % model)
     if fmemory:
         params.append("--fast_memory=%s" % fmemory)
     if fdvolume:
         params.append("--floppy_drive_volume_empty=%s" % fdvolume)
     if fdspeed:
         params.append("--floppy_drive_volume_empty=%s" % fdspeed)
     if grafixcard:
         params.append("--graphics_card=%s" % grafixcard)
     if grafixmemory:
         params.append("--graphics_memory=%s" % grafixmemory)
     if self.runner_config.get("gfx_fullscreen_amiga"):
         width = int(DISPLAY_MANAGER.get_current_resolution()[0])
         params.append("--fullscreen")
         # params.append("--fullscreen_mode=fullscreen-window")
         params.append("--fullscreen_mode=fullscreen")
         params.append("--fullscreen_width=%d" % width)
     if self.runner_config.get("jitcompiler"):
         params.append("--jit_compiler=1")
     if self.runner_config.get("jitcompiler"):
         params.append("--bsdsocket_library=1")
     if self.runner_config.get("scanlines"):
         params.append("--scanlines=1")
     return params
Exemplo n.º 16
0
    def get_params(self):  # pylint: disable=too-many-branches
        params = []
        option_params = {
            "kickstart_file": "--kickstart_file=%s",
            "kickstart_ext_file": "--kickstart_ext_file=%s",
            "model": "--amiga_model=%s",
            "cpumodel": "--cpu=%s",
            "fmemory": "--fast_memory=%s",
            "ziiimem": "--zorro_iii_memory=%s",
            "fdvolume": "--floppy_drive_volume=%s",
            "fdspeed": "--floppy_drive_speed=%s",
            "grafixcard": "--graphics_card=%s",
            "grafixmemory": "--graphics_memory=%s",
        }
        for option, param in option_params.items():
            option_value = self.runner_config.get(option)
            if option_value:
                params.append(param % option_value)

        if self.runner_config.get("gfx_fullscreen_amiga"):
            width = int(DISPLAY_MANAGER.get_current_resolution()[0])
            params.append("--fullscreen")
            # params.append("--fullscreen_mode=fullscreen-window")
            params.append("--fullscreen_mode=fullscreen")
            params.append("--fullscreen_width=%d" % width)
        if self.runner_config.get("jitcompiler"):
            params.append("--jit_compiler=1")
        if self.runner_config.get("bsdsocket"):
            params.append("--bsdsocket_library=1")
        if self.runner_config.get("gamemode"):
            params.append("--game_mode=0")
        if self.runner_config.get("govwarning"):
            params.append("--governor_warning=0")
        if self.runner_config.get("scanlines"):
            params.append("--scanlines=1")
        return params
Exemplo n.º 17
0
    def __init__(self, installer, parent):
        self.error = None
        self.errors = []
        self.target_path = None
        self.parent = parent
        self.game_dir_created = False  # Whether a game folder was created during the install
        self.game_files = {}
        self.game_disc = None
        self.cancelled = False
        self.abort_current_task = None
        self.user_inputs = []
        self.steam_data = {}
        self.gog_data = {}
        self.script = installer.get("script")
        if not self.script:
            raise ScriptingError("This installer doesn't have a 'script' section")

        self.script_pretty = json.dumps(self.script, indent=4)

        self.install_start_time = None  # Time of the start of the install
        self.steam_poll = None  # Reference to the Steam poller that checks if games are downloaded
        self.current_command = None  # Current installer command when iterating through them
        self.current_file_id = None  # Current file when downloading / gathering files
        self.runners_to_install = []
        self.prev_states = []  # Previous states for the Steam installer

        self.version = installer["version"]
        self.slug = installer["slug"]
        self.year = installer.get("year")
        self.runner = installer["runner"]
        self.game_name = self.script.get("custom-name") or installer["name"]
        self.game_slug = installer["game_slug"]
        self.steamid = installer.get("steamid")
        self.gogid = installer.get("gogid")

        if not self.is_valid():
            raise ScriptingError(
                "Invalid script: \n{}".format("\n".join(self.errors)), self.script
            )

        self.files = [
            InstallerFile(self.game_slug, file_id, file_meta)
            for file_desc in self.script.get("files", [])
            for file_id, file_meta in file_desc.items()
        ]
        self.requires = self.script.get("requires")
        self.extends = self.script.get("extends")

        self.current_resolution = DISPLAY_MANAGER.get_current_resolution()
        self._check_binary_dependencies()
        self._check_dependency()
        if self.creates_game_folder:
            self.target_path = self.get_default_target()

        # If the game is in the library and uninstalled, the first installation
        # updates it
        existing_game = pga.get_game_by_field(self.game_slug, "slug")
        if existing_game and not existing_game["installed"]:
            self.game_id = existing_game["id"]
        else:
            self.game_id = None
Exemplo n.º 18
0
    def __init__(self, installer, parent):
        self.error = None
        self.errors = []
        self.target_path = None
        self.parent = parent
        self.game_dir_created = False  # Whether a game folder was created during the install
        self.game_files = {}
        self.game_disc = None
        self.cancelled = False
        self.abort_current_task = None
        self.user_inputs = []
        self.steam_data = {}
        self.gog_data = {}
        self.script = installer.get("script")
        if not self.script:
            raise ScriptingError(
                "This installer doesn't have a 'script' section")

        self.script_pretty = json.dumps(self.script, indent=4)

        self.install_start_time = None  # Time of the start of the install
        self.steam_poll = None  # Reference to the Steam poller that checks if games are downloaded
        self.current_command = None  # Current installer command when iterating through them
        self.current_file_id = None  # Current file when downloading / gathering files
        self.runners_to_install = []
        self.prev_states = []  # Previous states for the Steam installer

        self.version = installer["version"]
        self.slug = installer["slug"]
        self.year = installer.get("year")
        self.runner = installer["runner"]
        self.game_name = self.script.get("custom-name") or installer["name"]
        self.game_slug = installer["game_slug"]
        self.steamid = installer.get("steamid")
        self.gogid = installer.get("gogid")

        if not self.is_valid():
            raise ScriptingError(
                "Invalid script: \n{}".format("\n".join(self.errors)),
                self.script)

        self.files = [
            InstallerFile(self.game_slug, file_id, file_meta)
            for file_desc in self.script.get("files", [])
            for file_id, file_meta in file_desc.items()
        ]
        self.requires = self.script.get("requires")
        self.extends = self.script.get("extends")

        self.current_resolution = DISPLAY_MANAGER.get_current_resolution()
        self._check_binary_dependencies()
        self._check_dependency()
        if self.creates_game_folder:
            self.target_path = self.get_default_target()

        # If the game is in the library and uninstalled, the first installation
        # updates it
        existing_game = pga.get_game_by_field(self.game_slug, "slug")
        if existing_game and not existing_game["installed"]:
            self.game_id = existing_game["id"]
        else:
            self.game_id = None
Exemplo n.º 19
0
    def configure_game(self, prelaunched, error=None):
        """Get the game ready to start, applying all the options
        This methods sets the game_runtime_config attribute.
        """

        if error:
            logger.error(error)
            dialogs.ErrorDialog(str(error))
        if not prelaunched:
            logger.error("Game prelaunch unsuccessful")
            dialogs.ErrorDialog("An error prevented the game from running")
            self.state = self.STATE_STOPPED
            self.emit("game-stop")
            return
        system_config = self.runner.system_config
        self.original_outputs = DISPLAY_MANAGER.get_config()

        gameplay_info = self.runner.play()
        if "error" in gameplay_info:
            self.show_error_message(gameplay_info)
            self.state = self.STATE_STOPPED
            self.emit("game-stop")
            return
        logger.debug("Launching %s: %s", self.name, gameplay_info)
        logger.debug("Game info: %s", json.dumps(gameplay_info, indent=2))

        env = {}
        sdl_gamecontrollerconfig = system_config.get(
            "sdl_gamecontrollerconfig")
        if sdl_gamecontrollerconfig:
            path = os.path.expanduser(sdl_gamecontrollerconfig)
            if system.path_exists(path):
                with open(path, "r") as controllerdb_file:
                    sdl_gamecontrollerconfig = controllerdb_file.read()
            env["SDL_GAMECONTROLLERCONFIG"] = sdl_gamecontrollerconfig

        sdl_video_fullscreen = system_config.get("sdl_video_fullscreen") or ""
        env["SDL_VIDEO_FULLSCREEN_DISPLAY"] = sdl_video_fullscreen

        restrict_to_display = system_config.get("display")
        if restrict_to_display != "off":
            if restrict_to_display == "primary":
                restrict_to_display = None
                for output in self.original_outputs:
                    if output.primary:
                        restrict_to_display = output.name
                        break
                if not restrict_to_display:
                    logger.warning("No primary display set")
            else:
                found = False
                for output in self.original_outputs:
                    if output.name == restrict_to_display:
                        found = True
                        break
                if not found:
                    logger.warning("Selected display %s not found",
                                   restrict_to_display)
                    restrict_to_display = None
            if restrict_to_display:
                turn_off_except(restrict_to_display)
                time.sleep(3)
                self.resolution_changed = True

        resolution = system_config.get("resolution")
        if resolution != "off":
            DISPLAY_MANAGER.set_resolution(resolution)
            time.sleep(3)
            self.resolution_changed = True

        if system_config.get("reset_pulse"):
            audio.reset_pulse()

        self.killswitch = system_config.get("killswitch")
        if self.killswitch and not system.path_exists(self.killswitch):
            # Prevent setting a killswitch to a file that doesn't exists
            self.killswitch = None

        # Command
        launch_arguments = gameplay_info["command"]

        optimus = system_config.get("optimus")
        if optimus == "primusrun" and system.find_executable("primusrun"):
            launch_arguments.insert(0, "primusrun")
        elif optimus == "optirun" and system.find_executable("optirun"):
            launch_arguments.insert(0, "virtualgl")
            launch_arguments.insert(0, "-b")
            launch_arguments.insert(0, "optirun")
        elif optimus == "pvkrun" and system.find_executable("pvkrun"):
            launch_arguments.insert(0, "pvkrun")

        xephyr = system_config.get("xephyr") or "off"
        if xephyr != "off":
            if not system.find_executable("Xephyr"):
                raise GameConfigError(
                    "Unable to find Xephyr, install it or disable the Xephyr option"
                )

            xephyr_depth = "8" if xephyr == "8bpp" else "16"
            xephyr_resolution = system_config.get(
                "xephyr_resolution") or "640x480"
            xephyr_command = [
                "Xephyr",
                ":2",
                "-ac",
                "-screen",
                xephyr_resolution + "x" + xephyr_depth,
                "-glamor",
                "-reset",
                "-terminate",
            ]
            if system_config.get("xephyr_fullscreen"):
                xephyr_command.append("-fullscreen")

            xephyr_thread = MonitoredCommand(xephyr_command)
            xephyr_thread.start()
            time.sleep(3)
            env["DISPLAY"] = ":2"

        if system_config.get("use_us_layout"):
            setxkbmap_command = [
                "setxkbmap", "-model", "pc101", "us", "-print"
            ]
            xkbcomp_command = ["xkbcomp", "-", os.environ.get("DISPLAY", ":0")]
            xkbcomp = subprocess.Popen(xkbcomp_command, stdin=subprocess.PIPE)
            subprocess.Popen(setxkbmap_command,
                             env=os.environ,
                             stdout=xkbcomp.stdin).communicate()
            xkbcomp.communicate()

        if system_config.get("aco"):
            env["RADV_PERFTEST"] = "aco"

        pulse_latency = system_config.get("pulse_latency")
        if pulse_latency:
            env["PULSE_LATENCY_MSEC"] = "60"

        vk_icd = system_config.get("vk_icd")
        if vk_icd and vk_icd != "off" and system.path_exists(vk_icd):
            env["VK_ICD_FILENAMES"] = vk_icd

        fps_limit = system_config.get("fps_limit") or ""
        if fps_limit:
            strangle_cmd = system.find_executable("strangle")
            if strangle_cmd:
                launch_arguments = [strangle_cmd, fps_limit] + launch_arguments
            else:
                logger.warning(
                    "libstrangle is not available on this system, FPS limiter disabled"
                )

        prefix_command = system_config.get("prefix_command") or ""
        if prefix_command:
            launch_arguments = (
                shlex.split(os.path.expandvars(prefix_command)) +
                launch_arguments)

        single_cpu = system_config.get("single_cpu") or False
        if single_cpu:
            logger.info("The game will run on a single CPU core")
            launch_arguments.insert(0, "0")
            launch_arguments.insert(0, "-c")
            launch_arguments.insert(0, "taskset")

        terminal = system_config.get("terminal")
        if terminal:
            terminal = system_config.get("terminal_app",
                                         system.get_default_terminal())
            if terminal and not system.find_executable(terminal):
                dialogs.ErrorDialog("The selected terminal application "
                                    "could not be launched:\n"
                                    "%s" % terminal)
                self.state = self.STATE_STOPPED
                self.emit("game-stop")
                return

        # Env vars
        game_env = gameplay_info.get("env") or self.runner.get_env()
        env.update(game_env)
        env["game_name"] = self.name

        # Prime vars
        prime = system_config.get("prime")
        if prime:
            env["__NV_PRIME_RENDER_OFFLOAD"] = "1"
            env["__GLX_VENDOR_LIBRARY_NAME"] = "nvidia"
            env["__VK_LAYER_NV_optimus"] = "NVIDIA_only"

        # LD_PRELOAD
        ld_preload = gameplay_info.get("ld_preload")
        if ld_preload:
            env["LD_PRELOAD"] = ld_preload

        # Feral gamemode
        gamemode = system_config.get("gamemode")
        if gamemode:
            env["LD_PRELOAD"] = ":".join([
                path for path in [
                    env.get("LD_PRELOAD"),
                    "libgamemodeauto.so",
                ] if path
            ])

        # LD_LIBRARY_PATH
        game_ld_libary_path = gameplay_info.get("ld_library_path")
        if game_ld_libary_path:
            ld_library_path = env.get("LD_LIBRARY_PATH")
            if not ld_library_path:
                ld_library_path = "$LD_LIBRARY_PATH"
            env["LD_LIBRARY_PATH"] = ":".join(
                [game_ld_libary_path, ld_library_path])

        include_processes = shlex.split(
            system_config.get("include_processes", ""))
        exclude_processes = shlex.split(
            system_config.get("exclude_processes", ""))

        self.game_runtime_config = {
            "args": launch_arguments,
            "env": env,
            "terminal": terminal,
            "include_processes": include_processes,
            "exclude_processes": exclude_processes,
        }

        if system_config.get("disable_compositor"):
            self.set_desktop_compositing(False)

        prelaunch_command = system_config.get("prelaunch_command")
        if system.path_exists(prelaunch_command):
            self.prelaunch_executor = MonitoredCommand(
                [prelaunch_command],
                include_processes=[os.path.basename(prelaunch_command)],
                env=self.game_runtime_config["env"],
                cwd=self.directory,
            )
            self.prelaunch_executor.start()
            logger.info("Running %s in the background", prelaunch_command)
        if system_config.get("prelaunch_wait"):
            self.heartbeat = GLib.timeout_add(HEARTBEAT_DELAY,
                                              self.prelaunch_beat)
        else:
            self.start_game()
Exemplo n.º 20
0
    def configure_game(self, prelaunched, error=None):  # noqa: C901
        """Get the game ready to start, applying all the options
        This methods sets the game_runtime_config attribute.
        """
        if error:
            logger.error(error)
            dialogs.ErrorDialog(str(error))
        if not prelaunched:
            logger.error("Game prelaunch unsuccessful")
            dialogs.ErrorDialog(_("An error prevented the game from running"))
            self.state = self.STATE_STOPPED
            self.emit("game-stop")
            return
        gameplay_info = self.get_gameplay_info()
        if not gameplay_info:
            return
        command, env = get_launch_parameters(self.runner, gameplay_info)
        env["game_name"] = self.name  # What is this used for??
        self.game_runtime_config = {
            "args": command,
            "env": env,
            "terminal": self.get_terminal(),
            "include_processes": shlex.split(self.runner.system_config.get("include_processes", "")),
            "exclude_processes": shlex.split(self.runner.system_config.get("exclude_processes", "")),
        }

        # Audio control

        if self.runner.system_config.get("reset_pulse"):
            audio.reset_pulse()

        # Input control

        if self.runner.system_config.get("use_us_layout"):
            self.set_keyboard_layout("us")

        # Display control

        self.original_outputs = DISPLAY_MANAGER.get_config()

        if self.runner.system_config.get("disable_compositor"):
            self.set_desktop_compositing(False)

        if self.runner.system_config.get("disable_screen_saver"):
            self.screen_saver_inhibitor_cookie = SCREEN_SAVER_INHIBITOR.inhibit(self.name)

        if self.runner.system_config.get("display") != "off":
            self.resolution_changed = self.restrict_to_display(self.runner.system_config.get("display"))

        resolution = self.runner.system_config.get("resolution")
        if resolution != "off":
            DISPLAY_MANAGER.set_resolution(resolution)
            time.sleep(3)
            self.resolution_changed = True

        xephyr = self.runner.system_config.get("xephyr") or "off"
        if xephyr != "off":
            env["DISPLAY"] = self.start_xephyr()

        # Execution control

        self.killswitch = self.get_killswitch()

        if self.runner.system_config.get("prelaunch_command"):
            self.start_prelaunch_command()

        if self.runner.system_config.get("prelaunch_wait"):
            # Monitor the prelaunch command and wait until it has finished
            self.heartbeat = GLib.timeout_add(HEARTBEAT_DELAY, self.prelaunch_beat)
        else:
            self.start_game()