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
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.Win32;
using StardewModdingApi.Installer.Enums;
using StardewModdingAPI.Installer.Framework;
using StardewModdingAPI.Internal;
using StardewModdingAPI.Internal.ConsoleWriting;
namespace StardewModdingApi.Installer
{
/// <summary>Interactively performs the install and uninstall logic.</summary>
internal class InteractiveInstaller
{
/*********
** Properties
*********/
/// <summary>The name of the installer file in the package.</summary>
private readonly string InstallerFileName = "install.exe";
/// <summary>Mod files which shouldn't be deleted when deploying bundled mods (mod folder name => file names).</summary>
private readonly IDictionary<string, HashSet<string>> ProtectBundledFiles = new Dictionary<string, HashSet<string>>(StringComparer.InvariantCultureIgnoreCase)
{
["SaveBackup"] = new HashSet<string>(new[] { "backups", "config.json" }, StringComparer.InvariantCultureIgnoreCase)
};
/// <summary>The <see cref="Environment.OSVersion"/> value that represents Windows 7.</summary>
private readonly Version Windows7Version = new Version(6, 1);
/// <summary>The default file paths where Stardew Valley can be installed.</summary>
/// <param name="platform">The target platform.</param>
/// <remarks>Derived from the crossplatform mod config: https://github.com/Pathoschild/Stardew.ModBuildConfig. </remarks>
private IEnumerable<string> GetDefaultInstallPaths(Platform platform)
{
switch (platform)
{
case Platform.Linux:
case Platform.Mac:
{
string home = Environment.GetEnvironmentVariable("HOME");
// Linux
yield return $"{home}/GOG Games/Stardew Valley/game";
yield return Directory.Exists($"{home}/.steam/steam/steamapps/common/Stardew Valley")
? $"{home}/.steam/steam/steamapps/common/Stardew Valley"
: $"{home}/.local/share/Steam/steamapps/common/Stardew Valley";
// Mac
yield return "/Applications/Stardew Valley.app/Contents/MacOS";
yield return $"{home}/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS";
}
break;
case Platform.Windows:
{
// Windows
yield return @"C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley";
yield return @"C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley";
// Windows registry
IDictionary<string, string> registryKeys = new Dictionary<string, string>
{
[@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 413150"] = "InstallLocation", // Steam
[@"SOFTWARE\WOW6432Node\GOG.com\Games\1453375253"] = "PATH", // GOG on 64-bit Windows
};
foreach (var pair in registryKeys)
{
string path = this.GetLocalMachineRegistryValue(pair.Key, pair.Value);
if (!string.IsNullOrWhiteSpace(path))
yield return path;
}
// via Steam library path
string steampath = this.GetCurrentUserRegistryValue(@"Software\Valve\Steam", "SteamPath");
if (steampath != null)
yield return Path.Combine(steampath.Replace('/', '\\'), @"steamapps\common\Stardew Valley");
}
break;
default:
throw new InvalidOperationException($"Unknown platform '{platform}'.");
}
}
/// <summary>Get the absolute file or folder paths to remove when uninstalling SMAPI.</summary>
/// <param name="installDir">The folder for Stardew Valley and SMAPI.</param>
/// <param name="modsDir">The folder for SMAPI mods.</param>
private IEnumerable<string> GetUninstallPaths(DirectoryInfo installDir, DirectoryInfo modsDir)
{
string GetInstallPath(string path) => Path.Combine(installDir.FullName, path);
// current files
yield return GetInstallPath("libgdiplus.dylib"); // Linux/Mac only
yield return GetInstallPath("StardewModdingAPI"); // Linux/Mac only
yield return GetInstallPath("StardewModdingAPI.exe");
yield return GetInstallPath("StardewModdingAPI.exe.mdb"); // Linux/Mac only
yield return GetInstallPath("StardewModdingAPI.pdb"); // Windows only
yield return GetInstallPath("StardewModdingAPI.xml");
yield return GetInstallPath("smapi-internal");
// obsolete
yield return GetInstallPath(Path.Combine("Mods", ".cache")); // 1.3-1.4
yield return GetInstallPath(Path.Combine("Mods", "TrainerMod")); // *–2.0 (renamed to ConsoleCommands)
yield return GetInstallPath("Mono.Cecil.Rocks.dll"); // 1.3–1.8
yield return GetInstallPath("StardewModdingAPI-settings.json"); // 1.0-1.4
yield return GetInstallPath("StardewModdingAPI.AssemblyRewriters.dll"); // 1.3-2.5.5
yield return GetInstallPath("0Harmony.dll"); // moved in 2.8
yield return GetInstallPath("0Harmony.pdb"); // moved in 2.8
yield return GetInstallPath("Mono.Cecil.dll"); // moved in 2.8
yield return GetInstallPath("Newtonsoft.Json.dll"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.config.json"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.metadata.json"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.dll"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.pdb"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.xml"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.CoreInterfaces.dll"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.CoreInterfaces.pdb"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.Toolkit.CoreInterfaces.xml"); // moved in 2.8
yield return GetInstallPath("StardewModdingAPI.xml"); // moved in 2.8
yield return GetInstallPath("System.Numerics.dll"); // moved in 2.8
yield return GetInstallPath("System.Runtime.Caching.dll"); // moved in 2.8
yield return GetInstallPath("System.ValueTuple.dll"); // moved in 2.8
yield return GetInstallPath("steam_appid.txt"); // moved in 2.8
if (modsDir.Exists)
{
foreach (DirectoryInfo modDir in modsDir.EnumerateDirectories())
yield return Path.Combine(modDir.FullName, ".cache"); // 1.4–1.7
}
yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley", "ErrorLogs"); // remove old log files
}
/// <summary>Handles writing color-coded text to the console.</summary>
private ColorfulConsoleWriter ConsoleWriter;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
public InteractiveInstaller()
{
this.ConsoleWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.AutoDetect);
}
/// <summary>Run the install or uninstall script.</summary>
/// <param name="args">The command line arguments.</param>
/// <remarks>
/// Initialisation flow:
/// 1. Collect information (mainly OS and install path) and validate it.
/// 2. Ask the user whether to install or uninstall.
///
/// Uninstall logic:
/// 1. On Linux/Mac: if a backup of the launcher exists, delete the launcher and restore the backup.
/// 2. Delete all files and folders in the game directory matching one of the values returned by <see cref="GetUninstallPaths"/>.
///
/// Install flow:
/// 1. Run the uninstall flow.
/// 2. Copy the SMAPI files from package/Windows or package/Mono into the game directory.
/// 3. On Linux/Mac: back up the game launcher and replace it with the SMAPI launcher. (This isn't possible on Windows, so the user needs to configure it manually.)
/// 4. Create the 'Mods' directory.
/// 5. Copy the bundled mods into the 'Mods' directory (deleting any existing versions).
/// 6. Move any mods from app data into game's mods directory.
/// </remarks>
public void Run(string[] args)
{
/*********
** Step 1: initial setup
*********/
/****
** Get platform & set window title
****/
Platform platform = EnvironmentUtility.DetectPlatform();
Console.Title = $"SMAPI {this.GetDisplayVersion(this.GetType().Assembly.GetName().Version)} installer on {platform} {EnvironmentUtility.GetFriendlyPlatformName(platform)}";
Console.WriteLine();
/****
** Check if correct installer
****/
#if SMAPI_FOR_WINDOWS
if (platform == Platform.Linux || platform == Platform.Mac)
{
this.PrintError($"This is the installer for Windows. Run the 'install on {platform}.{(platform == Platform.Linux ? "sh" : "command")}' file instead.");
Console.ReadLine();
return;
}
#else
if (platform == Platform.Windows)
{
this.PrintError($"This is the installer for Linux/Mac. Run the 'install on Windows.exe' file instead.");
Console.ReadLine();
return;
}
#endif
/****
** Check Windows dependencies
****/
if (platform == Platform.Windows)
{
// .NET Framework 4.5+
if (!this.HasNetFramework45(platform))
{
this.PrintError(Environment.OSVersion.Version >= this.Windows7Version
? "Please install the latest version of .NET Framework before installing SMAPI." // Windows 7+
: "Please install .NET Framework 4.5 before installing SMAPI." // Windows Vista or earlier
);
this.PrintError("See the download page at https://www.microsoft.com/net/download/framework for details.");
Console.ReadLine();
return;
}
if (!this.HasXna(platform))
{
this.PrintError("You don't seem to have XNA Framework installed. Please run the game at least once before installing SMAPI, so it can perform its first-time setup.");
Console.ReadLine();
return;
}
}
/****
** read command-line arguments
****/
// get action from CLI
bool installArg = args.Contains("--install");
bool uninstallArg = args.Contains("--uninstall");
if (installArg && uninstallArg)
{
this.PrintError("You can't specify both --install and --uninstall command-line flags.");
Console.ReadLine();
return;
}
// get game path from CLI
string gamePathArg = null;
{
int pathIndex = Array.LastIndexOf(args, "--game-path") + 1;
if (pathIndex >= 1 && args.Length >= pathIndex)
gamePathArg = args[pathIndex];
}
/*********
** Step 2: choose a theme (can't auto-detect on Linux/Mac)
*********/
MonitorColorScheme scheme = MonitorColorScheme.AutoDetect;
if (platform == Platform.Linux || platform == Platform.Mac)
{
/****
** print header
****/
this.PrintPlain("Hi there! I'll help you install or remove SMAPI. Just a few questions first.");
this.PrintPlain("----------------------------------------------------------------------------");
Console.WriteLine();
/****
** show theme selector
****/
// get theme writers
var lightBackgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.LightBackground);
var darkDarkgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.DarkBackground);
// print question
this.PrintPlain("Which text looks more readable?");
Console.WriteLine();
Console.Write(" [1] ");
lightBackgroundWriter.WriteLine("Dark text on light background", ConsoleLogLevel.Info);
Console.Write(" [2] ");
darkDarkgroundWriter.WriteLine("Light text on dark background", ConsoleLogLevel.Info);
Console.WriteLine();
// handle choice
string choice = this.InteractivelyChoose("Type 1 or 2, then press enter.", new[] { "1", "2" });
switch (choice)
{
case "1":
scheme = MonitorColorScheme.LightBackground;
this.ConsoleWriter = lightBackgroundWriter;
break;
case "2":
scheme = MonitorColorScheme.DarkBackground;
this.ConsoleWriter = darkDarkgroundWriter;
break;
default:
throw new InvalidOperationException($"Unexpected action key '{choice}'.");
}
}
Console.Clear();
/*********
** Step 3: find game folder
*********/
InstallerPaths paths;
{
/****
** print header
****/
this.PrintInfo("Hi there! I'll help you install or remove SMAPI. Just a few questions first.");
this.PrintDebug($"Color scheme: {this.GetDisplayText(scheme)}");
this.PrintDebug("----------------------------------------------------------------------------");
Console.WriteLine();
/****
** collect details
****/
// get game path
this.PrintInfo("Where is your game folder?");
DirectoryInfo installDir = this.InteractivelyGetInstallPath(platform, gamePathArg);
if (installDir == null)
{
this.PrintError("Failed finding your game path.");
Console.ReadLine();
return;
}
// get folders
DirectoryInfo packageDir = platform.IsMono()
? new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) // installer runs from internal folder on Mono
: new DirectoryInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "internal", "Windows"));
paths = new InstallerPaths(packageDir, installDir, EnvironmentUtility.GetExecutableName(platform));
}
Console.Clear();
/*********
** Step 4: validate assumptions
*********/
{
if (!paths.PackageDir.Exists)
{
this.PrintError(platform == Platform.Windows && paths.PackagePath.Contains(Path.GetTempPath()) && paths.PackagePath.Contains(".zip")
? "The installer is missing some files. It looks like you're running the installer from inside the downloaded zip; make sure you unzip the downloaded file first, then run the installer from the unzipped folder."
: $"The 'internal/{paths.PackageDir.Name}' package folder is missing (should be at {paths.PackagePath})."
);
Console.ReadLine();
return;
}
if (!File.Exists(paths.ExecutablePath))
{
this.PrintError("The detected game install path doesn't contain a Stardew Valley executable.");
Console.ReadLine();
return;
}
}
/*********
** Step 5: ask what to do
*********/
ScriptAction action;
{
/****
** print header
****/
this.PrintInfo("Hi there! I'll help you install or remove SMAPI. Just one question first.");
this.PrintDebug($"Game path: {paths.GamePath}");
this.PrintDebug($"Color scheme: {this.GetDisplayText(scheme)}");
this.PrintDebug("----------------------------------------------------------------------------");
Console.WriteLine();
/****
** ask what to do
****/
if (installArg)
action = ScriptAction.Install;
else if (uninstallArg)
action = ScriptAction.Uninstall;
else
{
this.PrintInfo("What do you want to do?");
Console.WriteLine();
this.PrintInfo("[1] Install SMAPI.");
this.PrintInfo("[2] Uninstall SMAPI.");
Console.WriteLine();
string choice = this.InteractivelyChoose("Type 1 or 2, then press enter.", new[] { "1", "2" });
switch (choice)
{
case "1":
action = ScriptAction.Install;
break;
case "2":
action = ScriptAction.Uninstall;
break;
default:
throw new InvalidOperationException($"Unexpected action key '{choice}'.");
}
}
}
Console.Clear();
/*********
** Step 6: apply
*********/
{
/****
** print header
****/
this.PrintInfo($"That's all I need! I'll {action.ToString().ToLower()} SMAPI now.");
this.PrintDebug($"Game path: {paths.GamePath}");
this.PrintDebug($"Color scheme: {this.GetDisplayText(scheme)}");
this.PrintDebug("----------------------------------------------------------------------------");
Console.WriteLine();
/****
** Always uninstall old files
****/
// restore game launcher
if (platform.IsMono() && File.Exists(paths.UnixBackupLauncherPath))
{
this.PrintDebug("Removing SMAPI launcher...");
this.InteractivelyDelete(paths.UnixLauncherPath);
File.Move(paths.UnixBackupLauncherPath, paths.UnixLauncherPath);
}
// remove old files
string[] removePaths = this.GetUninstallPaths(paths.GameDir, paths.ModsDir)
.Where(path => Directory.Exists(path) || File.Exists(path))
.ToArray();
if (removePaths.Any())
{
this.PrintDebug(action == ScriptAction.Install ? "Removing previous SMAPI files..." : "Removing SMAPI files...");
foreach (string path in removePaths)
this.InteractivelyDelete(path);
}
/****
** Install new files
****/
if (action == ScriptAction.Install)
{
// copy SMAPI files to game dir
this.PrintDebug("Adding SMAPI files...");
foreach (FileSystemInfo sourceEntry in paths.PackageDir.EnumerateFileSystemInfos().Where(this.ShouldCopy))
{
if (sourceEntry.Name == this.InstallerFileName)
continue;
this.InteractivelyDelete(Path.Combine(paths.GameDir.FullName, sourceEntry.Name));
this.RecursiveCopy(sourceEntry, paths.GameDir);
}
// replace mod launcher (if possible)
if (platform.IsMono())
{
this.PrintDebug("Safely replacing game launcher...");
if (File.Exists(paths.UnixLauncherPath))
{
if (!File.Exists(paths.UnixBackupLauncherPath))
File.Move(paths.UnixLauncherPath, paths.UnixBackupLauncherPath);
else
this.InteractivelyDelete(paths.UnixLauncherPath);
}
File.Move(paths.UnixSmapiLauncherPath, paths.UnixLauncherPath);
}
// create mods directory (if needed)
if (!paths.ModsDir.Exists)
{
this.PrintDebug("Creating mods directory...");
paths.ModsDir.Create();
}
// add or replace bundled mods
DirectoryInfo packagedModsDir = new DirectoryInfo(Path.Combine(paths.PackageDir.FullName, "Mods"));
if (packagedModsDir.Exists && packagedModsDir.EnumerateDirectories().Any())
{
this.PrintDebug("Adding bundled mods...");
// special case: rename Omegasis' SaveBackup mod
{
DirectoryInfo oldFolder = new DirectoryInfo(Path.Combine(paths.ModsDir.FullName, "SaveBackup"));
DirectoryInfo newFolder = new DirectoryInfo(Path.Combine(paths.ModsDir.FullName, "AdvancedSaveBackup"));
FileInfo manifest = new FileInfo(Path.Combine(oldFolder.FullName, "manifest.json"));
if (manifest.Exists && !newFolder.Exists && File.ReadLines(manifest.FullName).Any(p => p.IndexOf("Omegasis", StringComparison.InvariantCultureIgnoreCase) != -1))
{
this.PrintDebug($" moving {oldFolder.Name} to {newFolder.Name}...");
this.Move(oldFolder, newFolder.FullName);
}
}
// add bundled mods
foreach (DirectoryInfo sourceDir in packagedModsDir.EnumerateDirectories())
{
this.PrintDebug($" adding {sourceDir.Name}...");
// init/clear target dir
DirectoryInfo targetDir = new DirectoryInfo(Path.Combine(paths.ModsDir.FullName, sourceDir.Name));
if (targetDir.Exists)
{
this.ProtectBundledFiles.TryGetValue(targetDir.Name, out HashSet<string> protectedFiles);
foreach (FileSystemInfo entry in targetDir.EnumerateFileSystemInfos())
{
if (protectedFiles == null || !protectedFiles.Contains(entry.Name))
this.InteractivelyDelete(entry.FullName);
}
}
else
targetDir.Create();
// copy files
foreach (FileInfo sourceFile in sourceDir.EnumerateFiles().Where(this.ShouldCopy))
sourceFile.CopyTo(Path.Combine(targetDir.FullName, sourceFile.Name));
}
// set SMAPI's color scheme if defined
if (scheme != MonitorColorScheme.AutoDetect)
{
string configPath = Path.Combine(paths.GamePath, "StardewModdingAPI.config.json");
string text = File
.ReadAllText(configPath)
.Replace(@"""ColorScheme"": ""AutoDetect""", $@"""ColorScheme"": ""{scheme}""");
File.WriteAllText(configPath, text);
}
}
// remove obsolete appdata mods
this.InteractivelyRemoveAppDataMods(paths.ModsDir, packagedModsDir);
}
}
Console.WriteLine();
Console.WriteLine();
/*********
** Step 7: final instructions
*********/
if (platform == Platform.Windows)
{
if (action == ScriptAction.Install)
{
this.PrintSuccess("SMAPI is installed! If you use Steam, set your launch options to enable achievements (see smapi.io/install):");
this.PrintSuccess($" \"{Path.Combine(paths.GamePath, "StardewModdingAPI.exe")}\" %command%");
Console.WriteLine();
this.PrintSuccess("If you don't use Steam, launch StardewModdingAPI.exe in your game folder to play with mods.");
}
else
this.PrintSuccess("SMAPI is removed! If you configured Steam to launch SMAPI, don't forget to clear your launch options.");
}
else
{
this.PrintSuccess(action == ScriptAction.Install
? "SMAPI is installed! Launch the game the same way as before to play with mods."
: "SMAPI is removed! Launch the game the same way as before to play without mods."
);
}
Console.ReadKey();
}
/*********
** Private methods
*********/
/// <summary>Get the display text for an assembly version.</summary>
/// <param name="version">The assembly version.</param>
private string GetDisplayVersion(Version version)
{
string str = $"{version.Major}.{version.Minor}";
if (version.Build != 0)
str += $".{version.Build}";
return str;
}
/// <summary>Get the display text for a color scheme.</summary>
/// <param name="scheme">The color scheme.</param>
private string GetDisplayText(MonitorColorScheme scheme)
{
switch (scheme)
{
case MonitorColorScheme.AutoDetect:
return "auto-detect";
case MonitorColorScheme.DarkBackground:
return "light text on dark background";
case MonitorColorScheme.LightBackground:
return "dark text on light background";
default:
return scheme.ToString();
}
}
/// <summary>Get the value of a key in the Windows HKLM registry.</summary>
/// <param name="key">The full path of the registry key relative to HKLM.</param>
/// <param name="name">The name of the value.</param>
private string GetLocalMachineRegistryValue(string key, string name)
{
RegistryKey localMachine = Environment.Is64BitOperatingSystem ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) : Registry.LocalMachine;
RegistryKey openKey = localMachine.OpenSubKey(key);
if (openKey == null)
return null;
using (openKey)
return (string)openKey.GetValue(name);
}
/// <summary>Get the value of a key in the Windows HKCU registry.</summary>
/// <param name="key">The full path of the registry key relative to HKCU.</param>
/// <param name="name">The name of the value.</param>
private string GetCurrentUserRegistryValue(string key, string name)
{
RegistryKey currentuser = Environment.Is64BitOperatingSystem ? RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64) : Registry.CurrentUser;
RegistryKey openKey = currentuser.OpenSubKey(key);
if (openKey == null)
return null;
using (openKey)
return (string)openKey.GetValue(name);
}
/// <summary>Print a message without formatting.</summary>
/// <param name="text">The text to print.</param>
private void PrintPlain(string text) => Console.WriteLine(text);
/// <summary>Print a debug message.</summary>
/// <param name="text">The text to print.</param>
private void PrintDebug(string text) => this.ConsoleWriter.WriteLine(text, ConsoleLogLevel.Debug);
/// <summary>Print a debug message.</summary>
/// <param name="text">The text to print.</param>
private void PrintInfo(string text) => this.ConsoleWriter.WriteLine(text, ConsoleLogLevel.Info);
/// <summary>Print a warning message.</summary>
/// <param name="text">The text to print.</param>
private void PrintWarning(string text) => this.ConsoleWriter.WriteLine(text, ConsoleLogLevel.Warn);
/// <summary>Print a warning message.</summary>
/// <param name="text">The text to print.</param>
private void PrintError(string text) => this.ConsoleWriter.WriteLine(text, ConsoleLogLevel.Error);
/// <summary>Print a success message.</summary>
/// <param name="text">The text to print.</param>
private void PrintSuccess(string text) => this.ConsoleWriter.WriteLine(text, ConsoleLogLevel.Success);
/// <summary>Get whether the current system has .NET Framework 4.5 or later installed. This only applies on Windows.</summary>
/// <param name="platform">The current platform.</param>
/// <exception cref="NotSupportedException">The current platform is not Windows.</exception>
private bool HasNetFramework45(Platform platform)
{
switch (platform)
{
case Platform.Windows:
using (RegistryKey versionKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
return versionKey?.GetValue("Release") != null; // .NET Framework 4.5+
default:
throw new NotSupportedException("The installed .NET Framework version can only be checked on Windows.");
}
}
/// <summary>Get whether the current system has XNA Framework installed. This only applies on Windows.</summary>
/// <param name="platform">The current platform.</param>
/// <exception cref="NotSupportedException">The current platform is not Windows.</exception>
private bool HasXna(Platform platform)
{
switch (platform)
{
case Platform.Windows:
using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\XNA\Framework"))
return key != null; // XNA Framework 4.0+
default:
throw new NotSupportedException("The installed XNA Framework version can only be checked on Windows.");
}
}
/// <summary>Interactively delete a file or folder path, and block until deletion completes.</summary>
/// <param name="path">The file or folder path.</param>
private void InteractivelyDelete(string path)
{
while (true)
{
try
{
this.ForceDelete(Directory.Exists(path) ? new DirectoryInfo(path) : (FileSystemInfo)new FileInfo(path));
break;
}
catch (Exception ex)
{
this.PrintError($"Oops! The installer couldn't delete {path}: [{ex.GetType().Name}] {ex.Message}.");
this.PrintError("Try rebooting your computer and then run the installer again. If that doesn't work, try deleting it yourself then press any key to retry.");
Console.ReadKey();
}
}
}
/// <summary>Recursively copy a directory or file.</summary>
/// <param name="source">The file or folder to copy.</param>
/// <param name="targetFolder">The folder to copy into.</param>
private void RecursiveCopy(FileSystemInfo source, DirectoryInfo targetFolder)
{
if (!targetFolder.Exists)
targetFolder.Create();
switch (source)
{
case FileInfo sourceFile:
sourceFile.CopyTo(Path.Combine(targetFolder.FullName, sourceFile.Name));
break;
case DirectoryInfo sourceDir:
DirectoryInfo targetSubfolder = new DirectoryInfo(Path.Combine(targetFolder.FullName, sourceDir.Name));
foreach (var entry in sourceDir.EnumerateFileSystemInfos())
this.RecursiveCopy(entry, targetSubfolder);
break;
default:
throw new NotSupportedException($"Unknown filesystem info type '{source.GetType().FullName}'.");
}
}
/// <summary>Delete a file or folder regardless of file permissions, and block until deletion completes.</summary>
/// <param name="entry">The file or folder to reset.</param>
/// <remarks>This method is mirred from <c>FileUtilities.ForceDelete</c> in the toolkit.</remarks>
private void ForceDelete(FileSystemInfo entry)
{
// ignore if already deleted
entry.Refresh();
if (!entry.Exists)
return;
// delete children
if (entry is DirectoryInfo folder)
{
foreach (FileSystemInfo child in folder.GetFileSystemInfos())
this.ForceDelete(child);
}
// reset permissions & delete
entry.Attributes = FileAttributes.Normal;
entry.Delete();
// wait for deletion to finish
for (int i = 0; i < 10; i++)
{
entry.Refresh();
if (entry.Exists)
Thread.Sleep(500);
}
// throw exception if deletion didn't happen before timeout
entry.Refresh();
if (entry.Exists)
throw new IOException($"Timed out trying to delete {entry.FullName}");
}
/// <summary>Interactively ask the user to choose a value.</summary>
/// <param name="print">A callback which prints a message to the console.</param>
/// <param name="message">The message to print.</param>
/// <param name="options">The allowed options (not case sensitive).</param>
/// <param name="indent">The indentation to prefix to output.</param>
private string InteractivelyChoose(string message, string[] options, string indent = "", Action<string> print = null)
{
print = print ?? this.PrintInfo;
while (true)
{
print(indent + message);
Console.Write(indent);
string input = Console.ReadLine()?.Trim().ToLowerInvariant();
if (!options.Contains(input))
{
print($"{indent}That's not a valid option.");
continue;
}
return input;
}
}
/// <summary>Interactively locate the game install path to update.</summary>
/// <param name="platform">The current platform.</param>
/// <param name="specifiedPath">The path specified as a command-line argument (if any), which should override automatic path detection.</param>
private DirectoryInfo InteractivelyGetInstallPath(Platform platform, string specifiedPath)
{
// get executable name
string executableFilename = EnvironmentUtility.GetExecutableName(platform);
// validate specified path
if (specifiedPath != null)
{
var dir = new DirectoryInfo(specifiedPath);
if (!dir.Exists)
{
this.PrintError($"You specified --game-path \"{specifiedPath}\", but that folder doesn't exist.");
return null;
}
if (!dir.EnumerateFiles(executableFilename).Any())
{
this.PrintError($"You specified --game-path \"{specifiedPath}\", but that folder doesn't contain the Stardew Valley executable.");
return null;
}
return dir;
}
// get installed paths
DirectoryInfo[] defaultPaths =
(
from path in this.GetDefaultInstallPaths(platform).Distinct(StringComparer.InvariantCultureIgnoreCase)
let dir = new DirectoryInfo(path)
where dir.Exists && dir.EnumerateFiles(executableFilename).Any()
select dir
)
.GroupBy(p => p.FullName, StringComparer.InvariantCultureIgnoreCase) // ignore duplicate paths
.Select(p => p.First())
.ToArray();
// choose where to install
if (defaultPaths.Any())
{
// only one path
if (defaultPaths.Length == 1)
return defaultPaths.First();
// let user choose path
Console.WriteLine();
this.PrintInfo("Found multiple copies of the game:");
for (int i = 0; i < defaultPaths.Length; i++)
this.PrintInfo($"[{i + 1}] {defaultPaths[i].FullName}");
Console.WriteLine();
string[] validOptions = Enumerable.Range(1, defaultPaths.Length).Select(p => p.ToString(CultureInfo.InvariantCulture)).ToArray();
string choice = this.InteractivelyChoose("Where do you want to add/remove SMAPI? Type the number next to your choice, then press enter.", validOptions);
int index = int.Parse(choice, CultureInfo.InvariantCulture) - 1;
return defaultPaths[index];
}
// ask user
this.PrintInfo("Oops, couldn't find the game automatically.");
while (true)
{
// get path from user
this.PrintInfo($"Type the file path to the game directory (the one containing '{executableFilename}'), then press enter.");
string path = Console.ReadLine()?.Trim();
if (string.IsNullOrWhiteSpace(path))
{
this.PrintInfo(" You must specify a directory path to continue.");
continue;
}
// normalise path
if (platform == Platform.Windows)
path = path.Replace("\"", ""); // in Windows, quotes are used to escape spaces and aren't part of the file path
if (platform == Platform.Linux || platform == Platform.Mac)
path = path.Replace("\\ ", " "); // in Linux/Mac, spaces in paths may be escaped if copied from the command line
if (path.StartsWith("~/"))
{
string home = Environment.GetEnvironmentVariable("HOME") ?? Environment.GetEnvironmentVariable("USERPROFILE");
path = Path.Combine(home, path.Substring(2));
}
// get directory
if (File.Exists(path))
path = Path.GetDirectoryName(path);
DirectoryInfo directory = new DirectoryInfo(path);
// validate path
if (!directory.Exists)
{
this.PrintInfo(" That directory doesn't seem to exist.");
continue;
}
if (!directory.EnumerateFiles(executableFilename).Any())
{
this.PrintInfo(" That directory doesn't contain a Stardew Valley executable.");
continue;
}
// looks OK
this.PrintInfo(" OK!");
return directory;
}
}
/// <summary>Interactively move mods out of the appdata directory.</summary>
/// <param name="properModsDir">The directory which should contain all mods.</param>
/// <param name="packagedModsDir">The installer directory containing packaged mods.</param>
private void InteractivelyRemoveAppDataMods(DirectoryInfo properModsDir, DirectoryInfo packagedModsDir)
{
// get packaged mods to delete
string[] packagedModNames = packagedModsDir.GetDirectories().Select(p => p.Name).ToArray();
// get path
string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley");
DirectoryInfo modDir = new DirectoryInfo(Path.Combine(appDataPath, "Mods"));
// check if migration needed
if (!modDir.Exists)
return;
this.PrintDebug($"Found an obsolete mod path: {modDir.FullName}");
this.PrintDebug(" Support for mods here was dropped in SMAPI 1.0 (it was never officially supported).");
// move mods if no conflicts (else warn)
foreach (FileSystemInfo entry in modDir.EnumerateFileSystemInfos().Where(this.ShouldCopy))
{
// get type
bool isDir = entry is DirectoryInfo;
if (!isDir && !(entry is FileInfo))
continue; // should never happen
// delete packaged mods (newer version bundled into SMAPI)
if (isDir && packagedModNames.Contains(entry.Name, StringComparer.InvariantCultureIgnoreCase))
{
this.PrintDebug($" Deleting {entry.Name} because it's bundled into SMAPI...");
this.InteractivelyDelete(entry.FullName);
continue;
}
// check paths
string newPath = Path.Combine(properModsDir.FullName, entry.Name);
if (isDir ? Directory.Exists(newPath) : File.Exists(newPath))
{
this.PrintWarning($" Can't move {entry.Name} because it already exists in your game's mod directory.");
continue;
}
// move into mods
this.PrintDebug($" Moving {entry.Name} into the game's mod directory...");
this.Move(entry, newPath);
}
// delete if empty
if (modDir.EnumerateFileSystemInfos().Any())
this.PrintWarning(" You have files in this folder which couldn't be moved automatically. These will be ignored by SMAPI.");
else
{
this.PrintDebug(" Deleted empty directory.");
modDir.Delete(recursive: true);
}
}
/// <summary>Move a filesystem entry to a new parent directory.</summary>
/// <param name="entry">The filesystem entry to move.</param>
/// <param name="newPath">The destination path.</param>
/// <remarks>We can't use <see cref="FileInfo.MoveTo"/> or <see cref="DirectoryInfo.MoveTo"/>, because those don't work across partitions.</remarks>
private void Move(FileSystemInfo entry, string newPath)
{
// file
if (entry is FileInfo file)
{
file.CopyTo(newPath);
file.Delete();
}
// directory
else
{
Directory.CreateDirectory(newPath);
DirectoryInfo directory = (DirectoryInfo)entry;
foreach (FileSystemInfo child in directory.EnumerateFileSystemInfos().Where(this.ShouldCopy))
this.Move(child, Path.Combine(newPath, child.Name));
directory.Delete(recursive: true);
}
}
/// <summary>Get whether a file or folder should be copied from the installer files.</summary>
/// <param name="entry">The file or folder info.</param>
private bool ShouldCopy(FileSystemInfo entry)
{
switch (entry.Name)
{
case "mcs":
return false; // ignore Mac symlink
case "Mods":
return false; // Mods folder handled separately
default:
return true;
}
}
}
}
|