-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.js
More file actions
1885 lines (1593 loc) · 66.5 KB
/
main.js
File metadata and controls
1885 lines (1593 loc) · 66.5 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
const { app, BrowserWindow, ipcMain, dialog, net } = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const http = require('http');
const { extractFull } = require('node-7z');
const sevenBin = require('7zip-bin');
const ini = require('ini');
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
let mainWindow;
// Helper function to log to both main console AND renderer console
function logToRenderer(...args) {
const message = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
).join(' ');
console.log(...args); // Log to main process console
// Send to renderer console if window exists
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.log(${JSON.stringify(message)})`);
}
}
function logErrorToRenderer(...args) {
const message = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
).join(' ');
console.error(...args); // Log to main process console
// Send to renderer console if window exists
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.error(${JSON.stringify(message)})`);
}
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true
},
autoHideMenuBar: true,
resizable: false,
icon: path.join(__dirname, '4310811.png')
});
mainWindow.loadFile('index.html');
// Only open DevTools in development mode
if (process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Helper function to find Steam installation path
function findSteamPath() {
// Method 1: Check Windows Registry (most reliable)
const { execSync } = require('child_process');
// Try multiple registry keys (64-bit and 32-bit)
const registryKeys = [
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Valve\\Steam',
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Valve\\Steam',
'HKEY_CURRENT_USER\\SOFTWARE\\Valve\\Steam'
];
for (const regKey of registryKeys) {
try {
const regQuery = `reg query "${regKey}" /v InstallPath`;
const output = execSync(regQuery, { encoding: 'utf-8' });
const match = output.match(/InstallPath\s+REG_SZ\s+(.+)/);
if (match && match[1]) {
const steamPath = match[1].trim();
if (fs.existsSync(steamPath) && fs.existsSync(path.join(steamPath, 'steam.exe'))) {
console.log(`Found Steam via Registry (${regKey}): ${steamPath}`);
return steamPath;
}
}
} catch (error) {
// Continue to next registry key
continue;
}
}
console.log('Registry lookup failed for all keys, trying other methods...');
// Method 2: Check all drives (A-Z) for Steam installation
const drives = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const commonLocations = [
'Program Files (x86)\\Steam',
'Program Files\\Steam',
'Steam',
'Games\\Steam',
'SteamLibrary',
'Valve\\Steam',
'Steam Games\\Steam',
'Program Files (x86)\\Valve\\Steam',
'Program Files\\Valve\\Steam'
];
for (const drive of drives) {
for (const location of commonLocations) {
const steamPath = `${drive}:\\${location}`;
if (fs.existsSync(steamPath) && fs.existsSync(path.join(steamPath, 'steam.exe'))) {
console.log(`Found Steam on ${drive}: drive: ${steamPath}`);
return steamPath;
}
}
}
// Method 3: Fall back to environment variables (already covers C: drive)
const possiblePaths = [
path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Steam'),
path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Steam')
];
for (const steamPath of possiblePaths) {
if (fs.existsSync(steamPath)) {
console.log(`Found Steam via environment: ${steamPath}`);
return steamPath;
}
}
console.error('Steam installation not found on any drive!');
return null;
}
// Parse libraryfolders.vdf to find all Steam library paths
function getSteamLibraryPaths(steamPath) {
const libraryFoldersPath = path.join(steamPath, 'steamapps', 'libraryfolders.vdf');
const libraries = [steamPath];
if (!fs.existsSync(libraryFoldersPath)) {
return libraries;
}
try {
const content = fs.readFileSync(libraryFoldersPath, 'utf-8');
const pathRegex = /"path"\s+"(.+?)"/gi;
let match;
while ((match = pathRegex.exec(content)) !== null) {
const libraryPath = match[1].replace(/\\\\/g, '\\');
if (fs.existsSync(libraryPath)) {
libraries.push(libraryPath);
}
}
} catch (error) {
console.error('Error parsing libraryfolders.vdf:', error);
}
return [...new Set(libraries)]; // Remove duplicates
}
// Find game folder by AppID
function findGameByAppId(libraries, appId) {
for (const library of libraries) {
const steamappsPath = path.join(library, 'steamapps');
const manifestPath = path.join(steamappsPath, `appmanifest_${appId}.acf`);
if (fs.existsSync(manifestPath)) {
try {
const content = fs.readFileSync(manifestPath, 'utf-8');
const installDirMatch = content.match(/"installdir"\s+"(.+?)"/i);
if (installDirMatch) {
const installDir = installDirMatch[1];
const gamePath = path.join(steamappsPath, 'common', installDir);
if (fs.existsSync(gamePath)) {
return gamePath;
}
}
} catch (error) {
console.error('Error reading manifest:', error);
}
}
}
return null;
}
// ============================================================
// GAME EXE AUTO-DETECTION
// Search for "GAME EXE AUTO-DETECTION" to find this section
// ============================================================
// Find the main executable in game folder - returns full path to exe
function findGameExe(gameFolder) {
try {
const files = fs.readdirSync(gameFolder);
// Look for .exe files (excluding common utility files)
const exeFiles = files.filter(file =>
file.toLowerCase().endsWith('.exe') &&
!file.toLowerCase().includes('uninstall') &&
!file.toLowerCase().includes('crash') &&
!file.toLowerCase().includes('report') &&
!file.toLowerCase().includes('setup') &&
!file.toLowerCase().includes('config') &&
!file.toLowerCase().includes('launcher')
);
if (exeFiles.length === 0) {
// Search in subdirectories
for (const file of files) {
const fullPath = path.join(gameFolder, file);
if (fs.statSync(fullPath).isDirectory()) {
const subExe = findGameExe(fullPath);
if (subExe) return subExe; // Already returns full path
}
}
return null;
}
// Return full path to the first non-utility exe found
return path.join(gameFolder, exeFiles[0]);
} catch (error) {
console.error('Error finding exe:', error);
return null;
}
}
// ============================================================
// END GAME EXE AUTO-DETECTION
// ============================================================
// Download GlobalFix.zip from GitHub
async function downloadGlobalFix(destPath) {
return new Promise((resolve, reject) => {
const url = 'https://github.com/ShayneVi/Global-OnlineFix-Unsteam/raw/refs/heads/main/GlobalFix.zip';
const file = fs.createWriteStream(destPath);
https.get(url, (response) => {
if (response.statusCode === 302 || response.statusCode === 301) {
// Follow redirect
https.get(response.headers.location, (redirectResponse) => {
redirectResponse.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
}).on('error', (err) => {
fs.unlinkSync(destPath);
reject(err);
});
} else {
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
}
}).on('error', (err) => {
fs.unlinkSync(destPath);
reject(err);
});
});
}
// Extract zip to destination using 7-Zip (supports LZMA and other compression methods)
async function extractZip(zipPath, destPath) {
let pathTo7zip = sevenBin.path7za;
// When packaged, 7zip-bin is unpacked to app.asar.unpacked
// but sevenBin.path7za still points to app.asar, so we need to fix the path
if (app.isPackaged && pathTo7zip.includes('app.asar')) {
pathTo7zip = pathTo7zip.replace('app.asar', 'app.asar.unpacked');
}
const seven = extractFull(zipPath, destPath, {
$bin: pathTo7zip,
recursive: true
});
return new Promise((resolve, reject) => {
seven.on('end', () => {
resolve();
});
seven.on('error', (err) => {
reject(err);
});
});
}
// Unpack game executable using Steamless
async function steamlessUnpack(exePath) {
return new Promise((resolve, reject) => {
// Determine the correct resources path based on whether app is packaged
// When packaged: use process.resourcesPath/app.asar.unpacked
// When dev: use __dirname
const resourcesPath = app.isPackaged
? path.join(process.resourcesPath, 'app.asar.unpacked')
: __dirname;
const steamlessExe = path.join(resourcesPath, 'steamless', 'Steamless.CLI.exe');
console.log(`Looking for Steamless at: ${steamlessExe}`);
// Check if Steamless exists
if (!fs.existsSync(steamlessExe)) {
return reject(new Error(`Steamless.CLI.exe not found at: ${steamlessExe}\n\nPlease ensure the steamless folder is included in your installation.`));
}
const args = ['--quiet', '--recalcchecksum', exePath];
console.log(`Running Steamless on: ${exePath}`);
exec(`"${steamlessExe}" ${args.map(arg => `"${arg}"`).join(' ')}`, (error, stdout, stderr) => {
if (error) {
console.error('Steamless error:', stderr || error.message);
return reject(new Error(`Steamless unpacking failed: ${error.message}`));
}
const unpackedPath = exePath + '.unpacked.exe';
if (!fs.existsSync(unpackedPath)) {
return reject(new Error('Steamless did not create unpacked file. Game may not have SteamStub protection.'));
}
console.log('Steamless unpacking completed successfully');
resolve(unpackedPath);
});
});
}
// Modify unsteam.ini - preserve original format and comments
function modifyUnsteamIni(iniPath, exePath, dllPath, appId, steamId, username) {
try {
let content = fs.readFileSync(iniPath, 'utf-8');
// Replace exe_file in [loader] section (can be filename or full path)
content = content.replace(/^exe_file=.*$/m, `exe_file=${exePath}`);
// Replace dll_file in [loader] section (can be filename or full path)
content = content.replace(/^dll_file=.*$/m, `dll_file=${dllPath}`);
// Replace real_app_id in [game] section
content = content.replace(/^real_app_id=.*$/m, `real_app_id=${appId}`);
// Replace Steam ID if provided
if (steamId && steamId.trim() !== '') {
content = content.replace(/^steam_id=.*$/m, `steam_id=${steamId.trim()}`);
}
// Replace username if provided
if (username && username.trim() !== '') {
content = content.replace(/^player_name=.*$/m, `player_name=${username.trim()}`);
}
fs.writeFileSync(iniPath, content, 'utf-8');
return true;
} catch (error) {
console.error('Error modifying INI:', error);
return false;
}
}
// Remove Steam launch options by setting them to empty string
async function removeSteamLaunchOptions(appId) {
try {
const steamPath = findSteamPath();
if (!steamPath) {
throw new Error('Steam path not found');
}
const userDataPath = path.join(steamPath, 'userdata');
const users = fs.readdirSync(userDataPath);
let modifiedCount = 0;
const modifiedUsers = [];
// Loop through ALL users and clear launch options for each one that has this game
for (const user of users) {
const configPath = path.join(userDataPath, user, 'config', 'localconfig.vdf');
if (fs.existsSync(configPath)) {
let content = fs.readFileSync(configPath, 'utf-8');
// Check if app ID exists in this config
if (content.includes(`"${appId}"`)) {
// Check if LaunchOptions exists for this app
const launchOptionsPattern = new RegExp(
`"${appId}"\\s*\\n\\s*\\{[^}]*"LaunchOptions"\\s*"[^"]*"`,
's'
);
if (launchOptionsPattern.test(content)) {
// Clear the LaunchOptions value (set it to empty string)
// This mirrors how modifySteamLaunchOptions works but clears the value
content = content.replace(
new RegExp(`("${appId}"\\s*\\n\\s*\\{[^}]*"LaunchOptions"\\s*")([^"]*)(")`,'s'),
`$1$3` // Keeps the key and quotes but removes the value between them
);
fs.writeFileSync(configPath, content, 'utf-8');
modifiedCount++;
modifiedUsers.push(user);
console.log(`✓ Launch options cleared for AppID ${appId} in Steam user ${user}`);
}
}
}
}
// Log summary
if (modifiedCount > 0) {
if (modifiedCount === 1) {
console.log(`✓ Launch options successfully cleared for 1 Steam user`);
} else {
console.log(`✓ Launch options successfully cleared for ${modifiedCount} Steam users: ${modifiedUsers.join(', ')}`);
}
} else {
console.log(`No launch options found to clear for AppID ${appId}`);
}
return modifiedCount > 0;
} catch (error) {
console.error('Error removing launch options:', error);
return false;
}
}
// Save fix state to file for tracking what was installed
function saveFixState(gameFolder, state) {
try {
const statePath = path.join(gameFolder, '.globalfix-state.json');
const stateData = {
...state,
timestamp: new Date().toISOString()
};
fs.writeFileSync(statePath, JSON.stringify(stateData, null, 2), 'utf-8');
console.log('Fix state saved:', stateData);
return true;
} catch (error) {
console.error('Error saving fix state:', error);
return false;
}
}
// Load fix state from file
function loadFixState(gameFolder) {
try {
const statePath = path.join(gameFolder, '.globalfix-state.json');
if (!fs.existsSync(statePath)) {
return null;
}
const content = fs.readFileSync(statePath, 'utf-8');
const state = JSON.parse(content);
console.log('Fix state loaded:', state);
return state;
} catch (error) {
console.error('Error loading fix state:', error);
return null;
}
}
// Delete fix state file
function deleteFixState(gameFolder) {
try {
const statePath = path.join(gameFolder, '.globalfix-state.json');
if (fs.existsSync(statePath)) {
fs.unlinkSync(statePath);
console.log('Fix state deleted');
}
return true;
} catch (error) {
console.error('Error deleting fix state:', error);
return false;
}
}
// Modify Steam launch options
// Helper function to close Steam and wait for it to fully exit
async function closeSteamAndWait(steamPath) {
const { execSync } = require('child_process');
try {
// Check if Steam is running
const tasklistOutput = execSync('tasklist /FI "IMAGENAME eq steam.exe" /NH', { encoding: 'utf-8' });
if (!tasklistOutput.toLowerCase().includes('steam.exe')) {
return false; // Steam is not running
}
logToRenderer('🔄 Closing Steam to apply configuration changes...');
logToRenderer(' Steam must fully shut down and save its config before we can modify it.');
// Close Steam gracefully first
try {
execSync('taskkill /IM steam.exe', { encoding: 'utf-8' });
logToRenderer(' Sent graceful shutdown signal to Steam...');
} catch (e) {
// Ignore errors - Steam might already be closed
}
// Wait for Steam to fully close (check every 500ms, max 10 seconds)
let attempts = 0;
const maxAttempts = 20;
while (attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 500));
const checkOutput = execSync('tasklist /FI "IMAGENAME eq steam.exe" /NH', { encoding: 'utf-8' });
if (!checkOutput.toLowerCase().includes('steam.exe')) {
logToRenderer('✓ Steam process has exited');
break;
}
attempts++;
}
// If graceful shutdown didn't work, force kill Steam
if (attempts >= maxAttempts) {
logToRenderer('⚠️ Steam did not close gracefully, forcing shutdown...');
try {
execSync('taskkill /F /IM steam.exe', { encoding: 'utf-8' });
logToRenderer('✓ Forced Steam to close');
// Wait a bit more for force kill to complete
await new Promise(resolve => setTimeout(resolve, 2000));
// Verify Steam is actually closed
const verifyOutput = execSync('tasklist /FI "IMAGENAME eq steam.exe" /NH', { encoding: 'utf-8' });
if (verifyOutput.toLowerCase().includes('steam.exe')) {
logErrorToRenderer('✗ ERROR: Steam is still running even after force kill!');
throw new Error('Could not close Steam. Please close Steam manually and try again.');
}
} catch (killError) {
if (killError.message.includes('Could not close Steam')) {
throw killError;
}
// If taskkill failed, Steam might already be closed - verify
const finalCheck = execSync('tasklist /FI "IMAGENAME eq steam.exe" /NH', { encoding: 'utf-8' });
if (finalCheck.toLowerCase().includes('steam.exe')) {
logErrorToRenderer('✗ ERROR: Failed to close Steam');
throw new Error('Could not close Steam. Please close Steam manually and try again.');
}
}
}
// CRITICAL: Wait for Steam's config files to finish being written
// Steam writes localconfig.vdf as it shuts down, we need to wait for that to complete
logToRenderer('⏳ Waiting for Steam to finish writing config files...');
const userDataPath = path.join(steamPath, 'userdata');
if (fs.existsSync(userDataPath)) {
const users = fs.readdirSync(userDataPath);
const configFiles = [];
// Collect all localconfig.vdf files
for (const user of users) {
const configPath = path.join(userDataPath, user, 'config', 'localconfig.vdf');
if (fs.existsSync(configPath)) {
configFiles.push(configPath);
}
}
// Wait for all config files to stop being modified (stable for 2 seconds)
const stabilityWaitMs = 2000;
const maxConfigWaitMs = 10000;
const startTime = Date.now();
let allStable = false;
while (!allStable && (Date.now() - startTime) < maxConfigWaitMs) {
// Get current modification times
const mtimes = configFiles.map(f => {
try {
return fs.statSync(f).mtimeMs;
} catch (e) {
return 0;
}
});
// Wait
await new Promise(resolve => setTimeout(resolve, stabilityWaitMs));
// Check if any files were modified during the wait
allStable = true;
for (let i = 0; i < configFiles.length; i++) {
try {
const newMtime = fs.statSync(configFiles[i]).mtimeMs;
if (newMtime !== mtimes[i]) {
allStable = false;
logToRenderer(` Config file still being written (${users[i]})...`);
break;
}
} catch (e) {
// File might have been deleted or locked, skip
}
}
}
if (allStable) {
logToRenderer('✓ Config files are stable and ready for modification');
} else {
logToRenderer('⚠️ Config files may still be in use, proceeding anyway...');
}
}
// Extra safety wait
logToRenderer(' Adding 2-second safety buffer...');
await new Promise(resolve => setTimeout(resolve, 2000));
logToRenderer('✓ Steam fully shut down - safe to modify config');
return true; // We closed Steam
} catch (e) {
logErrorToRenderer('Error while closing Steam:', e.message);
return false;
}
}
// Helper function to restart Steam
async function restartSteam(steamPath) {
const { exec } = require('child_process');
try {
logToRenderer('\n🔄 Restarting Steam...');
// Find steam.exe path
const steamExePath = path.join(steamPath, 'steam.exe');
if (!fs.existsSync(steamExePath)) {
logErrorToRenderer('Steam.exe not found at:', steamExePath);
return false;
}
// Start Steam (using exec for non-blocking)
exec(`"${steamExePath}"`, (error) => {
if (error) {
logErrorToRenderer('Error starting Steam:', error.message);
}
});
// Give Steam a moment to start
await new Promise(resolve => setTimeout(resolve, 2000));
logToRenderer('✓ Steam restarted successfully');
return true;
} catch (e) {
logErrorToRenderer('Error restarting Steam:', e.message);
return false;
}
}
async function modifySteamLaunchOptions(appId, loaderPath) {
logToRenderer('\n╔══════════════════════════════════════════════════════════╗');
logToRenderer('║ INSIDE modifySteamLaunchOptions FUNCTION ║');
logToRenderer('╚══════════════════════════════════════════════════════════╝');
logToRenderer('Function called with:');
logToRenderer(' - AppID:', appId);
logToRenderer(' - Loader Path:', loaderPath);
try {
logToRenderer('\nStep 1: Finding Steam installation...');
const steamPath = findSteamPath();
logToRenderer('Steam Path found:', steamPath);
if (!steamPath) {
logErrorToRenderer('ERROR: Steam path is null/undefined!');
throw new Error('Steam installation not found. Please ensure Steam is installed. If Steam is installed in a custom location, the app may not be able to find it automatically.');
}
// Close Steam if it's running
logToRenderer('\n=== Step 2: Ensuring Steam is closed ===');
const steamWasClosed = await closeSteamAndWait(steamPath);
const needsSteamRestart = steamWasClosed;
if (steamWasClosed) {
logToRenderer('✓ Steam has been closed to prevent config overwrites\n');
} else {
logToRenderer('✓ Steam was not running\n');
}
const userDataPath = path.join(steamPath, 'userdata');
if (!fs.existsSync(userDataPath)) {
throw new Error('Steam userdata folder not found. Steam may not be configured properly.');
}
const users = fs.readdirSync(userDataPath);
if (users.length === 0) {
throw new Error('No Steam users found. Please ensure you have logged into Steam at least once.');
}
let modifiedCount = 0;
let foundAppId = false;
const modifiedUsers = [];
// Loop through ALL users and modify launch options for each one that has this game
for (const user of users) {
const configPath = path.join(userDataPath, user, 'config', 'localconfig.vdf');
logToRenderer(`\n=== Checking Steam user ${user} ===`);
logToRenderer(`Config path: ${configPath}`);
if (fs.existsSync(configPath)) {
logToRenderer(`✓ Config file exists`);
let content = fs.readFileSync(configPath, 'utf-8');
// Escape backslashes for the launch options path
const launchOptions = `\\"${loaderPath.replace(/\\/g, '\\\\')}\\" %command%`;
logToRenderer(`Launch options to set: ${launchOptions}`);
// Check if app ID exists in this config
logToRenderer(`Looking for AppID "${appId}" in config...`);
if (content.includes(`"${appId}"`)) {
logToRenderer(`✓ AppID "${appId}" found in config file`);
foundAppId = true;
// Extract the section around the AppID for debugging
const appIdIndex = content.indexOf(`"${appId}"`);
const sampleText = content.substring(Math.max(0, appIdIndex - 50), Math.min(content.length, appIdIndex + 200));
logToRenderer(`Context around AppID:\n${sampleText}\n`);
// Find the app section - look for the pattern: "appid"\n\t\t\t{
const appSectionRegex = new RegExp(`("${appId}"\\s*\\n\\s*\\{)`, 'g');
if (appSectionRegex.test(content)) {
logToRenderer(`✓ App section pattern matched`);
// Check if LaunchOptions already exists for this app
const launchOptionsPattern = new RegExp(
`"${appId}"\\s*\\n\\s*\\{[^}]*"LaunchOptions"\\s*"[^"]*"`,
's'
);
// Create a backup before modifying
const backupPath = configPath + '.backup';
fs.writeFileSync(backupPath, content, 'utf-8');
logToRenderer(`Created backup at: ${backupPath}`);
if (launchOptionsPattern.test(content)) {
logToRenderer(`Updating existing LaunchOptions...`);
// Update existing LaunchOptions
const replaceRegex = new RegExp(`("${appId}"\\s*\\n\\s*\\{[^}]*"LaunchOptions"\\s*")([^"]*)(")`,'s');
const oldContent = content;
content = content.replace(replaceRegex, `$1${launchOptions}$3`);
if (content !== oldContent) {
logToRenderer(`✓ Content was modified`);
} else {
logToRenderer(`⚠️ WARNING: Replace didn't change anything!`);
}
} else {
logToRenderer(`Adding new LaunchOptions entry...`);
// Add new LaunchOptions after the opening brace of the app section
const addRegex = new RegExp(`("${appId}"\\s*\\n\\s*\\{)`,'');
const oldContent = content;
content = content.replace(addRegex, `$1\n\t\t\t\t"LaunchOptions"\t\t"${launchOptions}"`);
if (content !== oldContent) {
logToRenderer(`✓ LaunchOptions entry added`);
} else {
logToRenderer(`⚠️ WARNING: Add didn't change anything!`);
}
}
fs.writeFileSync(configPath, content, 'utf-8');
logToRenderer(`✓ Config file written successfully`);
// Verify the write
const verifyContent = fs.readFileSync(configPath, 'utf-8');
if (verifyContent.includes(launchOptions)) {
logToRenderer(`✓ VERIFIED: Launch options are in the file`);
} else {
logToRenderer(`✗ ERROR: Launch options NOT found after writing!`);
}
modifiedCount++;
modifiedUsers.push(user);
logToRenderer(`✓ Launch options set for AppID ${appId} in Steam user ${user}`);
} else {
logToRenderer(`✗ App section regex did NOT match`);
logToRenderer(`Regex pattern: ("${appId}"\\s*\\n\\s*\\{)`);
}
} else {
logToRenderer(`✗ AppID "${appId}" NOT found in config file`);
}
} else {
logToRenderer(`✗ Config file does not exist`);
}
}
if (modifiedCount === 0) {
if (!foundAppId) {
throw new Error(`Game (AppID ${appId}) has not been launched in Steam yet. Please launch the game at least once, close it, then try applying the fix again. This creates the necessary Steam configuration entry.`);
} else {
throw new Error(`Could not modify launch options for AppID ${appId}. The game may need to be launched once to create its Steam configuration entry.`);
}
}
// Log summary
if (modifiedCount === 1) {
logToRenderer(`✓ Launch options successfully updated for 1 Steam user`);
} else {
logToRenderer(`✓ Launch options successfully updated for ${modifiedCount} Steam users: ${modifiedUsers.join(', ')}`);
}
if (needsSteamRestart) {
logToRenderer('\n⚠️ IMPORTANT: Please restart Steam for the changes to take effect!');
}
return { success: true, modifiedCount, modifiedUsers, needsSteamRestart };
} catch (error) {
logErrorToRenderer('Error modifying launch options:', error);
throw error; // Re-throw to preserve the error message
}
}
// Fetch Steam app list
let steamAppListCache = null;
ipcMain.handle('fetch-steam-apps', async () => {
// Return cached list if available
if (steamAppListCache) {
return { success: true, apps: steamAppListCache };
}
return new Promise((resolve) => {
const url = 'https://api.steampowered.com/ISteamApps/GetAppList/v2/';
https.get(url, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
try {
const parsed = JSON.parse(data);
if (parsed.applist && parsed.applist.apps) {
// Filter out entries with empty names and sort by name
const apps = parsed.applist.apps
.filter(app => app.name && app.name.trim() !== '')
.sort((a, b) => a.name.localeCompare(b.name));
steamAppListCache = apps;
resolve({ success: true, apps: apps });
} else {
resolve({ success: false, error: 'Invalid response format' });
}
} catch (error) {
resolve({ success: false, error: 'Failed to parse Steam app list' });
}
});
}).on('error', (error) => {
resolve({ success: false, error: error.message });
});
});
});
// Detect which Steam API DLL the game uses
function detectSteamApiDll(gameFolder) {
const api64Path = path.join(gameFolder, 'steam_api64.dll');
const api32Path = path.join(gameFolder, 'steam_api.dll');
// Check recursively in subdirectories too
function searchDir(dir, filename) {
if (!fs.existsSync(dir)) return null;
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
if (file.toLowerCase() === filename.toLowerCase()) {
return fullPath;
}
if (fs.statSync(fullPath).isDirectory()) {
const found = searchDir(fullPath, filename);
if (found) return found;
}
}
return null;
}
if (fs.existsSync(api64Path)) {
return { path: api64Path, is64bit: true };
}
if (fs.existsSync(api32Path)) {
return { path: api32Path, is64bit: false };
}
// Search in subdirectories
const found64 = searchDir(gameFolder, 'steam_api64.dll');
if (found64) return { path: found64, is64bit: true };
const found32 = searchDir(gameFolder, 'steam_api.dll');
if (found32) return { path: found32, is64bit: false };
return null;
}
// Fetch achievements from Steam Web API
async function fetchAchievements(appId, apiKey) {
return new Promise((resolve, reject) => {
const url = `http://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v0002/?key=${apiKey}&appid=${appId}&l=english&format=json`;
http.get(url, (response) => {
let data = '';
response.on('data', (chunk) => { data += chunk; });
response.on('end', () => {
try {
const parsed = JSON.parse(data);
if (parsed.game && parsed.game.availableGameStats) {
resolve(parsed.game.availableGameStats);
} else {
resolve({ achievements: [], stats: [] });
}
} catch (error) {
reject(error);
}
});
}).on('error', reject);
});
}
// Download achievement image
async function downloadImage(url, destPath) {
return new Promise((resolve, reject) => {
https.get(url, (response) => {
if (response.statusCode === 404) {
resolve(false); // Image not found, skip
return;
}
const file = fs.createWriteStream(destPath);
response.pipe(file);
file.on('finish', () => {
file.close();
resolve(true);
});
file.on('error', (err) => {
fs.unlinkSync(destPath);
reject(err);
});
}).on('error', reject);
});
}
// Create steam_settings folder structure
async function createSteamSettings(gameFolder, appId, goldbergOptions, achievementsData) {
const settingsFolder = path.join(gameFolder, 'steam_settings');
const imagesFolder = path.join(settingsFolder, 'achievement_images');
// Create directories
if (!fs.existsSync(settingsFolder)) {
fs.mkdirSync(settingsFolder, { recursive: true });
}
// Create steam_appid.txt
fs.writeFileSync(path.join(settingsFolder, 'steam_appid.txt'), appId.toString(), 'utf-8');
// Create configs.user.ini
const userIni = `[user::general]
# user account name
# default=gse orca
account_name=${goldbergOptions.accountName}
# your account ID in Steam64 format
# if the specified ID is invalid, the emu will ignore it and generate a proper one
# default=randomly generated by the emu only once and saved in the global settings
account_steamid=${goldbergOptions.steamId}
# the language reported to the app/game
# this must exist in 'supported_languages.txt', otherwise it will be ignored by the emu
# look for the column 'API language code' here: https://partner.steamgames.com/doc/store/localization/languages
# default=english
language=${goldbergOptions.language}
`;
fs.writeFileSync(path.join(settingsFolder, 'configs.user.ini'), userIni, 'utf-8');
// Create configs.main.ini
const mainIni = `[main::connectivity]
# 1=disable all steam networking interface functionality
# this won't prevent games/apps from making external requests
# networking related functionality like lobbies or those that launch a server in the background will not work
# default=0
disable_networking=0
# change the UDP/TCP port the emulator listens on, you should probably not change this because everyone needs to use the same port or you won't find yourselves on the network
# default=0