From e28d11a84ffa690de9093cfcd4805820750a1da6 Mon Sep 17 00:00:00 2001 From: farkadi Date: Wed, 15 Jan 2025 00:00:28 +0700 Subject: [PATCH] Update --- src/utils/game_launcher.py | 91 +++++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/src/utils/game_launcher.py b/src/utils/game_launcher.py index aa0424e..b1c3c57 100644 --- a/src/utils/game_launcher.py +++ b/src/utils/game_launcher.py @@ -1,5 +1,5 @@ import os -import subprocess +from subprocess import Popen, PIPE from pathlib import Path import logging import platform @@ -13,6 +13,13 @@ class GameLauncher: self.platform = platform.system().lower() self.account_username = None self.account_id = None + # Кэшируем пути к файлам + self.game_path = Path(settings.get('game', {}).get('path', '')) + self.config_path = self.game_path / 'WTF' / 'Config.wtf' + self.realmlist_paths = [ + self.game_path / 'Data' / 'ruRU' / 'realmlist.wtf', + self.game_path / 'Data' / 'realmlist.wtf' + ] def validate_game_path(self, path: str) -> bool: """Проверяет корректность пути к игре""" @@ -21,20 +28,17 @@ class GameLauncher: game_path = Path(path) - # На всех платформах ищем Wow.exe - exe_name = 'Wow.exe' - required_files = [ - exe_name, - 'Data/common.MPQ', - 'Data/common-2.MPQ' + game_path / 'Wow.exe', + game_path / 'Data/common.MPQ', + game_path / 'Data/common-2.MPQ' ] try: - for file in required_files: - file_path = game_path / file - if not file_path.exists(): - self.logger.error(f"Missing required file: {file}") + # Проверяем каждый файл + for required_file in required_files: + if not required_file.exists(): + self.logger.error(f"Missing required file: {required_file}") return False return True except Exception as e: @@ -44,12 +48,24 @@ class GameLauncher: def update_realmlist(self, path: str, realmlist: str) -> bool: """Обновляет файл realmlist.wtf""" try: - data_path = Path(path) / 'Data' / 'realmlist.wtf' - data_path.parent.mkdir(parents=True, exist_ok=True) + # Проверяем оба возможных пути + data_paths = [ + Path(path) / 'Data' / 'ruRU' / 'realmlist.wtf', # Путь для русской локализации + Path(path) / 'Data' / 'realmlist.wtf' # Стандартный путь + ] - with open(data_path, 'w', encoding='utf-8') as f: - f.write(f'set realmlist {realmlist}\n') - return True + # Обновляем существующие файлы или создаем новые + updated = False + for data_path in data_paths: + try: + data_path.parent.mkdir(parents=True, exist_ok=True) + with open(data_path, 'w', encoding='utf-8') as f: + f.write(f'set realmlist {realmlist}\n') + updated = True + except Exception as e: + self.logger.warning(f"Could not update {data_path}: {e}") + + return updated except Exception as e: self.logger.error(f"Error updating realmlist: {e}") return False @@ -57,6 +73,9 @@ class GameLauncher: def update_config_wtf(self, path: str) -> bool: """Обновляет файл Config.wtf для автологина""" try: + # Получаем realmlist из настроек + realmlist = self.settings.get('game', {}).get('realmlist', 'logon.server.com') + config_path = Path(path) / 'WTF' / 'Config.wtf' # Создаем директорию WTF если её нет @@ -73,7 +92,16 @@ class GameLauncher: # Обновляем настройки if self.account_username: - config['accountName'] = self.account_username + # Настройки для автологина + config['accountName'] = self.account_username.upper() # Имя должно быть в верхнем регистре + config['accountList'] = self.account_username.upper() # Список аккаунтов + config['lastAccountName'] = self.account_username.upper() # Последний использованный аккаунт + # Дополнительные настройки для списка аккаунтов + config['portal'] = self.account_username.upper() # Текущий аккаунт в портале + config['lastCharacterIndex'] = "0" # Индекс последнего персонажа + config['realmName'] = "WoW Server" # Имя реалма + config['savedAccountList'] = f"{self.account_username.upper()}|{realmlist}" # Сохраненный список + config['lastSelectedAccount'] = self.account_username.upper() # Последний выбранный аккаунт # Добавляем другие важные настройки если их нет defaults = { @@ -81,7 +109,13 @@ class GameLauncher: 'readTOS': '1', 'readEULA': '1', 'readTerminationWithoutNotice': '1', - 'accounttype': 'LK' + 'accounttype': 'LK', + 'lastSelectedRealm': '1', # Индекс последнего выбранного реалма + 'realmList': realmlist, # Адрес сервера + 'patchlist': f"'{realmlist}'", # Адрес сервера для патчей + 'accountListType': "1", # Тип списка аккаунтов + 'autoSelect': "1", # Автовыбор аккаунта + 'autoConnect': "1" # Автоподключение } for key, value in defaults.items(): @@ -131,13 +165,6 @@ class GameLauncher: # Формируем параметры запуска launch_options = self.settings.get('game', {}).get('launch_options', '').split() - # Добавляем параметры автологина если есть данные аккаунта - if self.account_username and self.account_id: - launch_options.extend([ - '-login', self.account_username, - '-accountid', str(self.account_id) - ]) - # Добавляем параметры графики graphics = self.settings.get('graphics', {}) if graphics.get('windowed', False): @@ -153,14 +180,14 @@ class GameLauncher: try: runner = self.settings.get('game', {}).get('runner', 'wine') - if runner == 'wine': + if runner == 'portproton': + cmd = ['portproton', exe_path] + launch_options + elif runner == 'wine': cmd = ['wine', exe_path] + launch_options elif runner == 'lutris': cmd = ['lutris', 'rungame', exe_path] + launch_options elif runner == 'proton': cmd = ['proton', 'run', exe_path] + launch_options - elif runner == 'portproton': - cmd = ['portproton', 'run', exe_path] + launch_options elif runner == 'crossover': cmd = ['crossover', exe_path] + launch_options else: @@ -171,16 +198,18 @@ class GameLauncher: if self.settings.get('game', {}).get('wineprefix'): env['WINEPREFIX'] = self.settings['game']['wineprefix'] env['WINEARCH'] = 'win32' + + # Запускаем процесс + Popen(cmd, env=env) - subprocess.Popen(cmd, env=env) except Exception as e: self.logger.error(f"Error launching with Wine: {e}") return False elif self.platform == 'darwin': - subprocess.Popen(['open', exe_path, '--args'] + launch_options) + Popen(['open', exe_path, '--args'] + launch_options) else: - subprocess.Popen([exe_path] + launch_options) + Popen([exe_path] + launch_options) return True