-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ps1
More file actions
1438 lines (1231 loc) · 55.9 KB
/
main.ps1
File metadata and controls
1438 lines (1231 loc) · 55.9 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
# Add necessary assemblies for Windows Forms
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Hide the PowerShell console window
function Hide-ConsoleWindow {
$consoleHandle = Get-ConsoleWindow
if ($consoleHandle -ne 0) {
# 0 = Hide window
ShowWindowAsync $consoleHandle 0
}
}
# Get console window handle
function Get-ConsoleWindow {
if (-not ([System.Management.Automation.PSTypeName]'Win32.NativeMethods').Type) {
Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
[DllImport("kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
"@
}
[Win32.NativeMethods]::GetConsoleWindow()
}
# Import ShowWindowAsync function
function ShowWindowAsync {
param (
[IntPtr]$hWnd,
[int]$nCmdShow
)
if (-not ([System.Management.Automation.PSTypeName]'Win32.NativeMethods2').Type) {
Add-Type -Namespace Win32 -Name NativeMethods2 -MemberDefinition @"
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@
}
[Win32.NativeMethods2]::ShowWindowAsync($hWnd, $nCmdShow) | Out-Null
}
# Hide the console window
Hide-ConsoleWindow
# Enable long path support (requires admin)
function Enable-LongPaths {
try {
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1 -Force -ErrorAction Stop
} catch {
# Silently continue - user may not have admin rights or it's already set
Write-Verbose "Could not enable long paths (may require admin): $_"
}
}
Enable-LongPaths
# Windows API Functions for File Operations
if (-not ([System.Management.Automation.PSTypeName]'WinAPI').Type) {
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class WinAPI {
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteFile(string path);
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);
}
"@
}
# Define the ModItem class
if (-not ([System.Management.Automation.PSTypeName]'ModItem').Type) {
Add-Type -TypeDefinition @"
using System;
public class ModItem {
public string Name { get; set; }
public bool IsInstalled { get; set; }
public override string ToString() {
return Name;
}
}
"@
}
# Helper Functions
function New-SymbolicLink {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Target
)
$escapedPath = [WildcardPattern]::Escape($Path)
New-Item -Path $escapedPath -ItemType SymbolicLink -Value $Target -Force | Out-Null
}
function New-DirectorySymlink {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Target
)
# Use cmd mklink /D - most reliable for directory symlinks
$output = cmd /c "mklink /D `"$Path`" `"$Target`"" 2>&1
if ($LASTEXITCODE -ne 0) {
throw "Failed to create directory symlink: $output"
}
}
function Remove-SymbolicLink {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$Path
)
if ((Test-Path -LiteralPath $Path) -and ((Get-Item -LiteralPath $Path).Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
$result = [WinAPI]::DeleteFile($Path)
if (-not $result) {
$errorMessage = [System.ComponentModel.Win32Exception]::new([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()).Message
throw "Failed to remove symbolic link: $errorMessage"
}
}
}
function Move-File-With-Metadata {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$SourcePath,
[Parameter(Mandatory = $true)][string]$DestinationPath
)
$result = [WinAPI]::MoveFile($SourcePath, $DestinationPath)
if (-not $result) {
$errorMessage = [System.ComponentModel.Win32Exception]::new([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()).Message
throw "Failed to move file: $errorMessage"
}
}
# Remove only the empty directories under the chosen target root
# that correspond to the mod's own folder layout.
function Remove-EmptyModDirectories {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)] [string] $ModSourcePath,
# This is the root the mod was installed to (either Core Game or Saved Games)
[Parameter(Mandatory=$true)] [string] $TargetRootPath
)
# Normalize paths with error handling
if (-not (Test-Path -LiteralPath $ModSourcePath)) {
Write-Warning "Mod source path not found: $ModSourcePath"
return
}
if (-not (Test-Path -LiteralPath $TargetRootPath)) {
Write-Warning "Target root path not found: $TargetRootPath"
return
}
$ModSourcePath = (Resolve-Path -LiteralPath $ModSourcePath).Path.TrimEnd('\','/')
$TargetRootPath = (Resolve-Path -LiteralPath $TargetRootPath).Path.TrimEnd('\','/')
# Gather all directories present in the mod (deepest-first)
$dirs = @(Get-ChildItem -LiteralPath $ModSourcePath -Recurse -Directory -Force |
Sort-Object FullName -Descending)
# First pass: delete leaf dirs that are already empty
foreach ($srcDir in $dirs) {
$relative = $srcDir.FullName.Substring($ModSourcePath.Length).TrimStart('\','/')
if ([string]::IsNullOrWhiteSpace($relative)) { continue } # never touch the TargetRoot itself
$targetDir = Join-Path -Path $TargetRootPath -ChildPath $relative
if (-not (Test-Path -LiteralPath $targetDir -PathType Container)) { continue }
$hasEntries = $true
try {
$hasEntries = [System.IO.Directory]::EnumerateFileSystemEntries($targetDir).GetEnumerator().MoveNext()
} catch {
$hasEntries = $true # play safe if we cannot enumerate
}
if (-not $hasEntries) {
try { Remove-Item -LiteralPath $targetDir -Force -ErrorAction Stop } catch {}
}
}
# Second pass (still deepest-first): parents may now be empty after leaf deletion
foreach ($srcDir in ($dirs | Sort-Object FullName -Descending)) {
$relative = $srcDir.FullName.Substring($ModSourcePath.Length).TrimStart('\','/')
if ([string]::IsNullOrWhiteSpace($relative)) { continue }
$targetDir = Join-Path -Path $TargetRootPath -ChildPath $relative
if (-not (Test-Path -LiteralPath $targetDir -PathType Container)) { continue }
$hasEntries = $true
try {
$hasEntries = [System.IO.Directory]::EnumerateFileSystemEntries($targetDir).GetEnumerator().MoveNext()
} catch {
$hasEntries = $true
}
if (-not $hasEntries) {
try { Remove-Item -LiteralPath $targetDir -Force -ErrorAction Stop } catch {}
}
}
}
# Function to read the configuration file
function Read-Config {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$ConfigFilePath
)
$config = @{}
if (Test-Path -LiteralPath $ConfigFilePath) {
Get-Content -LiteralPath $ConfigFilePath | ForEach-Object {
$_ = $_.Trim()
if ($_.Length -gt 0 -and -not $_.StartsWith('#')) {
$parts = $_ -split '='
if ($parts.Length -eq 2) {
$key = $parts[0].Trim()
$value = $parts[1].Trim()
$value = $value -replace "%USERPROFILE%", $env:USERPROFILE
$config[$key] = $value
}
}
}
} else {
Show-CustomMessageBox -Text "Config file not found: $ConfigFilePath"
}
return $config
}
# Function to check if a mod is installed
function Is-Mod-Installed {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$ModPath,
[Parameter(Mandatory = $true)][string]$GameDirectory
)
# Get a sample file from the mod
$sampleFile = Get-ChildItem -LiteralPath $ModPath -Recurse -File -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $sampleFile) {
return $false
}
$relativePath = $sampleFile.FullName.Substring($ModPath.Length).TrimStart('\', '/')
$expectedPath = Join-Path -Path $GameDirectory -ChildPath $relativePath
# Check if the expected file path exists
if (-not (Test-Path -LiteralPath $expectedPath)) {
return $false
}
# Method 1: Check if the file itself is a symlink (file symlink case)
$fileItem = Get-Item -LiteralPath $expectedPath -Force
if ($fileItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
$targetPath = $fileItem.Target
if ($targetPath -and $targetPath.StartsWith($ModPath, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
# Method 2: Check if any parent directory is a symlink pointing to our mod (directory symlink case)
$currentPath = $expectedPath
while ($currentPath -and $currentPath.Length -gt $GameDirectory.Length) {
$parentPath = Split-Path -Path $currentPath -Parent
if (-not $parentPath -or $parentPath.Length -lt $GameDirectory.Length) {
break
}
$parentItem = Get-Item -LiteralPath $parentPath -Force -ErrorAction SilentlyContinue
if ($parentItem -and ($parentItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
$parentTarget = $parentItem.Target
if ($parentTarget) {
# Check if this symlinked directory is part of our mod
if ($parentTarget.StartsWith($ModPath, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
# Also check if our mod path starts with the target (for deeper nesting)
if ($ModPath.StartsWith($parentTarget, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
}
$currentPath = $parentPath
}
return $false
}
# Function to remove leftover symbolic links directly
function Remove-Links-Directly {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$GameDirectory,
[Parameter(Mandatory = $true)][string]$ModSourcePath
)
try {
if (-not (Test-Path -LiteralPath $GameDirectory)) {
Write-Warning "Game directory not found: $GameDirectory"
return
}
# Find all symlinks (files and directories)
$symlinks = Get-ChildItem -Recurse -Force -LiteralPath $GameDirectory -ErrorAction SilentlyContinue |
Where-Object { $_.Attributes -band [System.IO.FileAttributes]::ReparsePoint }
foreach ($symlink in $symlinks) {
try {
$target = $symlink.Target
# Check if this symlink points to somewhere within our mod source
if ($target -and $target.StartsWith($ModSourcePath, [System.StringComparison]::OrdinalIgnoreCase)) {
if ($symlink.PSIsContainer) {
# Directory symlink - remove with rmdir (doesn't delete target contents)
cmd /c "rmdir `"$($symlink.FullName)`"" 2>&1 | Out-Null
} else {
# File symlink
Remove-SymbolicLink -Path $symlink.FullName
}
}
} catch {
Write-Verbose "Could not remove symlink: $($symlink.FullName) - $_"
}
}
} catch {
Write-Warning "Error in Remove-Links-Directly: $_"
}
}
# Function to install a mod
function Install-Mod {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$ModName,
[Parameter(Mandatory = $true)][string]$ModSourcePath,
[Parameter(Mandatory = $true)][string]$GameDirectory,
[Parameter(Mandatory = $true)][string]$BackupDirectory,
[Parameter()][System.Windows.Forms.ProgressBar]$ProgressBar
)
$backupDir = Join-Path -Path $BackupDirectory -ChildPath ("Backup-" + $ModName)
# Count total files for progress bar
$allFiles = @(Get-ChildItem -LiteralPath $ModSourcePath -Recurse -File -Force)
$totalFiles = $allFiles.Count
$script:installFilesProcessed = 0
if ($ProgressBar) {
$ProgressBar.Minimum = 0
$ProgressBar.Maximum = [Math]::Max($totalFiles, 1)
$ProgressBar.Value = 0
}
# Recursive installation
Install-ModDirectory -SourceDir $ModSourcePath -DestDir $GameDirectory -BackupDir $backupDir -ProgressBar $ProgressBar
if ($ProgressBar) {
$ProgressBar.Value = 0
}
}
function Install-ModDirectory {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$SourceDir,
[Parameter(Mandatory = $true)][string]$DestDir,
[Parameter(Mandatory = $true)][string]$BackupDir,
[Parameter()][System.Windows.Forms.ProgressBar]$ProgressBar
)
$children = Get-ChildItem -LiteralPath $SourceDir -Force
foreach ($child in $children) {
$destPath = Join-Path -Path $DestDir -ChildPath $child.Name
$backupPath = Join-Path -Path $BackupDir -ChildPath $child.Name
if ($child.PSIsContainer) {
# It's a directory
if (-not (Test-Path -LiteralPath $destPath)) {
# Destination doesn't exist - symlink entire directory
# Ensure parent exists
$parentDir = Split-Path -Path $destPath -Parent
if (-not (Test-Path -LiteralPath $parentDir)) {
[System.IO.Directory]::CreateDirectory($parentDir) | Out-Null
}
New-DirectorySymlink -Path $destPath -Target $child.FullName
# Update progress for all files in this directory
$filesInDir = @(Get-ChildItem -LiteralPath $child.FullName -Recurse -File -Force).Count
$script:installFilesProcessed += $filesInDir
if ($ProgressBar) {
$ProgressBar.Value = [Math]::Min($script:installFilesProcessed, $ProgressBar.Maximum)
$ProgressBar.Refresh()
}
} else {
# Destination exists - recurse
Install-ModDirectory -SourceDir $child.FullName -DestDir $destPath -BackupDir $backupPath -ProgressBar $ProgressBar
}
} else {
# It's a file
if (Test-Path -LiteralPath $destPath) {
# Check if it's already a symlink pointing to our source
$existingItem = Get-Item -LiteralPath $destPath -Force
if ($existingItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
# Remove existing symlink
Remove-SymbolicLink -Path $destPath
} else {
# Backup existing real file
$backupFileDir = Split-Path -Path $backupPath -Parent
if (-not (Test-Path -LiteralPath $backupFileDir)) {
[System.IO.Directory]::CreateDirectory($backupFileDir) | Out-Null
}
Move-File-With-Metadata -SourcePath $destPath -DestinationPath $backupPath
}
}
# Ensure target directory exists
$targetDir = Split-Path -Path $destPath -Parent
if (-not (Test-Path -LiteralPath $targetDir)) {
[System.IO.Directory]::CreateDirectory($targetDir) | Out-Null
}
# Create file symlink
New-SymbolicLink -Path $destPath -Target $child.FullName
$script:installFilesProcessed++
if ($ProgressBar) {
$ProgressBar.Value = [Math]::Min($script:installFilesProcessed, $ProgressBar.Maximum)
$ProgressBar.Refresh()
}
}
}
}
# Function to uninstall a mod
function Uninstall-Mod {
[CmdletBinding()]
param (
[string]$ModName,
[string]$ModSourcePath,
[string]$GameDirectory, # <- pass in the correct root (Core OR Saved) when calling
[string]$BackupDirectory,
[System.Windows.Forms.ProgressBar]$ProgressBar,
[ref]$FilesProcessed
)
$backupDir = Join-Path -Path $BackupDirectory -ChildPath ("Backup-" + $ModName)
# Restore backup files
if (Test-Path -LiteralPath $backupDir) {
$files = Get-ChildItem -LiteralPath $backupDir -Recurse -File
$totalFiles = $files.Count
foreach ($file in $files) {
$relativePath = $file.FullName.Substring($backupDir.Length).TrimStart('\', '/')
$targetFilePath = Join-Path -Path $GameDirectory -ChildPath $relativePath
# If a symlink is still there, remove it first
Remove-SymbolicLink -Path $targetFilePath
# Ensure target directory exists
$targetDir = Split-Path -Path $targetFilePath -Parent
if (-not (Test-Path -LiteralPath $targetDir)) {
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
}
# Move backup file back to original location (preserves metadata via WinAPI)
Move-File-With-Metadata -SourcePath $file.FullName -DestinationPath $targetFilePath
# Progress
$FilesProcessed.Value++
if ($ProgressBar) {
$ProgressBar.Value = [Math]::Min($FilesProcessed.Value, $ProgressBar.Maximum)
$ProgressBar.Refresh()
}
}
# Remove backup directory when done
Remove-Item -LiteralPath $backupDir -Recurse -Force
}
# Remove any remaining symbolic links for this mod within the chosen root
Remove-Links-Directly -GameDirectory $GameDirectory -ModSourcePath $ModSourcePath
# Clean up only empty directories that correspond to the mod's own folder layout
# This targets whichever root was used for this mod (Core Game OR Saved Games),
# because $GameDirectory is passed in as that root by the caller.
Remove-EmptyModDirectories -ModSourcePath $ModSourcePath -TargetRootPath $GameDirectory
}
# Function to find mod conflicts at the mod level
function Find-Mod-Conflicts {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][array]$Mods
)
$fileMappings = @{}
$modConflicts = @{}
foreach ($mod in $Mods) {
$modName = $mod.Name
$files = Get-ChildItem -LiteralPath $mod.FullName -Recurse -File
foreach ($file in $files) {
$relativePath = $file.FullName.Substring($mod.FullName.Length).TrimStart('\', '/').ToLower()
if ($fileMappings.ContainsKey($relativePath)) {
$existingModName = $fileMappings[$relativePath]
if ($existingModName -ne $modName) {
if (-not $modConflicts.ContainsKey($modName)) {
$modConflicts[$modName] = @()
}
if (-not $modConflicts[$modName].Contains($existingModName)) {
$modConflicts[$modName] += $existingModName
}
if (-not $modConflicts.ContainsKey($existingModName)) {
$modConflicts[$existingModName] = @()
}
if (-not $modConflicts[$existingModName].Contains($modName)) {
$modConflicts[$existingModName] += $modName
}
}
} else {
$fileMappings[$relativePath] = $modName
}
}
}
return $modConflicts
}
# Function to get a list of installed mods
function Get-Installed-Mods {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$GameDirectory,
[Parameter(Mandatory = $true)][string]$ModParentPath
)
$installedMods = @()
if (-not (Test-Path -LiteralPath $ModParentPath)) {
Write-Warning "Mod parent path not found: $ModParentPath"
return $installedMods
}
$modDirs = Get-ChildItem -LiteralPath $ModParentPath -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -notmatch '^Backup' }
foreach ($modDir in $modDirs) {
$modPath = $modDir.FullName
$modName = $modDir.Name
if (Is-Mod-Installed -ModPath $modPath -GameDirectory $GameDirectory) {
$installedMods += $modName
}
}
return $installedMods
}
# Function to find conflicts between a mod to install and installed mods
function Find-Mod-Conflicts-With-Installed {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$ModToInstall,
[Parameter(Mandatory = $true)]
[AllowEmptyCollection()]
[array]$InstalledMods,
[Parameter(Mandatory = $true)]
[string]$ModParentPath
)
$modToInstallName = Split-Path -Path $ModToInstall -Leaf
$modToInstallFiles = Get-ChildItem -LiteralPath $ModToInstall -Recurse -File | ForEach-Object {
$_.FullName.Substring($ModToInstall.Length).TrimStart('\', '/').ToLower()
}
$conflictingMods = @()
foreach ($installedModName in $InstalledMods) {
if ($installedModName -eq $modToInstallName) {
continue
}
$installedModPath = Join-Path -Path $ModParentPath -ChildPath $installedModName
$installedModFiles = Get-ChildItem -LiteralPath $installedModPath -Recurse -File | ForEach-Object {
$_.FullName.Substring($installedModPath.Length).TrimStart('\', '/').ToLower()
}
$conflicts = $modToInstallFiles | Where-Object { $installedModFiles -contains $_ }
if ($conflicts.Count -gt 0) {
$conflictingMods += $installedModName
}
}
return $conflictingMods | Select-Object -Unique
}
# Function to show a custom message box with dark theme
function Show-CustomMessageBox {
param (
[string]$Text,
[string]$Title = "Message",
[string]$Buttons = "OKCancel"
)
$form = New-Object System.Windows.Forms.Form
$form.Text = $Title
$form.Size = New-Object System.Drawing.Size(400, 200)
$form.StartPosition = "CenterParent"
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.BackColor = [System.Drawing.Color]::FromArgb(30, 30, 30)
$form.ForeColor = [System.Drawing.Color]::White
$form.ShowInTaskbar = $false
# Label
$label = New-Object System.Windows.Forms.Label
$label.Text = $Text
$label.Size = New-Object System.Drawing.Size(360, 80)
$label.Location = New-Object System.Drawing.Point(20, 20)
$label.BackColor = $form.BackColor
$label.ForeColor = $form.ForeColor
$label.AutoSize = $false
$label.TextAlign = 'MiddleCenter'
$form.Controls.Add($label)
# Buttons
switch ($Buttons) {
"OK" {
$buttonOK = New-Object System.Windows.Forms.Button
$buttonOK.Text = "OK"
$buttonOK.DialogResult = [System.Windows.Forms.DialogResult]::OK
$buttonOK.Location = New-Object System.Drawing.Point(160, 120)
$buttonOK.Size = New-Object System.Drawing.Size(75, 30)
$buttonOK.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonOK.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($buttonOK)
$form.AcceptButton = $buttonOK
}
"YesNo" {
$buttonYes = New-Object System.Windows.Forms.Button
$buttonYes.Text = "Yes"
$buttonYes.DialogResult = [System.Windows.Forms.DialogResult]::Yes
$buttonYes.Location = New-Object System.Drawing.Point(110, 120)
$buttonYes.Size = New-Object System.Drawing.Size(75, 30)
$buttonYes.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonYes.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($buttonYes)
$buttonNo = New-Object System.Windows.Forms.Button
$buttonNo.Text = "No"
$buttonNo.DialogResult = [System.Windows.Forms.DialogResult]::No
$buttonNo.Location = New-Object System.Drawing.Point(210, 120)
$buttonNo.Size = New-Object System.Drawing.Size(75, 30)
$buttonNo.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonNo.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($buttonNo)
$form.AcceptButton = $buttonYes
$form.CancelButton = $buttonNo
}
default {
# OKCancel
$buttonOK = New-Object System.Windows.Forms.Button
$buttonOK.Text = "OK"
$buttonOK.DialogResult = [System.Windows.Forms.DialogResult]::OK
$buttonOK.Location = New-Object System.Drawing.Point(110, 120)
$buttonOK.Size = New-Object System.Drawing.Size(75, 30)
$buttonOK.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonOK.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($buttonOK)
$buttonCancel = New-Object System.Windows.Forms.Button
$buttonCancel.Text = "Cancel"
$buttonCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$buttonCancel.Location = New-Object System.Drawing.Point(210, 120)
$buttonCancel.Size = New-Object System.Drawing.Size(75, 30)
$buttonCancel.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonCancel.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($buttonCancel)
$form.AcceptButton = $buttonOK
$form.CancelButton = $buttonCancel
}
}
return $form.ShowDialog()
}
# Function to get the script directory
function Get-ScriptDirectory {
if ($MyInvocation.PSCommandPath) {
$scriptDir = Split-Path -Parent $MyInvocation.PSCommandPath
} elseif ($PSScriptRoot) {
$scriptDir = $PSScriptRoot
} else {
$scriptDir = Get-Location
}
return $scriptDir
}
function Initialize-GUI {
# Add required assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Create the form
$form = New-Object System.Windows.Forms.Form
$form.Text = "SymLink Advanced Modding for DCS"
$form.Size = New-Object System.Drawing.Size(800, 850) # Increased form height
$form.StartPosition = "CenterScreen"
$form.MaximizeBox = $false
$form.BackColor = [System.Drawing.Color]::FromArgb(30, 30, 30)
$form.ForeColor = [System.Drawing.Color]::White
$form.Add_FormClosed({
[System.Windows.Forms.Application]::Exit()
})
# Define fonts
$headingFont = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
# Label for games
$labelGames = New-Object System.Windows.Forms.Label
$labelGames.Text = "Available Games:"
$labelGames.Location = New-Object System.Drawing.Point(10, 10)
$labelGames.Size = New-Object System.Drawing.Size(120, 20)
$labelGames.Font = $headingFont
$labelGames.BackColor = $form.BackColor
$labelGames.ForeColor = $form.ForeColor
$form.Controls.Add($labelGames)
# ListBox for games
$listboxGames = New-Object System.Windows.Forms.ListBox
$listboxGames.Location = New-Object System.Drawing.Point(10, 40)
$listboxGames.Width = 100 # Adjusted width
$listboxGames.Height = 200 # Set default height
$listboxGames.BackColor = [System.Drawing.Color]::FromArgb(50, 50, 50)
$listboxGames.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($listboxGames)
# Label for mod parents
$labelModParents = New-Object System.Windows.Forms.Label
$labelModParents.Text = "Mod Parent Directories:"
$labelModParents.Location = New-Object System.Drawing.Point(130, 10) # Moved to the right
$labelModParents.Size = New-Object System.Drawing.Size(160, 20)
$labelModParents.Font = $headingFont
$labelModParents.BackColor = $form.BackColor
$labelModParents.ForeColor = $form.ForeColor
$form.Controls.Add($labelModParents)
# ListBox for mod parents
$listboxModParents = New-Object System.Windows.Forms.ListBox
$listboxModParents.Location = New-Object System.Drawing.Point(130, 40) # Moved to the right
$listboxModParents.Width = 150 # Increased width
$listboxModParents.Height = 200 # Set default height
$listboxModParents.BackColor = [System.Drawing.Color]::FromArgb(50, 50, 50)
$listboxModParents.ForeColor = [System.Drawing.Color]::White
$form.Controls.Add($listboxModParents)
# Label for mods
$labelMods = New-Object System.Windows.Forms.Label
$labelMods.Text = "Available Mods:"
$labelMods.Location = New-Object System.Drawing.Point(290, 10) # Adjusted position
$labelMods.Size = New-Object System.Drawing.Size(150, 20)
$labelMods.Font = $headingFont
$labelMods.BackColor = $form.BackColor
$labelMods.ForeColor = $form.ForeColor
$form.Controls.Add($labelMods)
# ListBox for mods
$listboxMods = New-Object System.Windows.Forms.ListBox
$listboxMods.Location = New-Object System.Drawing.Point(290, 40) # Adjusted position
$listboxMods.Width = 300 # Adjusted width
$listboxMods.Height = 200 # Set default height same as mod parents
$listboxMods.SelectionMode = "MultiSimple"
$listboxMods.BackColor = [System.Drawing.Color]::FromArgb(50, 50, 50)
$listboxMods.ForeColor = [System.Drawing.Color]::White
$listboxMods.DrawMode = [System.Windows.Forms.DrawMode]::OwnerDrawFixed
$listboxMods.ItemHeight = 20
$form.Controls.Add($listboxMods)
# Function to dynamically adjust ListBox height based on item count
function Adjust-ListBoxHeight($listBox, $maxHeight) {
$itemCount = $listBox.Items.Count
$desiredHeight = $itemCount * $listBox.ItemHeight + 4 # +4 for borders
if ($desiredHeight -gt $maxHeight) {
$desiredHeight = $maxHeight
}
if ($desiredHeight -lt 200) {
$desiredHeight = 200 # Set minimum/default height
}
$listBox.Height = $desiredHeight
}
# Set maximum heights for list boxes
$maxModsListHeight = 320 # Capped at 20% less than previous height
# Checkbox for Select All
$checkboxSelectAll = New-Object System.Windows.Forms.CheckBox
$checkboxSelectAll.Text = "Select All"
$checkboxSelectAll.Location = New-Object System.Drawing.Point(600, 10) # Adjusted position
$checkboxSelectAll.Size = New-Object System.Drawing.Size(150, 20)
$checkboxSelectAll.BackColor = $form.BackColor
$checkboxSelectAll.ForeColor = $form.ForeColor
$form.Controls.Add($checkboxSelectAll)
# Checkbox for sorting by installed status
$checkboxSortByInstalled = New-Object System.Windows.Forms.CheckBox
$checkboxSortByInstalled.Text = "Sort by Installed Status"
$checkboxSortByInstalled.Location = New-Object System.Drawing.Point(600, 40) # Adjusted position
$checkboxSortByInstalled.Size = New-Object System.Drawing.Size(180, 20)
$checkboxSortByInstalled.BackColor = $form.BackColor
$checkboxSortByInstalled.ForeColor = $form.ForeColor
$form.Controls.Add($checkboxSortByInstalled)
# Open Mod Directory button (adjusted width)
$buttonOpenModFolder = New-Object System.Windows.Forms.Button
$buttonOpenModFolder.Text = "Open Mod Directory"
$buttonOpenModFolder.Location = New-Object System.Drawing.Point(600, 70) # Adjusted position
$buttonOpenModFolder.Size = New-Object System.Drawing.Size(200, 30)
$buttonOpenModFolder.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonOpenModFolder.ForeColor = [System.Drawing.Color]::White
$buttonOpenModFolder.FlatStyle = 'Flat'
$form.Controls.Add($buttonOpenModFolder)
# Install button (moved to right side and increased width)
$buttonInstall = New-Object System.Windows.Forms.Button
$buttonInstall.Text = "Install Selected Mods"
$buttonInstall.Location = New-Object System.Drawing.Point(600, 110) # Adjusted position
$buttonInstall.Size = New-Object System.Drawing.Size(200, 30)
$buttonInstall.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonInstall.ForeColor = [System.Drawing.Color]::White
$buttonInstall.FlatStyle = 'Flat'
$form.Controls.Add($buttonInstall)
# Uninstall button (moved to right side and increased width)
$buttonUninstall = New-Object System.Windows.Forms.Button
$buttonUninstall.Text = "Uninstall Selected Mods"
$buttonUninstall.Location = New-Object System.Drawing.Point(600, 150) # Adjusted position
$buttonUninstall.Size = New-Object System.Drawing.Size(200, 30)
$buttonUninstall.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonUninstall.ForeColor = [System.Drawing.Color]::White
$buttonUninstall.FlatStyle = 'Flat'
$form.Controls.Add($buttonUninstall)
# Add "Check for Updates" button (adjusted width)
$buttonCheckForUpdates = New-Object System.Windows.Forms.Button
$buttonCheckForUpdates.Text = "Check for Updates"
$buttonCheckForUpdates.Location = New-Object System.Drawing.Point(600, 190) # Adjusted position
$buttonCheckForUpdates.Size = New-Object System.Drawing.Size(200, 30)
$buttonCheckForUpdates.BackColor = [System.Drawing.Color]::FromArgb(70, 70, 70)
$buttonCheckForUpdates.ForeColor = [System.Drawing.Color]::White
$buttonCheckForUpdates.FlatStyle = 'Flat'
$form.Controls.Add($buttonCheckForUpdates)
# Progress Bar
$progressBar = New-Object System.Windows.Forms.ProgressBar
$progressBar.Location = New-Object System.Drawing.Point(10, 360)
$progressBar.Size = New-Object System.Drawing.Size(780, 20) # Adjusted width
$progressBar.Minimum = 0
$form.Controls.Add($progressBar)
# Logo Image
$scriptDir = Get-ScriptDirectory
$logoPath = Join-Path -Path $scriptDir -ChildPath 'icon.ico'
if (Test-Path -LiteralPath $logoPath) {
$logoImage = [System.Drawing.Image]::FromFile($logoPath)
$pictureBox = New-Object System.Windows.Forms.PictureBox
$pictureBox.Image = $logoImage
$pictureBox.SizeMode = 'Zoom'
$pictureBox.Location = New-Object System.Drawing.Point(275, 390) # Adjusted position
$pictureBox.Size = New-Object System.Drawing.Size(250, 250)
$pictureBox.BackColor = $form.BackColor
$form.Controls.Add($pictureBox)
}
# Status Label
$labelStatus = New-Object System.Windows.Forms.Label
$labelStatus.Text = "Status: Ready"
$labelStatus.Location = New-Object System.Drawing.Point(10, 660) # Adjusted position
$labelStatus.Size = New-Object System.Drawing.Size(780, 20) # Adjusted width
$labelStatus.BackColor = $form.BackColor
$labelStatus.ForeColor = $form.ForeColor
$form.Controls.Add($labelStatus)
# Donation Link Label (adjusted position)
$linkLabelDonate = New-Object System.Windows.Forms.LinkLabel
$linkLabelDonate.Text = "Donate/support the developer"
$linkLabelDonate.Location = New-Object System.Drawing.Point(300, 690) # Adjusted position
$linkLabelDonate.Size = New-Object System.Drawing.Size(200, 20)
$linkLabelDonate.BackColor = $form.BackColor
$linkLabelDonate.LinkColor = [System.Drawing.Color]::LightBlue
$linkLabelDonate.ActiveLinkColor = [System.Drawing.Color]::Orange
$linkLabelDonate.VisitedLinkColor = [System.Drawing.Color]::Purple
$linkLabelDonate.LinkBehavior = 'HoverUnderline'
$linkLabelDonate.Add_LinkClicked({
Start-Process "https://buymeacoffee.com/halfmanbear"
})
$form.Controls.Add($linkLabelDonate)
# Global variables
$script:GamesPath = $null
$script:Config = $null
$script:scriptDir = $scriptDir
# Load configuration
Load-Configuration
# Populate games
Populate-GamesList -ListBox $listboxGames
# Populate mod parents
Populate-ModParentsList -ListBox $listboxModParents
# Event handlers
$listboxGames.Add_SelectedIndexChanged({
UpdateModsList $listboxGames $listboxModParents $listboxMods $checkboxSortByInstalled
Adjust-ListBoxHeight $listboxMods $maxModsListHeight
})
$listboxModParents.Add_SelectedIndexChanged({
UpdateModsList $listboxGames $listboxModParents $listboxMods $checkboxSortByInstalled
Adjust-ListBoxHeight $listboxMods $maxModsListHeight
})
$buttonInstall.Add_Click({
InstallSelectedMods $listboxGames $listboxModParents $listboxMods $progressBar $labelStatus
})
$buttonUninstall.Add_Click({
UninstallSelectedMods $listboxGames $listboxModParents $listboxMods $progressBar $labelStatus
})
# Event handler for Select All checkbox
$checkboxSelectAll.Add_CheckedChanged({
if ($checkboxSelectAll.Checked) {
# Select all mods
for ($i = 0; $i -lt $listboxMods.Items.Count; $i++) {
$listboxMods.SetSelected($i, $true)
}
} else {
# Deselect all mods
$listboxMods.ClearSelected()
}
})
# Event handler for Sort by Installed Status checkbox
$checkboxSortByInstalled.Add_CheckedChanged({
UpdateModsList $listboxGames $listboxModParents $listboxMods $checkboxSortByInstalled
Adjust-ListBoxHeight $listboxMods $maxModsListHeight
})
# Open Mod Directory button handler (label->path resolver)
$buttonOpenModFolder.Add_Click({
try {
# Must have a Mod Parent selection
if (-not $listboxModParents.SelectedItem) {
Show-CustomMessageBox -Text "Please select a Mod Parent directory first." -Title "Open Mod Directory" -Buttons "OK"
return
}
# Resolve selected parent label to a real path under the repo's Games\DCS root
$scriptDir = $script:scriptDir # set in Initialize-GUI / Load-Configuration
$parentsRoot = Join-Path $scriptDir 'Games\DCS'
$selectedLabel = $listboxModParents.SelectedItem.ToString()
$parentDir = Get-ChildItem -LiteralPath $parentsRoot -Directory -Force |
Where-Object { $_.Name -eq $selectedLabel } |
Select-Object -First 1
if (-not $parentDir) {
Show-CustomMessageBox -Text "Could not resolve a path for:`n$selectedLabel" -Title "Open Mod Directory" -Buttons "OK"
return
}
$openPath = $parentDir.FullName
# If exactly one mod is selected, open that mod's subfolder
if ($listboxMods.SelectedItems.Count -eq 1) {
$selectedMod = $listboxMods.SelectedItems[0] # ModItem
$candidate = Join-Path -Path $openPath -ChildPath $selectedMod.Name
if (Test-Path -LiteralPath $candidate) { $openPath = $candidate }
}
if (-not (Test-Path -LiteralPath $openPath)) {
Show-CustomMessageBox -Text "Path not found:`n$openPath" -Title "Open Mod Directory" -Buttons "OK"
return