forked from apoguita/Py4GW
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPy4GW_Launcher.py
More file actions
1842 lines (1557 loc) · 75.1 KB
/
Copy pathPy4GW_Launcher.py
File metadata and controls
1842 lines (1557 loc) · 75.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from imgui_bundle import hello_imgui, imgui
import json
import tkinter as tk
from tkinter import filedialog
#region --- patcher ---
import ctypes
import ctypes.wintypes
from ctypes import wintypes
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
from typing import List, Optional
#region --- injector ---
import threading
import time
import win32gui
import win32process
import psutil
import sys
import configparser
import os
class IniHandler:
def __init__(self, filename: str):
"""
Initialize the handler with the given INI file.
"""
self.filename = filename
self.last_modified = 0
self.config = configparser.ConfigParser()
# ----------------------------
# Core Methods
# ----------------------------
def reload(self) -> configparser.ConfigParser:
"""Reload the INI file only if it has changed."""
current_mtime = os.path.getmtime(self.filename)
if current_mtime != self.last_modified:
self.last_modified = current_mtime
self.config.read(self.filename)
return self.config
def save(self, config: configparser.ConfigParser) -> None:
"""
Save changes to the INI file.
"""
with open(self.filename, 'w') as configfile:
config.write(configfile)
# ----------------------------
# Read Methods
# ----------------------------
def read_key(self, section: str, key: str, default_value: str = "") -> str:
"""
Read a string value from the INI file.
"""
config = self.reload()
try:
return config.get(section, key)
except (configparser.NoOptionError, configparser.NoSectionError):
return default_value
def read_int(self, section: str, key: str, default_value: int = 0) -> int:
"""
Read an integer value.
"""
config = self.reload()
try:
return config.getint(section, key)
except (ValueError, configparser.NoOptionError, configparser.NoSectionError):
return default_value
def read_float(self, section: str, key: str, default_value: float = 0.0) -> float:
"""
Read a float value.
"""
config = self.reload()
try:
return config.getfloat(section, key)
except (ValueError, configparser.NoOptionError, configparser.NoSectionError):
return default_value
def read_bool(self, section: str, key: str, default_value: bool = False) -> bool:
"""
Read a boolean value.
"""
config = self.reload()
try:
return config.getboolean(section, key)
except (ValueError, configparser.NoOptionError, configparser.NoSectionError):
return default_value
# ----------------------------
# Write Methods
# ----------------------------
def write_key(self, section: str, key: str, value: str) -> None:
"""
Write or update a key-value pair.
"""
config = self.reload()
if not config.has_section(section):
config.add_section(section)
config.set(section, key, str(value))
self.save(config)
# ----------------------------
# Delete Methods
# ----------------------------
def delete_key(self, section: str, key: str) -> None:
"""
Delete a specific key.
"""
config = self.reload()
if config.has_section(section) and config.has_option(section, key):
config.remove_option(section, key)
self.save(config)
def delete_section(self, section: str) -> None:
"""
Delete an entire section.
"""
config = self.reload()
if config.has_section(section):
config.remove_section(section)
self.save(config)
# ----------------------------
# Utility Methods
# ----------------------------
def list_sections(self) -> list:
"""
List all sections in the INI file.
"""
config = self.reload()
return config.sections()
def list_keys(self, section: str) -> dict:
"""
List all keys and values in a section.
"""
config = self.reload()
if config.has_section(section):
return dict(config.items(section))
return {}
def has_key(self, section: str, key: str) -> bool:
"""
Check if a key exists in a section.
"""
config = self.reload()
return config.has_section(section) and config.has_option(section, key)
def clone_section(self, source_section: str, target_section: str) -> None:
"""
Clone all keys from one section to another.
"""
config = self.reload()
if config.has_section(source_section):
if not config.has_section(target_section):
config.add_section(target_section)
for key, value in config.items(source_section):
config.set(target_section, key, value)
self.save(config)
current_directory = os.getcwd()
ini_file = "Py4GW.ini"
ini_handler = IniHandler(ini_file)
'''For Future Use'''
mods_directory = os.path.join(current_directory, "Addons", "mods")
os.makedirs(mods_directory, exist_ok=True) # Create Addons/Mods if it doesn't exist
config_file = ini_handler.read_key("settings","account_config_file","accounts.json")
py4gw_dll_name = ini_handler.read_key("settings","py4gw_dll_name","Py4GW.dll")
blackbox_dll_name = ini_handler.read_key("settings","blackbox_dll_name","GWBlackBOX.dll")
gmod_dll_name = ini_handler.read_key("settings", "gmod_dll_name", "gMod.dll")
log_history = []
log_history.append("Welcome To Py4GW!")
APP_VERSION = "1.0.0" # Update this with each release as needed
def check_and_handle_version_mismatch(ini_filename: str):
"""
Check if the stored application version matches the current version.
If there's a mismatch, clear the Hello ImGui settings file and update the stored version.
Args:
ini_filename: The path to the Hello ImGui settings file (e.g., Py4GW_Launcher.ini).
"""
global ini_handler, log_history
# Read the stored version from Py4GW.ini
stored_version = ini_handler.read_key("Py4GW_Launcher", "APP_VERSION", "0.0.0")
# Compare with the current version
if stored_version != APP_VERSION:
log_history.append(f"Version mismatch detected: Stored={stored_version}, Current={APP_VERSION}")
# Clear the Hello ImGui settings file to reset layout settings
if os.path.exists(ini_filename):
try:
os.remove(ini_filename)
log_history.append(f"Cleared Hello ImGui settings: {ini_filename}")
except Exception as e:
log_history.append(f"Error clearing Hello ImGui settings: {str(e)}")
else:
log_history.append(f"No Hello ImGui settings file found at {ini_filename}")
# Update the stored version in Py4GW.ini
ini_handler.write_key("Py4GW_Launcher", "APP_VERSION", APP_VERSION)
log_history.append(f"Updated stored version to {APP_VERSION}")
else:
log_history.append(f"Version check passed: {APP_VERSION}")
PROCESS_ALL_ACCESS = 0x1F0FFF
VIRTUAL_MEM = 0x1000 | 0x2000 # MEM_COMMIT | MEM_RESERVE
PAGE_READWRITE = 0x04
MEM_RELEASE = 0x8000
PROCESS_VM_OPERATION = 0x0008
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
PROCESS_QUERY_INFORMATION = 0x0400
MAX_PATH = 260
TH32CS_SNAPPROCESS = 0x00000002
# Constants
SWP_NOZORDER = 0x0004
SWP_NOACTIVATE = 0x0010
HWND_TOP = 0
WM_SETTEXT = 0x000C
# Load libraries
#user32 = ctypes.WinDLL('user32', use_last_error=True)
# Define WNDENUMPROC correctly
WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
# Function signatures for User32
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
user32.GetWindowThreadProcessId.restype = wintypes.DWORD
user32.EnumWindows.argtypes = [WNDENUMPROC, wintypes.LPARAM]
user32.EnumWindows.restype = wintypes.BOOL
user32.IsWindowVisible.argtypes = [wintypes.HWND]
user32.IsWindowVisible.restype = wintypes.BOOL
user32.SetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPCWSTR]
user32.SetWindowTextW.restype = wintypes.BOOL
class PROCESS_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [("Reserved1", ctypes.c_void_p),
("PebBaseAddress", ctypes.c_void_p),
("Reserved2", ctypes.c_void_p * 2),
("UniqueProcessId", ctypes.c_ulong),
("Reserved3", ctypes.c_void_p)]
class PEB(ctypes.Structure):
_fields_ = [("InheritedAddressSpace", ctypes.c_ubyte),
("ReadImageFileExecOptions", ctypes.c_ubyte),
("BeingDebugged", ctypes.c_ubyte),
("BitField", ctypes.c_ubyte),
("Mutant", ctypes.c_void_p),
("ImageBaseAddress", ctypes.c_void_p)]
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.c_ulong),
("cntUsage", ctypes.c_ulong),
("th32ProcessID", ctypes.c_ulong),
("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
("th32ModuleID", ctypes.c_ulong),
("cntThreads", ctypes.c_ulong),
("th32ParentProcessID", ctypes.c_ulong),
("pcPriClassBase", ctypes.c_long),
("dwFlags", ctypes.c_ulong),
("szExeFile", ctypes.c_char * MAX_PATH)]
CREATE_SUSPENDED = 0x00000004
class STARTUPINFO(ctypes.Structure):
_fields_ = [("cb", ctypes.c_ulong),
("lpReserved", ctypes.c_wchar_p),
("lpDesktop", ctypes.c_wchar_p),
("lpTitle", ctypes.c_wchar_p),
("dwX", ctypes.c_ulong),
("dwY", ctypes.c_ulong),
("dwXSize", ctypes.c_ulong),
("dwYSize", ctypes.c_ulong),
("dwXCountChars", ctypes.c_ulong),
("dwYCountChars", ctypes.c_ulong),
("dwFillAttribute", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("wShowWindow", ctypes.c_ushort),
("cbReserved2", ctypes.c_ushort),
("lpReserved2", ctypes.c_void_p),
("hStdInput", ctypes.c_void_p),
("hStdOutput", ctypes.c_void_p),
("hStdError", ctypes.c_void_p)]
class PROCESS_INFORMATION(ctypes.Structure):
_fields_ = [("hProcess", ctypes.c_void_p),
("hThread", ctypes.c_void_p),
("dwProcessId", ctypes.c_ulong),
("dwThreadId", ctypes.c_ulong)]
kernel32 = ctypes.windll.kernel32
ntdll = ctypes.windll.ntdll
class Account:
def __init__(self, character_name, email, password, gw_client_name, gw_path, extra_args, run_as_admin,
inject_py4gw, inject_blackbox, script_path="", enable_client_rename=False, use_character_name=False,
custom_client_name="", last_launch_time=None, total_runtime=0.0, current_session_time=0.0,
average_runtime=0.0, min_runtime=0.0, max_runtime=0.0, top_left=(0, 0), width=800, height=600,
preview_area=False, resize_client=False, inject_gmod=False, gmod_mods=None):
self.character_name = character_name
self.email = email
self.password = password
self.gw_client_name = gw_client_name
self.gw_path = gw_path
self.extra_args = extra_args
self.run_as_admin = run_as_admin
self.inject_py4gw = inject_py4gw
self.inject_blackbox = inject_blackbox
self.inject_gmod = inject_gmod # New: Flag for gMod injection
self.gmod_mods = gmod_mods if gmod_mods is not None else [] # New: List of mod file names
self.script_path = script_path # Path to the Python script
self.enable_client_rename = enable_client_rename # Whether client renaming is enabled
self.use_character_name = use_character_name # Whether to use the character name for renaming
self.custom_client_name = custom_client_name # Custom client name for renaming
self.last_launch_time = last_launch_time # Timestamp of the last launch
self.total_runtime = total_runtime # Total runtime in hours
self.current_session_time = current_session_time # Current session runtime in hours
self.average_runtime = average_runtime # Average runtime in hours
self.min_runtime = min_runtime # Minimum runtime recorded
self.max_runtime = max_runtime # Maximum runtime recorded
self.top_left = top_left # Top-left position of the window
self.width = width # Window width
self.height = height # Window height
self.preview_area = preview_area # Whether to preview the configured area
self.resize_client = resize_client # Whether to enable client resizing
def to_dict(self):
return {
"character_name": self.character_name,
"email": self.email,
"password": self.password,
"gw_client_name": self.gw_client_name,
"gw_path": self.gw_path,
"extra_args": self.extra_args,
"run_as_admin": self.run_as_admin,
"inject_py4gw": self.inject_py4gw,
"inject_blackbox": self.inject_blackbox,
"inject_gmod": self.inject_gmod,
"gmod_mods": self.gmod_mods,
"script_path": self.script_path,
"enable_client_rename": self.enable_client_rename,
"use_character_name": self.use_character_name,
"custom_client_name": self.custom_client_name,
"last_launch_time": self.last_launch_time,
"total_runtime": self.total_runtime,
"current_session_time": self.current_session_time,
"average_runtime": self.average_runtime,
"min_runtime": self.min_runtime,
"max_runtime": self.max_runtime,
"top_left": self.top_left,
"width": self.width,
"height": self.height,
"preview_area": self.preview_area,
"resize_client": self.resize_client,
}
@staticmethod
def from_dict(data):
return Account(
character_name=data["character_name"],
email=data["email"],
password=data["password"],
gw_client_name=data["gw_client_name"],
gw_path=data["gw_path"],
extra_args=data["extra_args"],
run_as_admin=data["run_as_admin"],
inject_py4gw=data["inject_py4gw"],
inject_blackbox=data["inject_blackbox"],
inject_gmod=data.get("inject_gmod", False),
gmod_mods=data.get("gmod_mods", []),
script_path=data.get("script_path", ""), # Default to an empty string if not present
enable_client_rename=data.get("enable_client_rename", False),
use_character_name=data.get("use_character_name", False),
custom_client_name=data.get("custom_client_name", ""),
last_launch_time=data.get("last_launch_time", None),
total_runtime=data.get("total_runtime", 0.0),
current_session_time=data.get("current_session_time", 0.0),
average_runtime=data.get("average_runtime", 0.0),
min_runtime=data.get("min_runtime", 0.0),
max_runtime=data.get("max_runtime", 0.0),
top_left=tuple(data.get("top_left", (0, 0))), # Convert to tuple if not present
width=data.get("width", 800),
height=data.get("height", 600),
preview_area=data.get("preview_area", False),
resize_client=data.get("resize_client", False),
)
class Team:
def __init__(self, name):
self.name = name
self.accounts = []
def add_account(self, account):
"""
Add an account to the team.
"""
self.accounts.append(account)
def to_dict(self):
"""
Convert the team and its accounts to a dictionary.
"""
return [account.to_dict() for account in self.accounts]
@staticmethod
def from_dict(name, accounts_data):
"""
Create a Team object from a dictionary.
"""
team = Team(name)
for account_data in accounts_data:
team.add_account(Account.from_dict(account_data))
return team
class TeamManager:
global log_history
def __init__(self):
self.teams = {}
def add_team(self, team):
"""
Add a team to the manager.
"""
self.teams[team.name] = team
def save_to_json(self, file_path):
"""
Save all teams and their accounts to a JSON file.
"""
data = {team_name: team.to_dict() for team_name, team in self.teams.items()}
with open(file_path, "w") as file:
json.dump(data, file, indent=4)
def load_from_json(self, file_path):
"""
Load teams and their accounts from a JSON file.
Create the file if it does not exist.
"""
try:
with open(file_path, "r") as file:
data = json.load(file)
self.teams = {team_name: Team.from_dict(team_name, accounts) for team_name, accounts in data.items()}
except FileNotFoundError:
# Create the file if it doesn't exist
with open(file_path, "w") as file:
json.dump({}, file)
log_history.append(f"File {file_path} not found. Created an empty file.")
self.teams = {}
except json.JSONDecodeError as e:
log_history.append(f"Error parsing JSON from {file_path}: {e}")
self.teams = {}
def get_team(self, team_name):
"""
Retrieve a team by name.
"""
return self.teams.get(team_name)
def get_first_team(self):
"""
Get the first team in the manager.
"""
if self.teams:
return next(iter(self.teams.values()))
def filter_accounts(self, team_name=None, character_name=None):
"""
Filter accounts by team and/or character name.
"""
results = []
for team in self.teams.values():
if team_name and team.name != team_name:
continue
for account in team.accounts:
if character_name and account.character_name != character_name:
continue
results.append(account)
return results
class Patcher:
global log_history
def __init__(self):
pass
def get_process_module_base(self, process_handle: int) -> Optional[int]:
pbi = PROCESS_BASIC_INFORMATION()
return_length = ctypes.c_ulong(0)
if ntdll.NtQueryInformationProcess(process_handle, 0, ctypes.byref(pbi), ctypes.sizeof(pbi), ctypes.byref(return_length)) != 0:
return None
peb_address = pbi.PebBaseAddress
buffer = ctypes.create_string_buffer(ctypes.sizeof(PEB))
bytes_read = ctypes.c_size_t()
if not kernel32.ReadProcessMemory(process_handle, peb_address, buffer, ctypes.sizeof(PEB), ctypes.byref(bytes_read)):
return None
peb = PEB.from_buffer(buffer)
return peb.ImageBaseAddress
def search_bytes(self, haystack: bytes, needle: bytes) -> int:
try:
return haystack.index(needle)
except ValueError:
return -1
def patch(self, pid: int) -> bool:
process_handle = kernel32.OpenProcess(
PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION,
False,
pid
)
if process_handle is None:
log_history.append(f"Patcher - Could not open process with PID {pid}: {ctypes.GetLastError()}")
return False
sig_patch = bytes([0x56, 0x57, 0x68, 0x00, 0x01, 0x00, 0x00, 0x89, 0x85, 0xF4, 0xFE, 0xFF, 0xFF, 0xC7, 0x00, 0x00, 0x00, 0x00, 0x00])
module_base = self.get_process_module_base(process_handle)
if module_base is None:
log_history.append("Patcher - Failed to get module base")
kernel32.CloseHandle(process_handle)
return False
gwdata = ctypes.create_string_buffer(0x48D000)
bytes_read = ctypes.c_size_t()
if not kernel32.ReadProcessMemory(process_handle, module_base, gwdata, 0x48D000, ctypes.byref(bytes_read)):
log_history.append(f"Patcher - Failed to read process memory: {ctypes.GetLastError()}")
kernel32.CloseHandle(process_handle)
return False
idx = self.search_bytes(gwdata.raw, sig_patch)
if idx == -1:
log_history.append("Patcher - Failed to find signature")
kernel32.CloseHandle(process_handle)
return False
mcpatch_address = module_base + idx - 0x1A
payload = bytes([0x31, 0xC0, 0x90, 0xC3])
bytes_written = ctypes.c_size_t()
if not kernel32.WriteProcessMemory(process_handle, mcpatch_address, payload, len(payload), ctypes.byref(bytes_written)):
log_history.append(f"Patcher - Failed to write process memory: {ctypes.GetLastError()}")
kernel32.CloseHandle(process_handle)
return False
log_history.append(f"Patcher - Patched at address: {hex(mcpatch_address)}")
kernel32.CloseHandle(process_handle)
return True
def get_hwnd_by_pid(self, pid: int) -> wintypes.HWND:
"""
Retrieve the HWND (window handle) associated with a given PID.
"""
hwnd = wintypes.HWND(0) # Default handle if not found
# Callback function for EnumWindows
def callback(handle, extra):
nonlocal hwnd
window_pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(handle, ctypes.byref(window_pid))
if window_pid.value == pid and user32.IsWindowVisible(handle):
hwnd = handle
return False # Stop enumeration
return True # Continue enumeration
# Enumerate all windows and find the one matching the PID
user32.EnumWindows(WNDENUMPROC(callback), 0)
return hwnd
def launch_and_patch(self, gw_exe_path: str, account: str, password: str, character: str, extra_args: str, elevated: bool) -> Optional[int]:
command_line = f'"{gw_exe_path}" -email "{account}" -password "{password}"'
if character:
command_line += f' -character "{character}"'
command_line += f" {extra_args}"
startup_info = STARTUPINFO()
startup_info.cb = ctypes.sizeof(startup_info)
process_info = PROCESS_INFORMATION()
success = kernel32.CreateProcessW(
None,
command_line,
None,
None,
False,
CREATE_SUSPENDED,
None,
None,
ctypes.byref(startup_info),
ctypes.byref(process_info)
)
if not success:
log_history.append(f"Patcher - Failed to create process: {ctypes.GetLastError()}")
return None
pid = process_info.dwProcessId
if self.patch(pid):
log_history.append("Patcher - Multiclient patch applied successfully.")
else:
log_history.append("Patcher - Failed to apply multiclient patch.")
kernel32.TerminateProcess(process_info.hProcess, 0)
kernel32.CloseHandle(process_info.hProcess)
kernel32.CloseHandle(process_info.hThread)
return None
if kernel32.ResumeThread(process_info.hThread) == -1:
log_history.append(f"Python - Failed to resume thread: {ctypes.GetLastError()}")
kernel32.TerminateProcess(process_info.hProcess, 0)
kernel32.CloseHandle(process_info.hProcess)
kernel32.CloseHandle(process_info.hThread)
return None
log_history.append("Patcher - Process resumed.")
kernel32.CloseHandle(process_info.hProcess)
kernel32.CloseHandle(process_info.hThread)
return pid
class GWLauncher:
global log_history, current_directory, py4gw_dll_name, blackbox_dll_name, ini_handler
def __init__(self):
self.active_pids = []
self.gmod_injection_delay = 0.5 # Delay before gMod injection (configurable)
def wait_for_gw_window(self, pid, timeout=30):
"""Wait for GW window to be created and fully loaded"""
log_history.append(f"Waiting for GW window (PID: {pid})")
start_time = time.time()
found_windows = []
def enum_windows_callback(hwnd, _):
if win32gui.IsWindowVisible(hwnd):
try:
_, window_pid = win32process.GetWindowThreadProcessId(hwnd)
if window_pid == pid:
title = win32gui.GetWindowText(hwnd)
log_history.append(f"Wait for GW Window - Found window with title: '{title}' for PID: {pid}")
# Accept any window from the process initially
found_windows.append(hwnd)
except Exception as e:
log_history.append(f"Wait for GW Window - Error in callback: {str(e)}")
return True
while time.time() - start_time < timeout:
try:
process = psutil.Process(pid)
if process.status() != psutil.STATUS_RUNNING:
log_history.append(f"Wait for GW Window - Process {pid} is not running")
return False
# Clear previous findings
found_windows.clear()
win32gui.EnumWindows(enum_windows_callback, None)
if found_windows:
log_history.append(f"Wait for GW Window - Found {len(found_windows)} windows for process {pid}")
# Return True if we found any window from the process
return True
except psutil.NoSuchProcess:
log_history.append(f"Wait for GW Window - Process {pid} no longer exists")
return False
except Exception as e:
log_history.append(f"Wait for GW Window - Error while waiting for GW window: {str(e)}")
return False
time.sleep(0.5)
# Add progress indicator every 5 seconds
elapsed = time.time() - start_time
if elapsed % 5 < 0.5:
log_history.append(f"Wait for GW Window - Still waiting... ({int(elapsed)}s)")
# List all windows for the process
try:
process = psutil.Process(pid)
log_history.append(f"Wait for GW Window - Process status: {process.status()}")
log_history.append(f"Wait for GW Window - Process command line: {process.cmdline()}")
except Exception as e:
log_history.append(f"Wait for GW Window - Error getting process info: {str(e)}")
log_history.append(f"Wait for GW Window - Timeout waiting for window of process {pid}")
return False
def inject_dll(self, pid, dll_path):
if not dll_path or not os.path.exists(dll_path):
log_history.append("Inject DLL - Invalid DLL path")
return False
log_history.append(f"Inject DLL - Starting DLL injection for PID: {pid}")
kernel32 = ctypes.windll.kernel32
process_handle = None
allocated_memory = None
thread_handle = None
try:
# Get process handle
process_handle = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if not process_handle:
log_history.append(f"Inject DLL - Failed to open process. Error: {ctypes.get_last_error()}")
return False
# Get LoadLibraryA address
loadlib_addr = kernel32.GetProcAddress(
kernel32._handle,
b"LoadLibraryA"
)
if not loadlib_addr:
log_history.append("Inject DLL - Failed to get LoadLibraryA address")
return False
# Prepare DLL path
dll_path_bytes = dll_path.encode('ascii') + b'\0'
path_size = len(dll_path_bytes)
# Allocate memory in target process
allocated_memory = kernel32.VirtualAllocEx(
process_handle,
0,
path_size,
VIRTUAL_MEM,
PAGE_READWRITE
)
if not allocated_memory:
log_history.append("Inject DLL - Failed to allocate memory")
return False
# Write DLL path to allocated memory
written = ctypes.c_size_t(0)
write_success = kernel32.WriteProcessMemory(
process_handle,
allocated_memory,
dll_path_bytes,
path_size,
ctypes.byref(written)
)
if not write_success or written.value != path_size:
log_history.append("Inject DLL - Failed to write to process memory")
return False
# Create remote thread
thread_handle = kernel32.CreateRemoteThread(
process_handle,
None,
0,
loadlib_addr,
allocated_memory,
0,
None
)
if not thread_handle:
log_history.append("Inject DLL - Failed to create remote thread")
return False
# Wait for thread completion
kernel32.WaitForSingleObject(thread_handle, 5000) # 5 second timeout
# Get thread exit code
exit_code = ctypes.c_ulong(0)
if kernel32.GetExitCodeThread(thread_handle, ctypes.byref(exit_code)):
log_history.append(f"Inject DLL - Injection completed with exit code: {exit_code.value}")
return exit_code.value != 0
return False
except Exception as e:
log_history.append(f"Inject DLL - DLL injection failed with error: {str(e)}")
return False
finally:
# Cleanup
if thread_handle:
kernel32.CloseHandle(thread_handle)
if allocated_memory and process_handle:
kernel32.VirtualFreeEx(process_handle, allocated_memory, 0, MEM_RELEASE)
if process_handle:
kernel32.CloseHandle(process_handle)
def inject_BlackBox(self, pid, dll_path):
"""Inject GWBlackBoxdll.dll into the process"""
if not os.path.exists(os.path.join(current_directory, "Addons", blackbox_dll_name)):
log_history.append("GWBlackBox DLL path not valid")
return False
log_history.append(f"Injecting BlackBox from: {os.path.join(current_directory, "Addons", blackbox_dll_name)}")
# Store original DLL path
original_dll_path = os.path.join(current_directory, "Addons", blackbox_dll_name)
try:
# Use existing inject_dll method
result = self.inject_dll(pid,original_dll_path)
log_history.append("GWBlackBox injection " + ("successful" if result else "failed"))
return result
finally:
pass
def inject_gmod(self, pid):
gmod_path = os.path.join(current_directory, "Addons", gmod_dll_name)
if not os.path.exists(gmod_path):
log_history.append("gMod DLL path not valid")
return False
log_history.append(f"Injecting gMod from: {gmod_path}")
result = self.inject_dll(pid, gmod_path)
log_history.append("gMod injection " + ("successful" if result else "failed"))
return result
def is_process_running(self, pid):
try:
process = psutil.Process(pid)
return process.status() == psutil.STATUS_RUNNING
except psutil.NoSuchProcess:
return False
def attempt_dll_injection(self, pid, delay=0, dll_type="Py4GW"):
if delay > 0:
log_history.append(f"Waiting {delay} seconds before injecting {dll_type} DLL...")
time.sleep(delay)
if not self.is_process_running(pid):
log_history.append(f"Process no longer running, skipping {dll_type} DLL injection")
return False
if dll_type == "Py4GW":
log_history.append("Attempting Py4GW DLL injection...")
dll_dir = os.path.join(current_directory, py4gw_dll_name)
return self.inject_dll(pid,dll_dir)
elif dll_type == "BlackBox":
log_history.append("Attempting BlackBox DLL injection...")
dll_dir = os.path.join(current_directory, "Addons", "GWBlackBOX.dll")
return self.inject_BlackBox(pid,dll_dir)
elif dll_type == "gMod":
log_history.append("Attempting gMod DLL injection...")
return self.inject_gmod(pid)
log_history.append(f"Skipping {dll_type} DLL injection (not enabled).")
return False
def start_injection_thread(self, pid, account: Account):
def injection_thread():
try:
if self.wait_for_gw_window(pid):
log_history.append("Injection - GW window found, waiting for initialization...")
time.sleep(5) # delay after window is found
if account.inject_blackbox:
if self.attempt_dll_injection(pid, delay=0, dll_type="BlackBox"):
log_history.append("GWBlackBOX.dll injection successful")
else:
log_history.append("GWBlackBOX.dll injection failed")
custom_dll_delay = 0
if account.inject_py4gw:
ini_handler.write_key("settings", "autoexec_script", account.script_path)
if self.attempt_dll_injection(pid, delay=custom_dll_delay, dll_type="Py4GW"):
log_history.append("Py4GW DLL injection successful")
else:
log_history.append("Py4GW DLL injection failed")
else:
log_history.append("Failed to detect GW window")
except Exception as e:
log_history.append(f"Error in injection thread: {str(e)}")
threading.Thread(target=injection_thread, daemon=True).start()
def create_modlist_for_gmod(self, account: Account):
if not account.gw_path:
log_history.append("Cannot create modlist.txt: gw_path not specified")
return
# Get the directory containing Gw.exe
gw_dir = os.path.dirname(account.gw_path)
modlist_path = os.path.join(gw_dir, "modlist.txt")
# Generate list of full paths to .tpf files
mod_paths = account.gmod_mods # Already full paths from select_mod_file()
# Write to modlist.txt (create an empty file if no mods)
try:
with open(modlist_path, "w") as f:
for mod_path in mod_paths:
f.write(f"{mod_path}\n")
log_history.append(f"Updated modlist.txt with {len(mod_paths)} mods at {modlist_path}")
except Exception as e:
log_history.append(f"Error updating modlist.txt at {modlist_path}: {str(e)}")
def start_team_launch_thread(self, team):
def team_launch_thread():
log_history.append(f"Launching team: {team.name}")
for account in team.accounts:
self.launch_gw(account)
# Dynamic idle message update
idle_time = 15 # Seconds
for remaining in range(idle_time, 0, -1):
log_history[-1] = f"Idling... {remaining}s remaining to prevent log-in throttle"
time.sleep(1) # Sleep 1 second and update countdown dynamically
log_history.append("Idle complete, continuing...")
log_history.append(f"Finished launching team: {team.name}")
# Start the thread for launching the team
threading.Thread(target=team_launch_thread, daemon=True).start()
def launch_gw(self, account: Account):
patcher = Patcher()
try:
pid = patcher.launch_and_patch(
account.gw_path,
account.email,
account.password,
account.character_name,
account.extra_args,
account.run_as_admin
)
if pid is None:
log_history.append("Launch GW - Failed to launch or patch Guild Wars.")
return
log_history.append(f"Launch GW - Launched and patched GW with PID: {pid}")
self.active_pids.append((account, pid))
# Create modlist.txt and inject gMod.dll
if account.inject_gmod:
self.create_modlist_for_gmod(account)
if self.attempt_dll_injection(pid, dll_type="gMod"):
log_history.append("gMod DLL injection successful")
time.sleep(3) # 3-second delay after gMod, this may need to be adjusted to longer delay.
else:
log_history.append("gMod DLL injection failed")
if account.inject_py4gw or account.inject_blackbox:
self.start_injection_thread(pid, account)
"""
if account.resize_client or account.enable_client_rename:
log_history.append(f"Launch GW - Waiting for window handle to be created.")
hwnd = None
retries = 10 # Maximum number of attempts
retry_interval = 0.5 # Seconds between retries
for attempt in range(retries):
hwnd = patcher.get_hwnd_by_pid(pid)
if hwnd:
break # Exit the loop if hwnd is found
time.sleep(retry_interval) # Wait before retrying
if not hwnd:
log_history.append("Launch GW - Failed to find Guild Wars window after retries.")
return
log_history.append(f"Launch GW - Found window handle: {hwnd}")
if hwnd and account.enable_client_rename:
# Set the new title
client_name = account.character_name if account.use_character_name else account.custom_client_name
log_history.append(f"Launch GW - renaming client to: {client_name}")