diff options
author | Jesse Plamondon-Willard <github@jplamondonw.com> | 2016-12-12 11:52:34 -0500 |
---|---|---|
committer | Jesse Plamondon-Willard <github@jplamondonw.com> | 2016-12-12 11:52:34 -0500 |
commit | 28e2695a19f7babf35d177367840a82b798beb55 (patch) | |
tree | 591b2badd77a7c9c0c36b8e09abdb6a323513307 /src | |
parent | aaf354761f18a18b0bcb81c9bd32819bb28deac9 (diff) | |
parent | a3376e2a6257c01c52a3c64c4f5f1f8de9a9c906 (diff) | |
download | SMAPI-28e2695a19f7babf35d177367840a82b798beb55.tar.gz SMAPI-28e2695a19f7babf35d177367840a82b798beb55.tar.bz2 SMAPI-28e2695a19f7babf35d177367840a82b798beb55.zip |
Merge branch 'develop' into stable
Diffstat (limited to 'src')
35 files changed, 1317 insertions, 261 deletions
diff --git a/src/GlobalAssemblyInfo.cs b/src/GlobalAssemblyInfo.cs index 239c5eba..0dfb42bb 100644 --- a/src/GlobalAssemblyInfo.cs +++ b/src/GlobalAssemblyInfo.cs @@ -2,5 +2,5 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] -[assembly: AssemblyVersion("1.3.0.0")] -[assembly: AssemblyFileVersion("1.3.0.0")]
\ No newline at end of file +[assembly: AssemblyVersion("1.4.0.0")] +[assembly: AssemblyFileVersion("1.4.0.0")]
\ No newline at end of file diff --git a/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj b/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj index 51a49da0..1e6caacc 100644 --- a/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj +++ b/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj @@ -47,7 +47,6 @@ <ErrorReport>prompt</ErrorReport> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> - <Import Project="$(SolutionDir)\dependencies.targets" /> <ItemGroup> <Reference Include="Mono.Cecil, Version=0.9.6.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756, processorArchitecture=MSIL"> <HintPath>..\packages\Mono.Cecil.0.9.6.4\lib\net45\Mono.Cecil.dll</HintPath> @@ -82,13 +81,6 @@ <ItemGroup> <None Include="packages.config" /> </ItemGroup> - <ItemGroup /> + <Import Project="$(SolutionDir)\crossplatform.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. - <Target Name="BeforeBuild"> - </Target> - <Target Name="AfterBuild"> - </Target> - --> </Project>
\ No newline at end of file diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs index 1d3802ab..9c8f8af9 100644 --- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs +++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs @@ -1,7 +1,11 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; +#if SMAPI_FOR_WINDOWS +using Microsoft.Win32; +#endif using StardewModdingApi.Installer.Enums; namespace StardewModdingApi.Installer @@ -14,21 +18,40 @@ namespace StardewModdingApi.Installer *********/ /// <summary>The default file paths where Stardew Valley can be installed.</summary> /// <remarks>Derived from the crossplatform mod config: https://github.com/Pathoschild/Stardew.ModBuildConfig. </remarks> - private readonly string[] DefaultInstallPaths = { - // Linux - $"{Environment.GetEnvironmentVariable("HOME")}/GOG Games/Stardew Valley/game", - $"{Environment.GetEnvironmentVariable("HOME")}/.local/share/Steam/steamapps/common/Stardew Valley", + private IEnumerable<string> DefaultInstallPaths + { + get + { + // Linux + yield return $"{Environment.GetEnvironmentVariable("HOME")}/GOG Games/Stardew Valley/game"; + yield return $"{Environment.GetEnvironmentVariable("HOME")}/.local/share/Steam/steamapps/common/Stardew Valley"; - // Mac - $"{Environment.GetEnvironmentVariable("HOME")}/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS", + // Mac + yield return $"{Environment.GetEnvironmentVariable("HOME")}/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS"; - // Windows - @"C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley", - @"C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley" - }; + // Windows + yield return @"C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley"; + yield return @"C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley"; - /// <summary>The files to remove when uninstalling SMAPI.</summary> - private readonly string[] UninstallFiles = + // Windows registry +#if SMAPI_FOR_WINDOWS + 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; + } +#endif + } + } + + /// <summary>The directory or file paths to remove when uninstalling SMAPI, relative to the game directory.</summary> + private readonly string[] UninstallPaths = { // common "StardewModdingAPI.exe", @@ -45,7 +68,10 @@ namespace StardewModdingApi.Installer "System.Numerics.dll", // Windows only - "StardewModdingAPI.pdb" + "StardewModdingAPI.pdb", + + // obsolete + "Mods/.cache" }; @@ -59,16 +85,17 @@ namespace StardewModdingApi.Installer /// 1. Collect information (mainly OS and install path) and validate it. /// 2. Ask the user whether to install or uninstall. /// - /// Install flow: - /// 1. Copy the SMAPI files from package/Windows or package/Mono into the game directory. - /// 2. 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.) - /// 3. Create the 'Mods' directory. - /// 4. Copy the bundled mods into the 'Mods' directory (deleting any existing versions). - /// 5. Move any mods from app data into game's mods directory. - /// /// Uninstall logic: /// 1. On Linux/Mac: if a backup of the launcher exists, delete the launcher and restore the backup. - /// 2. Delete all files in the game directory matching one of the <see cref="UninstallFiles"/>. + /// 2. Delete all files and folders in the game directory matching one of the <see cref="UninstallPaths"/>. + /// + /// 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) { @@ -85,7 +112,6 @@ namespace StardewModdingApi.Installer unixLauncher = Path.Combine(installDir.FullName, "StardewValley"), unixLauncherBackup = Path.Combine(installDir.FullName, "StardewValley-original") }; - this.PrintDebug($"Detected {(platform == Platform.Windows ? "Windows" : "Linux or Mac")} with game in {installDir}."); /**** @@ -115,7 +141,7 @@ namespace StardewModdingApi.Installer ScriptAction action; { - string choice = this.InteractivelyChoose("What do you want to do?", "1", "2"); + string choice = this.InteractivelyChoose("What do you want to do? Type 1 or 2, then press enter.", "1", "2"); switch (choice) { case "1": @@ -131,90 +157,93 @@ namespace StardewModdingApi.Installer Console.WriteLine(); /**** - ** Perform action + ** Always uninstall old files ****/ - switch (action) + // restore game launcher + if (platform == Platform.Mono && File.Exists(paths.unixLauncherBackup)) { - case ScriptAction.Uninstall: - { - // restore game launcher - if (platform == Platform.Mono && File.Exists(paths.unixLauncherBackup)) - { - this.PrintDebug("Restoring game launcher..."); - if (File.Exists(paths.unixLauncher)) - File.Delete(paths.unixLauncher); - File.Move(paths.unixLauncherBackup, paths.unixLauncher); - } - - // remove SMAPI files - this.PrintDebug("Removing SMAPI files..."); - foreach (string filename in this.UninstallFiles) - { - string targetPath = Path.Combine(installDir.FullName, filename); - if (File.Exists(targetPath)) - File.Delete(targetPath); - } - } - break; + this.PrintDebug("Removing SMAPI launcher..."); + if (File.Exists(paths.unixLauncher)) + File.Delete(paths.unixLauncher); + File.Move(paths.unixLauncherBackup, paths.unixLauncher); + } + + // remove old files + string[] removePaths = this.UninstallPaths + .Select(path => Path.Combine(installDir.FullName, path)) + .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) + { + if (Directory.Exists(path)) + Directory.Delete(path, recursive: true); + else + File.Delete(path); + } + } + + /**** + ** Install new files + ****/ + if (action == ScriptAction.Install) + { + // copy SMAPI files to game dir + this.PrintDebug("Adding SMAPI files..."); + foreach (FileInfo sourceFile in packageDir.EnumerateFiles()) + { + string targetPath = Path.Combine(installDir.FullName, sourceFile.Name); + if (File.Exists(targetPath)) + File.Delete(targetPath); + sourceFile.CopyTo(targetPath); + } + + // replace mod launcher (if possible) + if (platform == Platform.Mono) + { + this.PrintDebug("Safely replacing game launcher..."); + if (!File.Exists(paths.unixLauncherBackup)) + File.Move(paths.unixLauncher, paths.unixLauncherBackup); + else if (File.Exists(paths.unixLauncher)) + File.Delete(paths.unixLauncher); + + File.Move(paths.unixSmapiLauncher, paths.unixLauncher); + } + + // create mods directory (if needed) + DirectoryInfo modsDir = new DirectoryInfo(Path.Combine(installDir.FullName, "Mods")); + if (!modsDir.Exists) + { + this.PrintDebug("Creating mods directory..."); + modsDir.Create(); + } - case ScriptAction.Install: + // add or replace bundled mods + Directory.CreateDirectory(Path.Combine(installDir.FullName, "Mods")); + DirectoryInfo packagedModsDir = new DirectoryInfo(Path.Combine(packageDir.FullName, "Mods")); + if (packagedModsDir.Exists && packagedModsDir.EnumerateDirectories().Any()) + { + this.PrintDebug("Adding bundled mods..."); + foreach (DirectoryInfo sourceDir in packagedModsDir.EnumerateDirectories()) { - // copy SMAPI files to game dir - this.PrintDebug("Copying SMAPI files to game directory..."); - foreach (FileInfo sourceFile in packageDir.EnumerateFiles()) - { - string targetPath = Path.Combine(installDir.FullName, sourceFile.Name); - if (File.Exists(targetPath)) - File.Delete(targetPath); - sourceFile.CopyTo(targetPath); - } - - // replace mod launcher (if possible) - if (platform == Platform.Mono) - { - this.PrintDebug("Safely replacing game launcher..."); - if (!File.Exists(paths.unixLauncherBackup)) - File.Move(paths.unixLauncher, paths.unixLauncherBackup); - else if (File.Exists(paths.unixLauncher)) - File.Delete(paths.unixLauncher); - - File.Move(paths.unixSmapiLauncher, paths.unixLauncher); - } - - // create mods directory (if needed) - DirectoryInfo modsDir = new DirectoryInfo(Path.Combine(installDir.FullName, "Mods")); - if (!modsDir.Exists) - { - this.PrintDebug("Creating mods directory..."); - modsDir.Create(); - } - - // add or replace bundled mods - Directory.CreateDirectory(Path.Combine(installDir.FullName, "Mods")); - DirectoryInfo packagedModsDir = new DirectoryInfo(Path.Combine(packageDir.FullName, "Mods")); - if (packagedModsDir.Exists && packagedModsDir.EnumerateDirectories().Any()) - { - this.PrintDebug("Adding bundled mods..."); - foreach (DirectoryInfo sourceDir in packagedModsDir.EnumerateDirectories()) - { - this.PrintDebug($" adding {sourceDir.Name}..."); - - // initialise target dir - DirectoryInfo targetDir = new DirectoryInfo(Path.Combine(modsDir.FullName, sourceDir.Name)); - if (targetDir.Exists) - targetDir.Delete(recursive: true); - targetDir.Create(); - - // copy files - foreach (FileInfo sourceFile in sourceDir.EnumerateFiles()) - sourceFile.CopyTo(Path.Combine(targetDir.FullName, sourceFile.Name)); - } - } - - // remove obsolete appdata mods - this.InteractivelyRemoveAppDataMods(platform, modsDir); + this.PrintDebug($" adding {sourceDir.Name}..."); + + // initialise target dir + DirectoryInfo targetDir = new DirectoryInfo(Path.Combine(modsDir.FullName, sourceDir.Name)); + if (targetDir.Exists) + targetDir.Delete(recursive: true); + targetDir.Create(); + + // copy files + foreach (FileInfo sourceFile in sourceDir.EnumerateFiles()) + sourceFile.CopyTo(Path.Combine(targetDir.FullName, sourceFile.Name)); } - break; + } + + // remove obsolete appdata mods + this.InteractivelyRemoveAppDataMods(platform, modsDir, packagedModsDir); } Console.WriteLine(); @@ -255,6 +284,21 @@ namespace StardewModdingApi.Installer } } +#if SMAPI_FOR_WINDOWS + /// <summary>Get the value of a key in the Windows 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); + } +#endif + /// <summary>Print a debug message.</summary> /// <param name="text">The text to print.</param> private void PrintDebug(string text) @@ -313,12 +357,11 @@ namespace StardewModdingApi.Installer } // ask user - Console.WriteLine("Oops, couldn't find your Stardew Valley install path automatically. You'll need to specify where the game is installed (or install SMAPI manually)."); + Console.WriteLine("Oops, couldn't find the game automatically."); while (true) { // get path from user - Console.WriteLine(" Enter the game's full directory path (the one containing 'StardewValley.exe' or 'Stardew Valley.exe')."); - Console.Write(" > "); + Console.WriteLine($"Type the file path to the game directory (the one containing '{(platform == Platform.Mono ? "StardewValley.exe" : "Stardew Valley.exe")}'), then press enter."); string path = Console.ReadLine()?.Trim(); if (string.IsNullOrWhiteSpace(path)) { @@ -356,8 +399,12 @@ namespace StardewModdingApi.Installer /// <summary>Interactively move mods out of the appdata directory.</summary> /// <param name="platform">The current platform.</param> /// <param name="properModsDir">The directory which should contain all mods.</param> - private void InteractivelyRemoveAppDataMods(Platform platform, DirectoryInfo properModsDir) + /// <param name="packagedModsDir">The installer directory containing packaged mods.</param> + private void InteractivelyRemoveAppDataMods(Platform platform, DirectoryInfo properModsDir, DirectoryInfo packagedModsDir) { + // get packaged mods to delete + string[] packagedModNames = packagedModsDir.GetDirectories().Select(p => p.Name).ToArray(); + // get path string homePath = platform == Platform.Windows ? Environment.GetEnvironmentVariable("APPDATA") @@ -379,6 +426,14 @@ namespace StardewModdingApi.Installer 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..."); + entry.Delete(); + continue; + } + // check paths string newPath = Path.Combine(properModsDir.FullName, entry.Name); if (isDir ? Directory.Exists(newPath) : File.Exists(newPath)) @@ -389,10 +444,7 @@ namespace StardewModdingApi.Installer // move into mods this.PrintDebug($" Moving {entry.Name} into the game's mod directory..."); - if (isDir) - (entry as DirectoryInfo).MoveTo(newPath); - else - (entry as FileInfo).MoveTo(newPath); + this.Move(entry, newPath); } // delete if empty @@ -404,5 +456,32 @@ namespace StardewModdingApi.Installer modDir.Delete(); } } + + /// <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) + { + FileInfo file = (FileInfo)entry; + file.CopyTo(newPath); + file.Delete(); + } + + // directory + else + { + Directory.CreateDirectory(newPath); + + DirectoryInfo directory = (DirectoryInfo)entry; + foreach (FileSystemInfo child in directory.EnumerateFileSystemInfos()) + this.Move(child, Path.Combine(newPath, child.Name)); + + directory.Delete(); + } + } } } diff --git a/src/StardewModdingAPI.Installer/StardewModdingAPI.Installer.csproj b/src/StardewModdingAPI.Installer/StardewModdingAPI.Installer.csproj index 0a33cd57..9baa0d14 100644 --- a/src/StardewModdingAPI.Installer/StardewModdingAPI.Installer.csproj +++ b/src/StardewModdingAPI.Installer/StardewModdingAPI.Installer.csproj @@ -50,6 +50,7 @@ <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> + <Import Project="$(SolutionDir)\crossplatform.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- package files --> <Target Name="AfterBuild"> diff --git a/src/StardewModdingAPI.sln b/src/StardewModdingAPI.sln index d97e4645..6e13b16b 100644 --- a/src/StardewModdingAPI.sln +++ b/src/StardewModdingAPI.sln @@ -11,6 +11,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "metadata", "metadata", "{86 ProjectSection(SolutionItems) = preProject ..\.gitattributes = ..\.gitattributes ..\.gitignore = ..\.gitignore + crossplatform.targets = crossplatform.targets GlobalAssemblyInfo.cs = GlobalAssemblyInfo.cs ..\LICENSE = ..\LICENSE ..\README.md = ..\README.md diff --git a/src/StardewModdingAPI/Advanced/ConfigFile.cs b/src/StardewModdingAPI/Advanced/ConfigFile.cs index 1aba2f2c..1a2e6618 100644 --- a/src/StardewModdingAPI/Advanced/ConfigFile.cs +++ b/src/StardewModdingAPI/Advanced/ConfigFile.cs @@ -9,7 +9,7 @@ namespace StardewModdingAPI.Advanced /********* ** Accessors *********/ - /// <summary>Provides methods for interacting with the mod directory, including read/writing the config file.</summary> + /// <summary>Provides simplified APIs for writing mods.</summary> public IModHelper ModHelper { get; set; } /// <summary>The file path from which the model was loaded, relative to the mod directory.</summary> diff --git a/src/StardewModdingAPI/Advanced/IConfigFile.cs b/src/StardewModdingAPI/Advanced/IConfigFile.cs index 841f4c58..5bc31a88 100644 --- a/src/StardewModdingAPI/Advanced/IConfigFile.cs +++ b/src/StardewModdingAPI/Advanced/IConfigFile.cs @@ -6,7 +6,7 @@ /********* ** Accessors *********/ - /// <summary>Provides methods for interacting with the mod directory, including read/writing the config file.</summary> + /// <summary>Provides simplified APIs for writing mods.</summary> IModHelper ModHelper { get; set; } /// <summary>The file path from which the model was loaded, relative to the mod directory.</summary> diff --git a/src/StardewModdingAPI/Constants.cs b/src/StardewModdingAPI/Constants.cs index 3feb0830..f5b9e70a 100644 --- a/src/StardewModdingAPI/Constants.cs +++ b/src/StardewModdingAPI/Constants.cs @@ -26,7 +26,7 @@ namespace StardewModdingAPI ** Accessors *********/ /// <summary>SMAPI's current semantic version.</summary> - public static readonly Version Version = new Version(1, 3, 0, null); + public static readonly Version Version = new Version(1, 4, 0, null); /// <summary>The minimum supported version of Stardew Valley.</summary> public const string MinimumGameVersion = "1.1"; diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs index 3459488e..9d4d6b11 100644 --- a/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs @@ -54,7 +54,8 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// <summary>Rewrite the types referenced by an assembly.</summary> /// <param name="assembly">The assembly to rewrite.</param> - public void RewriteAssembly(AssemblyDefinition assembly) + /// <returns>Returns whether the assembly was modified.</returns> + public bool RewriteAssembly(AssemblyDefinition assembly) { ModuleDefinition module = assembly.Modules.Single(); // technically an assembly can have multiple modules, but none of the build tools (including MSBuild) support it; simplify by assuming one module @@ -71,7 +72,7 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting } } if (!shouldRewrite) - return; + return false; // add target assembly references foreach (AssemblyNameReference target in this.AssemblyMap.TargetReferences.Values) @@ -117,6 +118,7 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting } method.Body.OptimizeMacros(); } + return true; } diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs new file mode 100644 index 00000000..3dfbc78c --- /dev/null +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs @@ -0,0 +1,46 @@ +using System.IO; + +namespace StardewModdingAPI.Framework.AssemblyRewriting +{ + /// <summary>Represents cached metadata for a rewritten assembly.</summary> + internal class CacheEntry + { + /********* + ** Accessors + *********/ + /// <summary>The MD5 hash for the original assembly.</summary> + public readonly string Hash; + + /// <summary>The SMAPI version used to rewrite the assembly.</summary> + public readonly string ApiVersion; + + /// <summary>Whether to use the cached assembly instead of the original assembly.</summary> + public readonly bool UseCachedAssembly; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="hash">The MD5 hash for the original assembly.</param> + /// <param name="apiVersion">The SMAPI version used to rewrite the assembly.</param> + /// <param name="useCachedAssembly">Whether to use the cached assembly instead of the original assembly.</param> + public CacheEntry(string hash, string apiVersion, bool useCachedAssembly) + { + this.Hash = hash; + this.ApiVersion = apiVersion; + this.UseCachedAssembly = useCachedAssembly; + } + + /// <summary>Get whether the cache entry is up-to-date for the given assembly hash.</summary> + /// <param name="paths">The paths for the cached assembly.</param> + /// <param name="hash">The MD5 hash of the original assembly.</param> + /// <param name="currentVersion">The current SMAPI version.</param> + public bool IsUpToDate(CachePaths paths, string hash, Version currentVersion) + { + return hash == this.Hash + && this.ApiVersion == currentVersion.ToString() + && (!this.UseCachedAssembly || File.Exists(paths.Assembly)); + } + } +}
\ No newline at end of file diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs index 17c4d188..18861873 100644 --- a/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs @@ -12,8 +12,8 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// <summary>The file path of the assembly file.</summary> public string Assembly { get; } - /// <summary>The file path containing the MD5 hash for the assembly.</summary> - public string Hash { get; } + /// <summary>The file path containing the assembly metadata.</summary> + public string Metadata { get; } /********* @@ -22,12 +22,12 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// <summary>Construct an instance.</summary> /// <param name="directory">The directory path which contains the assembly.</param> /// <param name="assembly">The file path of the assembly file.</param> - /// <param name="hash">The file path containing the MD5 hash for the assembly.</param> - public CachePaths(string directory, string assembly, string hash) + /// <param name="metadata">The file path containing the assembly metadata.</param> + public CachePaths(string directory, string assembly, string metadata) { this.Directory = directory; this.Assembly = assembly; - this.Hash = hash; + this.Metadata = metadata; } } }
\ No newline at end of file diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs new file mode 100644 index 00000000..8f34bb20 --- /dev/null +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs @@ -0,0 +1,49 @@ +namespace StardewModdingAPI.Framework.AssemblyRewriting +{ + /// <summary>Metadata about a preprocessed assembly.</summary> + internal class RewriteResult + { + /********* + ** Accessors + *********/ + /// <summary>The original assembly path.</summary> + public readonly string OriginalAssemblyPath; + + /// <summary>The cache paths.</summary> + public readonly CachePaths CachePaths; + + /// <summary>The rewritten assembly bytes.</summary> + public readonly byte[] AssemblyBytes; + + /// <summary>The MD5 hash for the original assembly.</summary> + public readonly string Hash; + + /// <summary>Whether to use the cached assembly instead of the original assembly.</summary> + public readonly bool UseCachedAssembly; + + /// <summary>Whether this data is newer than the cache.</summary> + public readonly bool IsNewerThanCache; + + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="originalAssemblyPath"></param> + /// <param name="cachePaths">The cache paths.</param> + /// <param name="assemblyBytes">The rewritten assembly bytes.</param> + /// <param name="hash">The MD5 hash for the original assembly.</param> + /// <param name="useCachedAssembly">Whether to use the cached assembly instead of the original assembly.</param> + /// <param name="isNewerThanCache">Whether this data is newer than the cache.</param> + public RewriteResult(string originalAssemblyPath, CachePaths cachePaths, byte[] assemblyBytes, string hash, bool useCachedAssembly, bool isNewerThanCache) + { + this.OriginalAssemblyPath = originalAssemblyPath; + this.CachePaths = cachePaths; + this.Hash = hash; + this.AssemblyBytes = assemblyBytes; + this.UseCachedAssembly = useCachedAssembly; + this.IsNewerThanCache = isNewerThanCache; + } + } +} diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs index 71f70fd5..415785d9 100644 --- a/src/StardewModdingAPI/Framework/InternalExtensions.cs +++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs @@ -70,15 +70,21 @@ namespace StardewModdingAPI.Framework /// <param name="exception">The error to summarise.</param> public static string GetLogSummary(this Exception exception) { - string summary = exception.ToString(); + // type load exception + if (exception is TypeLoadException) + return $"Failed loading type: {((TypeLoadException)exception).TypeName}: {exception}"; + // reflection type load exception if (exception is ReflectionTypeLoadException) { + string summary = exception.ToString(); foreach (Exception childEx in ((ReflectionTypeLoadException)exception).LoaderExceptions) summary += $"\n\n{childEx.GetLogSummary()}"; + return summary; } - return summary; + // anything else + return exception.ToString(); } } } diff --git a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs index 51018b0b..1ceb8ad2 100644 --- a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs +++ b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs @@ -1,9 +1,11 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using Mono.Cecil; +using Newtonsoft.Json; using StardewModdingAPI.AssemblyRewriters; using StardewModdingAPI.Framework.AssemblyRewriting; @@ -15,8 +17,8 @@ namespace StardewModdingAPI.Framework /********* ** Properties *********/ - /// <summary>The directory in which to cache data.</summary> - private readonly string CacheDirPath; + /// <summary>The name of the directory containing a mod's cached data.</summary> + private readonly string CacheDirName; /// <summary>Metadata for mapping assemblies to the current <see cref="Platform"/>.</summary> private readonly PlatformAssemblyMap AssemblyMap; @@ -32,74 +34,76 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// <summary>Construct an instance.</summary> - /// <param name="cacheDirPath">The cache directory.</param> + /// <param name="cacheDirName">The name of the directory containing a mod's cached data.</param> /// <param name="targetPlatform">The current game platform.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> - public ModAssemblyLoader(string cacheDirPath, Platform targetPlatform, IMonitor monitor) + public ModAssemblyLoader(string cacheDirName, Platform targetPlatform, IMonitor monitor) { - this.CacheDirPath = cacheDirPath; + this.CacheDirName = cacheDirName; this.Monitor = monitor; this.AssemblyMap = Constants.GetAssemblyMap(targetPlatform); this.AssemblyTypeRewriter = new AssemblyTypeRewriter(this.AssemblyMap, monitor); } - /// <summary>Preprocess an assembly and cache the modified version.</summary> + /// <summary>Preprocess an assembly unless the cache is up to date.</summary> /// <param name="assemblyPath">The assembly file path.</param> - public void ProcessAssembly(string assemblyPath) + /// <returns>Returns the rewrite metadata for the preprocessed assembly.</returns> + public RewriteResult ProcessAssemblyUnlessCached(string assemblyPath) { // read assembly data - string assemblyFileName = Path.GetFileName(assemblyPath); - string assemblyDir = Path.GetDirectoryName(assemblyPath); byte[] assemblyBytes = File.ReadAllBytes(assemblyPath); - string hash = $"SMAPI {Constants.Version}|" + string.Join("", MD5.Create().ComputeHash(assemblyBytes).Select(p => p.ToString("X2"))); + string hash = string.Join("", MD5.Create().ComputeHash(assemblyBytes).Select(p => p.ToString("X2"))); - // check cache - CachePaths cachePaths = this.GetCacheInfo(assemblyPath); - bool canUseCache = File.Exists(cachePaths.Assembly) && File.Exists(cachePaths.Hash) && hash == File.ReadAllText(cachePaths.Hash); - - // process assembly if not cached - if (!canUseCache) + // get cached result if current + CachePaths cachePaths = this.GetCachePaths(assemblyPath); + { + CacheEntry cacheEntry = File.Exists(cachePaths.Metadata) ? JsonConvert.DeserializeObject<CacheEntry>(File.ReadAllText(cachePaths.Metadata)) : null; + if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.Version)) + return new RewriteResult(assemblyPath, cachePaths, assemblyBytes, cacheEntry.Hash, cacheEntry.UseCachedAssembly, isNewerThanCache: false); // no rewrite needed + } + this.Monitor.Log($"Preprocessing {Path.GetFileName(assemblyPath)} for compatibility...", LogLevel.Trace); + + // rewrite assembly + AssemblyDefinition assembly; + using (Stream readStream = new MemoryStream(assemblyBytes)) + assembly = AssemblyDefinition.ReadAssembly(readStream); + bool modified = this.AssemblyTypeRewriter.RewriteAssembly(assembly); + using (MemoryStream outStream = new MemoryStream()) { - this.Monitor.Log($"Loading {assemblyFileName} for the first time; preprocessing...", LogLevel.Trace); - - // read assembly definition - AssemblyDefinition assembly; - using (Stream readStream = new MemoryStream(assemblyBytes)) - assembly = AssemblyDefinition.ReadAssembly(readStream); - - // rewrite assembly to match platform - this.AssemblyTypeRewriter.RewriteAssembly(assembly); - - // write cache - using (MemoryStream outStream = new MemoryStream()) - { - // get assembly bytes - assembly.Write(outStream); - byte[] outBytes = outStream.ToArray(); - - // write assembly data - Directory.CreateDirectory(cachePaths.Directory); - File.WriteAllBytes(cachePaths.Assembly, outBytes); - File.WriteAllText(cachePaths.Hash, hash); - - // copy any mdb/pdb files - foreach (string path in Directory.GetFiles(assemblyDir, "*.mdb").Concat(Directory.GetFiles(assemblyDir, "*.pdb"))) - { - string filename = Path.GetFileName(path); - File.Copy(path, Path.Combine(cachePaths.Directory, filename), overwrite: true); - } - } + assembly.Write(outStream); + byte[] outBytes = outStream.ToArray(); + return new RewriteResult(assemblyPath, cachePaths, outBytes, hash, useCachedAssembly: modified, isNewerThanCache: true); } } - /// <summary>Load a preprocessed assembly.</summary> - /// <param name="assemblyPath">The assembly file path.</param> - public Assembly LoadCachedAssembly(string assemblyPath) + /// <summary>Write rewritten assembly metadata to the cache for a mod.</summary> + /// <param name="results">The rewrite results.</param> + /// <param name="forceCacheAssemblies">Whether to write all assemblies to the cache, even if they weren't modified.</param> + /// <exception cref="InvalidOperationException">There are no results to write, or the results are not all for the same directory.</exception> + public void WriteCache(IEnumerable<RewriteResult> results, bool forceCacheAssemblies) { - CachePaths cachePaths = this.GetCacheInfo(assemblyPath); - if (!File.Exists(cachePaths.Assembly)) - throw new InvalidOperationException($"The assembly {assemblyPath} doesn't exist in the preprocessed cache."); - return Assembly.UnsafeLoadFrom(cachePaths.Assembly); // unsafe load allows DLLs downloaded from the Internet without the user needing to 'unblock' them + results = results.ToArray(); + + // get cache directory + if (!results.Any()) + throw new InvalidOperationException("There are no assemblies to cache."); + if (results.Select(p => p.CachePaths.Directory).Distinct().Count() > 1) + throw new InvalidOperationException("The assemblies can't be cached together because they have different source directories."); + string cacheDir = results.Select(p => p.CachePaths.Directory).First(); + + // reset cache + if (Directory.Exists(cacheDir)) + Directory.Delete(cacheDir, recursive: true); + Directory.CreateDirectory(cacheDir); + + // cache all results + foreach (RewriteResult result in results) + { + CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.Version.ToString(), forceCacheAssemblies || result.UseCachedAssembly); + File.WriteAllText(result.CachePaths.Metadata, JsonConvert.SerializeObject(cacheEntry)); + if (forceCacheAssemblies || result.UseCachedAssembly) + File.WriteAllBytes(result.CachePaths.Assembly, result.AssemblyBytes); + } } /// <summary>Resolve an assembly from its name.</summary> @@ -124,13 +128,13 @@ namespace StardewModdingAPI.Framework *********/ /// <summary>Get the cache details for an assembly.</summary> /// <param name="assemblyPath">The assembly file path.</param> - private CachePaths GetCacheInfo(string assemblyPath) + private CachePaths GetCachePaths(string assemblyPath) { - string key = Path.GetFileNameWithoutExtension(assemblyPath); - string dirPath = Path.Combine(this.CacheDirPath, new DirectoryInfo(Path.GetDirectoryName(assemblyPath)).Name); - string cacheAssemblyPath = Path.Combine(dirPath, $"{key}.dll"); - string cacheHashPath = Path.Combine(dirPath, $"{key}.hash"); - return new CachePaths(dirPath, cacheAssemblyPath, cacheHashPath); + string fileName = Path.GetFileName(assemblyPath); + string dirPath = Path.Combine(Path.GetDirectoryName(assemblyPath), this.CacheDirName); + string cacheAssemblyPath = Path.Combine(dirPath, fileName); + string metadataPath = Path.Combine(dirPath, $"{fileName}.json"); + return new CachePaths(dirPath, cacheAssemblyPath, metadataPath); } } } diff --git a/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs b/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs new file mode 100644 index 00000000..0bf45969 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs @@ -0,0 +1,93 @@ +using System; +using System.Reflection; + +namespace StardewModdingAPI.Framework.Reflection +{ + /// <summary>A private field obtained through reflection.</summary> + /// <typeparam name="TValue">The field value type.</typeparam> + internal class PrivateField<TValue> : IPrivateField<TValue> + { + /********* + ** Properties + *********/ + /// <summary>The type that has the field.</summary> + private readonly Type ParentType; + + /// <summary>The object that has the instance field (if applicable).</summary> + private readonly object Parent; + + /// <summary>The display name shown in error messages.</summary> + private string DisplayName => $"{this.ParentType.FullName}::{this.FieldInfo.Name}"; + + + /********* + ** Accessors + *********/ + /// <summary>The reflection metadata.</summary> + public FieldInfo FieldInfo { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="parentType">The type that has the field.</param> + /// <param name="obj">The object that has the instance field (if applicable).</param> + /// <param name="field">The reflection metadata.</param> + /// <param name="isStatic">Whether the field is static.</param> + /// <exception cref="ArgumentNullException">The <paramref name="parentType"/> or <paramref name="field"/> is null.</exception> + /// <exception cref="ArgumentException">The <paramref name="obj"/> is null for a non-static field, or not null for a static field.</exception> + public PrivateField(Type parentType, object obj, FieldInfo field, bool isStatic) + { + // validate + if (parentType == null) + throw new ArgumentNullException(nameof(parentType)); + if (field == null) + throw new ArgumentNullException(nameof(field)); + if (isStatic && obj != null) + throw new ArgumentException("A static field cannot have an object instance."); + if (!isStatic && obj == null) + throw new ArgumentException("A non-static field must have an object instance."); + + // save + this.ParentType = parentType; + this.Parent = obj; + this.FieldInfo = field; + } + + /// <summary>Get the field value.</summary> + public TValue GetValue() + { + try + { + return (TValue)this.FieldInfo.GetValue(this.Parent); + } + catch (InvalidCastException) + { + throw new InvalidCastException($"Can't convert the private {this.DisplayName} field from {this.FieldInfo.FieldType.FullName} to {typeof(TValue).FullName}."); + } + catch (Exception ex) + { + throw new Exception($"Couldn't get the value of the private {this.DisplayName} field", ex); + } + } + + /// <summary>Set the field value.</summary> + //// <param name="value">The value to set.</param> + public void SetValue(TValue value) + { + try + { + this.FieldInfo.SetValue(this.Parent, value); + } + catch (InvalidCastException) + { + throw new InvalidCastException($"Can't assign the private {this.DisplayName} field a {typeof(TValue).FullName} value, must be compatible with {this.FieldInfo.FieldType.FullName}."); + } + catch (Exception ex) + { + throw new Exception($"Couldn't set the value of the private {this.DisplayName} field", ex); + } + } + } +} diff --git a/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs b/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs new file mode 100644 index 00000000..ba2374f4 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs @@ -0,0 +1,99 @@ +using System; +using System.Reflection; + +namespace StardewModdingAPI.Framework.Reflection +{ + /// <summary>A private method obtained through reflection.</summary> + internal class PrivateMethod : IPrivateMethod + { + /********* + ** Properties + *********/ + /// <summary>The type that has the method.</summary> + private readonly Type ParentType; + + /// <summary>The object that has the instance method (if applicable).</summary> + private readonly object Parent; + + /// <summary>The display name shown in error messages.</summary> + private string DisplayName => $"{this.ParentType.FullName}::{this.MethodInfo.Name}"; + + + /********* + ** Accessors + *********/ + /// <summary>The reflection metadata.</summary> + public MethodInfo MethodInfo { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="parentType">The type that has the method.</param> + /// <param name="obj">The object that has the instance method(if applicable).</param> + /// <param name="method">The reflection metadata.</param> + /// <param name="isStatic">Whether the field is static.</param> + /// <exception cref="ArgumentNullException">The <paramref name="parentType"/> or <paramref name="method"/> is null.</exception> + /// <exception cref="ArgumentException">The <paramref name="obj"/> is null for a non-static method, or not null for a static method.</exception> + public PrivateMethod(Type parentType, object obj, MethodInfo method, bool isStatic) + { + // validate + if (parentType == null) + throw new ArgumentNullException(nameof(parentType)); + if (method == null) + throw new ArgumentNullException(nameof(method)); + if (isStatic && obj != null) + throw new ArgumentException("A static method cannot have an object instance."); + if (!isStatic && obj == null) + throw new ArgumentException("A non-static method must have an object instance."); + + // save + this.ParentType = parentType; + this.Parent = obj; + this.MethodInfo = method; + } + + /// <summary>Invoke the method.</summary> + /// <typeparam name="TValue">The return type.</typeparam> + /// <param name="arguments">The method arguments to pass in.</param> + public TValue Invoke<TValue>(params object[] arguments) + { + // invoke method + object result; + try + { + result = this.MethodInfo.Invoke(this.Parent, arguments); + } + catch (Exception ex) + { + throw new Exception($"Couldn't invoke the private {this.DisplayName} field", ex); + } + + // cast return value + try + { + return (TValue)result; + } + catch (InvalidCastException) + { + throw new InvalidCastException($"Can't convert the return value of the private {this.DisplayName} method from {this.MethodInfo.ReturnType.FullName} to {typeof(TValue).FullName}."); + } + } + + /// <summary>Invoke the method.</summary> + /// <param name="arguments">The method arguments to pass in.</param> + public void Invoke(params object[] arguments) + { + // invoke method + try + { + this.MethodInfo.Invoke(this.Parent, arguments); + } + catch (Exception ex) + { + throw new Exception($"Couldn't invoke the private {this.DisplayName} field", ex); + } + } + } +}
\ No newline at end of file diff --git a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs new file mode 100644 index 00000000..38b4e357 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs @@ -0,0 +1,239 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Caching; + +namespace StardewModdingAPI.Framework.Reflection +{ + /// <summary>Provides helper methods for accessing private game code.</summary> + /// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks> + internal class ReflectionHelper : IReflectionHelper + { + /********* + ** Properties + *********/ + /// <summary>The cached fields and methods found via reflection.</summary> + private readonly MemoryCache Cache = new MemoryCache(typeof(ReflectionHelper).FullName); + + /// <summary>The sliding cache expiration time.</summary> + private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5); + + + /********* + ** Public methods + *********/ + /**** + ** Fields + ****/ + /// <summary>Get a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field wrapper, or <c>null</c> if the field doesn't exist and <paramref name="required"/> is <c>false</c>.</returns> + public IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true) + { + // validate + if (obj == null) + throw new ArgumentNullException(nameof(obj), "Can't get a private instance field from a null object."); + + // get field from hierarchy + IPrivateField<TValue> field = this.GetFieldFromHierarchy<TValue>(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic); + if (required && field == null) + throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance field."); + return field; + } + + /// <summary>Get a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true) + { + // get field from hierarchy + IPrivateField<TValue> field = this.GetFieldFromHierarchy<TValue>(type, null, name, BindingFlags.NonPublic | BindingFlags.Static); + if (required && field == null) + throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static field."); + return field; + } + + /**** + ** Field values + ** (shorthand since this is the most common case) + ****/ + /// <summary>Get the value of a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks> + public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true) + { + return this.GetPrivateField<TValue>(obj, name, required).GetValue(); + } + + /// <summary>Get the value of a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks> + public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true) + { + return this.GetPrivateField<TValue>(type, name, required).GetValue(); + } + + /**** + ** Methods + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true) + { + // validate + if (obj == null) + throw new ArgumentNullException(nameof(obj), "Can't get a private instance method from a null object."); + + // get method from hierarchy + IPrivateMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic); + if (required && method == null) + throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance method."); + return method; + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true) + { + // get method from hierarchy + IPrivateMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static); + if (required && method == null) + throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static method."); + return method; + } + + /**** + ** Methods by signature + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, Type[] argumentTypes, bool required = true) + { + // validate parent + if (obj == null) + throw new ArgumentNullException(nameof(obj), "Can't get a private instance method from a null object."); + + // get method from hierarchy + PrivateMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic, argumentTypes); + if (required && method == null) + throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance method with that signature."); + return method; + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, Type[] argumentTypes, bool required = true) + { + // get field from hierarchy + PrivateMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static, argumentTypes); + if (required && method == null) + throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static method with that signature."); + return method; + } + + + /********* + ** Private methods + *********/ + /// <summary>Get a field from the type hierarchy.</summary> + /// <typeparam name="TValue">The expected field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="bindingFlags">The reflection binding which flags which indicates what type of field to find.</param> + private IPrivateField<TValue> GetFieldFromHierarchy<TValue>(Type type, object obj, string name, BindingFlags bindingFlags) + { + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); + FieldInfo field = this.GetCached<FieldInfo>($"field::{isStatic}::{type.FullName}::{name}", () => + { + FieldInfo fieldInfo = null; + for (; type != null && fieldInfo == null; type = type.BaseType) + fieldInfo = type.GetField(name, bindingFlags); + return fieldInfo; + }); + + return field != null + ? new PrivateField<TValue>(type, obj, field, isStatic) + : null; + } + + /// <summary>Get a method from the type hierarchy.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The method name.</param> + /// <param name="bindingFlags">The reflection binding which flags which indicates what type of method to find.</param> + private IPrivateMethod GetMethodFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags) + { + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); + MethodInfo method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}", () => + { + MethodInfo methodInfo = null; + for (; type != null && methodInfo == null; type = type.BaseType) + methodInfo = type.GetMethod(name, bindingFlags); + return methodInfo; + }); + + return method != null + ? new PrivateMethod(type, obj, method, isStatic: bindingFlags.HasFlag(BindingFlags.Static)) + : null; + } + + /// <summary>Get a method from the type hierarchy.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The method name.</param> + /// <param name="bindingFlags">The reflection binding which flags which indicates what type of method to find.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + private PrivateMethod GetMethodFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags, Type[] argumentTypes) + { + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); + MethodInfo method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}({string.Join(",", argumentTypes.Select(p => p.FullName))})", () => + { + MethodInfo methodInfo = null; + for (; type != null && methodInfo == null; type = type.BaseType) + methodInfo = type.GetMethod(name, bindingFlags, null, argumentTypes, null); + return methodInfo; + }); + return method != null + ? new PrivateMethod(type, obj, method, isStatic) + : null; + } + + /// <summary>Get a method or field through the cache.</summary> + /// <typeparam name="TMemberInfo">The expected <see cref="MemberInfo"/> type.</typeparam> + /// <param name="key">The cache key.</param> + /// <param name="fetch">Fetches a new value to cache.</param> + private TMemberInfo GetCached<TMemberInfo>(string key, Func<TMemberInfo> fetch) where TMemberInfo : MemberInfo + { + // get from cache + if (this.Cache.Contains(key)) + return (TMemberInfo)this.Cache[key]; + + // fetch & cache new value + TMemberInfo result = fetch(); + this.Cache.Add(key, result, new CacheItemPolicy { SlidingExpiration = this.SlidingCacheExpiry }); + return result; + } + } +}
\ No newline at end of file diff --git a/src/StardewModdingAPI/IModHelper.cs b/src/StardewModdingAPI/IModHelper.cs index 1af7df6b..183b3b2b 100644 --- a/src/StardewModdingAPI/IModHelper.cs +++ b/src/StardewModdingAPI/IModHelper.cs @@ -1,6 +1,6 @@ namespace StardewModdingAPI { - /// <summary>Provides methods for interacting with a mod directory.</summary> + /// <summary>Provides simplified APIs for writing mods.</summary> public interface IModHelper { /********* @@ -9,6 +9,9 @@ /// <summary>The mod directory path.</summary> string DirectoryPath { get; } + /// <summary>Simplifies access to private game code.</summary> + IReflectionHelper Reflection { get; } + /********* ** Public methods diff --git a/src/StardewModdingAPI/IPrivateField.cs b/src/StardewModdingAPI/IPrivateField.cs new file mode 100644 index 00000000..3e681c12 --- /dev/null +++ b/src/StardewModdingAPI/IPrivateField.cs @@ -0,0 +1,26 @@ +using System.Reflection; + +namespace StardewModdingAPI +{ + /// <summary>A private field obtained through reflection.</summary> + /// <typeparam name="TValue">The field value type.</typeparam> + public interface IPrivateField<TValue> + { + /********* + ** Accessors + *********/ + /// <summary>The reflection metadata.</summary> + FieldInfo FieldInfo { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Get the field value.</summary> + TValue GetValue(); + + /// <summary>Set the field value.</summary> + //// <param name="value">The value to set.</param> + void SetValue(TValue value); + } +}
\ No newline at end of file diff --git a/src/StardewModdingAPI/IPrivateMethod.cs b/src/StardewModdingAPI/IPrivateMethod.cs new file mode 100644 index 00000000..67fc8b3c --- /dev/null +++ b/src/StardewModdingAPI/IPrivateMethod.cs @@ -0,0 +1,27 @@ +using System.Reflection; + +namespace StardewModdingAPI +{ + /// <summary>A private method obtained through reflection.</summary> + public interface IPrivateMethod + { + /********* + ** Accessors + *********/ + /// <summary>The reflection metadata.</summary> + MethodInfo MethodInfo { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Invoke the method.</summary> + /// <typeparam name="TValue">The return type.</typeparam> + /// <param name="arguments">The method arguments to pass in.</param> + TValue Invoke<TValue>(params object[] arguments); + + /// <summary>Invoke the method.</summary> + /// <param name="arguments">The method arguments to pass in.</param> + void Invoke(params object[] arguments); + } +}
\ No newline at end of file diff --git a/src/StardewModdingAPI/IReflectionHelper.cs b/src/StardewModdingAPI/IReflectionHelper.cs new file mode 100644 index 00000000..5d747eda --- /dev/null +++ b/src/StardewModdingAPI/IReflectionHelper.cs @@ -0,0 +1,53 @@ +using System; + +namespace StardewModdingAPI +{ + /// <summary>Simplifies access to private game code.</summary> + public interface IReflectionHelper + { + /********* + ** Public methods + *********/ + /// <summary>Get a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true); + + /// <summary>Get a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true); + + /// <summary>Get the value of a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks> + TValue GetPrivateValue<TValue>(object obj, string name, bool required = true); + + /// <summary>Get the value of a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks> + TValue GetPrivateValue<TValue>(Type type, string name, bool required = true); + + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true); + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true); + } +} diff --git a/src/StardewModdingAPI/Inheritance/SGame.cs b/src/StardewModdingAPI/Inheritance/SGame.cs index 93d56553..f70d0696 100644 --- a/src/StardewModdingAPI/Inheritance/SGame.cs +++ b/src/StardewModdingAPI/Inheritance/SGame.cs @@ -373,7 +373,7 @@ namespace StardewModdingAPI.Inheritance /// <summary>The method called to draw everything to the screen.</summary> /// <param name="gameTime">A snapshot of the game timing state.</param> - /// <remarks>This implementation is identical to <see cref="Game1.Draw"/>, except for minor formatting and added events.</remarks> + /// <remarks>This implementation is identical to <see cref="Game1.Draw"/>, except for try..catch around menu draw code, minor formatting, and added events.</remarks> protected override void Draw(GameTime gameTime) { // track frame rate @@ -388,9 +388,25 @@ namespace StardewModdingAPI.Inheritance if (Game1.options.showMenuBackground && Game1.activeClickableMenu != null && Game1.activeClickableMenu.showWithoutTransparencyIfOptionIsSet()) { Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - Game1.activeClickableMenu.drawBackground(Game1.spriteBatch); + try + { + Game1.activeClickableMenu.drawBackground(Game1.spriteBatch); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing its background. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); - Game1.activeClickableMenu.draw(Game1.spriteBatch); + try + { + Game1.activeClickableMenu.draw(Game1.spriteBatch); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); Game1.spriteBatch.End(); if (!this.ZoomLevelIsOne) @@ -434,7 +450,15 @@ namespace StardewModdingAPI.Inheritance if (Game1.showingEndOfNightStuff) { Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - Game1.activeClickableMenu?.draw(Game1.spriteBatch); + try + { + Game1.activeClickableMenu?.draw(Game1.spriteBatch); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } Game1.spriteBatch.End(); if (!this.ZoomLevelIsOne) { @@ -742,7 +766,15 @@ namespace StardewModdingAPI.Inheritance if (Game1.activeClickableMenu != null) { GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); - Game1.activeClickableMenu.draw(Game1.spriteBatch); + try + { + Game1.activeClickableMenu.draw(Game1.spriteBatch); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); } else diff --git a/src/StardewModdingAPI/Mod.cs b/src/StardewModdingAPI/Mod.cs index 05122df5..21551771 100644 --- a/src/StardewModdingAPI/Mod.cs +++ b/src/StardewModdingAPI/Mod.cs @@ -13,10 +13,11 @@ namespace StardewModdingAPI /// <summary>The backing field for <see cref="Mod.PathOnDisk"/>.</summary> private string _pathOnDisk; + /********* ** Accessors *********/ - /// <summary>Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</summary> + /// <summary>Provides simplified APIs for writing mods.</summary> public IModHelper Helper { get; internal set; } /// <summary>Writes messages to the console and log file.</summary> @@ -74,12 +75,12 @@ namespace StardewModdingAPI public virtual void Entry(params object[] objects) { } /// <summary>The mod entry point, called after the mod is first loaded.</summary> - /// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param> + /// <param name="helper">Provides simplified APIs for writing mods.</param> [Obsolete("This overload is obsolete since SMAPI 1.1.")] public virtual void Entry(ModHelper helper) { } /// <summary>The mod entry point, called after the mod is first loaded.</summary> - /// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param> + /// <param name="helper">Provides simplified APIs for writing mods.</param> public virtual void Entry(IModHelper helper) { } diff --git a/src/StardewModdingAPI/ModHelper.cs b/src/StardewModdingAPI/ModHelper.cs index 6a7e200a..1fcc0182 100644 --- a/src/StardewModdingAPI/ModHelper.cs +++ b/src/StardewModdingAPI/ModHelper.cs @@ -2,11 +2,12 @@ using System.IO; using Newtonsoft.Json; using StardewModdingAPI.Advanced; +using StardewModdingAPI.Framework.Reflection; namespace StardewModdingAPI { - /// <summary>Provides methods for interacting with a mod directory.</summary> - [Obsolete("Use " + nameof(IModHelper) + " instead.")] + /// <summary>Provides simplified APIs for writing mods.</summary> + [Obsolete("Use " + nameof(IModHelper) + " instead.")] // only direct mod access to this class is obsolete public class ModHelper : IModHelper { /********* @@ -15,6 +16,9 @@ namespace StardewModdingAPI /// <summary>The mod directory path.</summary> public string DirectoryPath { get; } + /// <summary>Simplifies access to private game code.</summary> + public IReflectionHelper Reflection { get; } = new ReflectionHelper(); + /********* ** Public methods diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index e648ed64..62b9dabd 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -12,6 +13,7 @@ using Newtonsoft.Json; using StardewModdingAPI.AssemblyRewriters; using StardewModdingAPI.Events; using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.AssemblyRewriting; using StardewModdingAPI.Inheritance; using StardewValley; using Monitor = StardewModdingAPI.Framework.Monitor; @@ -38,8 +40,8 @@ namespace StardewModdingAPI /// <summary>The full path to the folder containing mods.</summary> private static readonly string ModPath = Path.Combine(Constants.ExecutionPath, "Mods"); - /// <summary>The full path to the folder containing cached SMAPI data.</summary> - private static readonly string CachePath = Path.Combine(Program.ModPath, ".cache"); + /// <summary>The name of the folder containing a mod's cached assembly data.</summary> + private static readonly string CacheDirName = ".cache"; /// <summary>The log file to which to write messages.</summary> private static readonly LogFileManager LogFile = new LogFileManager(Constants.LogPath); @@ -134,7 +136,6 @@ namespace StardewModdingAPI Program.Monitor.Log("Loading SMAPI..."); Console.Title = Constants.ConsoleTitle; Program.VerifyPath(Program.ModPath); - Program.VerifyPath(Program.CachePath); Program.VerifyPath(Constants.LogDir); if (!File.Exists(Program.GameExecutablePath)) { @@ -304,7 +305,7 @@ namespace StardewModdingAPI Program.Monitor.Log("Loading mods..."); // get assembly loader - ModAssemblyLoader modAssemblyLoader = new ModAssemblyLoader(Program.CachePath, Program.TargetPlatform, Program.Monitor); + ModAssemblyLoader modAssemblyLoader = new ModAssemblyLoader(Program.CacheDirName, Program.TargetPlatform, Program.Monitor); AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name); // load mods @@ -326,7 +327,14 @@ namespace StardewModdingAPI // get manifest path string manifestPath = Path.Combine(directory, "manifest.json"); + if (!File.Exists(manifestPath)) + { + Program.Monitor.Log($"Ignored folder \"{new DirectoryInfo(directory).Name}\" which doesn't have a manifest.json.", LogLevel.Warn); + continue; + } string errorPrefix = $"Couldn't load mod for manifest '{manifestPath}'"; + + // read manifest Manifest manifest; try { @@ -401,14 +409,15 @@ namespace StardewModdingAPI } } - // preprocess mod assemblies + // preprocess mod assemblies for compatibility + var processedAssemblies = new List<RewriteResult>(); { bool succeeded = true; foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll")) { try { - modAssemblyLoader.ProcessAssembly(assemblyPath); + processedAssemblies.Add(modAssemblyLoader.ProcessAssemblyUnlessCached(assemblyPath)); } catch (Exception ex) { @@ -420,13 +429,27 @@ namespace StardewModdingAPI if (!succeeded) continue; } + bool forceUseCachedAssembly = processedAssemblies.Any(p => p.UseCachedAssembly); // make sure DLLs are kept together for dependency resolution + if (processedAssemblies.Any(p => p.IsNewerThanCache)) + modAssemblyLoader.WriteCache(processedAssemblies, forceUseCachedAssembly); + + // get entry assembly path + string mainAssemblyPath; + { + RewriteResult mainProcessedAssembly = processedAssemblies.FirstOrDefault(p => p.OriginalAssemblyPath == Path.Combine(directory, manifest.EntryDll)); + if (mainProcessedAssembly == null) + { + Program.Monitor.Log($"{errorPrefix}: the specified mod DLL does not exist.", LogLevel.Error); + continue; + } + mainAssemblyPath = forceUseCachedAssembly ? mainProcessedAssembly.CachePaths.Assembly : mainProcessedAssembly.OriginalAssemblyPath; + } - // load assembly + // load entry assembly Assembly modAssembly; try { - string assemblyPath = Path.Combine(directory, manifest.EntryDll); - modAssembly = modAssemblyLoader.LoadCachedAssembly(assemblyPath); + modAssembly = Assembly.UnsafeLoadFrom(mainAssemblyPath); // unsafe load allows downloaded DLLs if (modAssembly.DefinedTypes.Count(x => x.BaseType == typeof(Mod)) == 0) { Program.Monitor.Log($"{errorPrefix}: the mod DLL does not contain an implementation of the 'Mod' class.", LogLevel.Error); diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj index 96eb038e..4e547fa0 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.csproj +++ b/src/StardewModdingAPI/StardewModdingAPI.csproj @@ -53,7 +53,6 @@ </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> <PlatformTarget>x86</PlatformTarget> - <OutputPath>bin\Debug\</OutputPath> <Prefer32Bit>false</Prefer32Bit> <DefineConstants>DEBUG;TRACE</DefineConstants> <UseVSHostingProcess>true</UseVSHostingProcess> @@ -65,7 +64,6 @@ </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> <PlatformTarget>x86</PlatformTarget> - <OutputPath>bin\Release\</OutputPath> <Prefer32Bit>false</Prefer32Bit> <OutputPath>$(SolutionDir)\..\bin\Release\SMAPI</OutputPath> <DocumentationFile>$(SolutionDir)\..\bin\Debug\SMAPI\StardewModdingAPI.xml</DocumentationFile> @@ -79,7 +77,6 @@ <PropertyGroup> <ApplicationIcon>icon.ico</ApplicationIcon> </PropertyGroup> - <Import Project="$(SolutionDir)\dependencies.targets" /> <ItemGroup> <Reference Include="Mono.Cecil, Version=0.9.6.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756, processorArchitecture=MSIL"> <HintPath>..\packages\Mono.Cecil.0.9.6.4\lib\net45\Mono.Cecil.dll</HintPath> @@ -107,6 +104,7 @@ <Reference Include="System.Numerics"> <Private>True</Private> </Reference> + <Reference Include="System.Runtime.Caching" /> <Reference Include="System.Windows.Forms" Condition="$(OS) == 'Windows_NT'" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> @@ -154,12 +152,17 @@ <Compile Include="Events\PlayerEvents.cs" /> <Compile Include="Events\TimeEvents.cs" /> <Compile Include="Extensions.cs" /> + <Compile Include="Framework\AssemblyRewriting\RewriteResult.cs" /> <Compile Include="Framework\AssemblyRewriting\CachePaths.cs" /> <Compile Include="Framework\AssemblyRewriting\AssemblyTypeRewriter.cs" /> + <Compile Include="Framework\AssemblyRewriting\CacheEntry.cs" /> <Compile Include="Framework\DeprecationLevel.cs" /> <Compile Include="Framework\DeprecationManager.cs" /> <Compile Include="Framework\InternalExtensions.cs" /> <Compile Include="Framework\ModAssemblyLoader.cs" /> + <Compile Include="Framework\Reflection\PrivateField.cs" /> + <Compile Include="Framework\Reflection\PrivateMethod.cs" /> + <Compile Include="Framework\Reflection\ReflectionHelper.cs" /> <Compile Include="IModHelper.cs" /> <Compile Include="Framework\LogFileManager.cs" /> <Compile Include="LogLevel.cs" /> @@ -181,6 +184,9 @@ <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Inheritance\SGame.cs" /> + <Compile Include="IPrivateField.cs" /> + <Compile Include="IPrivateMethod.cs" /> + <Compile Include="IReflectionHelper.cs" /> <Compile Include="Version.cs" /> </ItemGroup> <ItemGroup> @@ -221,6 +227,7 @@ <Name>StardewModdingAPI.AssemblyRewriters</Name> </ProjectReference> </ItemGroup> + <Import Project="$(SolutionDir)\crossplatform.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <PropertyGroup> <PostBuildEvent> diff --git a/src/StardewModdingAPI/unix-launcher.sh b/src/StardewModdingAPI/unix-launcher.sh index 0bfe0d5c..93e33c78 100644 --- a/src/StardewModdingAPI/unix-launcher.sh +++ b/src/StardewModdingAPI/unix-launcher.sh @@ -1,7 +1,7 @@ #!/bin/bash # MonoKickstart Shell Script # Written by Ethan "flibitijibibo" Lee -# Modified for StardewModdingAPI by Viz +# Modified for StardewModdingAPI by Viz and Pathoschild # Move to script's directory cd "`dirname "$0"`" @@ -28,15 +28,40 @@ if [ "$UNAME" == "Darwin" ]; then ln -sf mcs.bin.osx mcs cp StardewValley.bin.osx StardewModdingAPI.bin.osx - ./StardewModdingAPI.bin.osx $@ + open -a Terminal ./StardewModdingAPI.bin.osx $@ else + # choose launcher + LAUNCHER="" if [ "$ARCH" == "x86_64" ]; then ln -sf mcs.bin.x86_64 mcs cp StardewValley.bin.x86_64 StardewModdingAPI.bin.x86_64 - ./StardewModdingAPI.bin.x86_64 $@ + LAUNCHER="./StardewModdingAPI.bin.x86_64 $@" else ln -sf mcs.bin.x86 mcs cp StardewValley.bin.x86 StardewModdingAPI.bin.x86 - ./StardewModdingAPI.bin.x86 $@ + LAUNCHER="./StardewModdingAPI.bin.x86 $@" + fi + + # get cross-distro version of POSIX command + COMMAND="" + if command -v command 2>/dev/null; then + COMMAND="command -v" + elif type type 2>/dev/null; then + COMMAND="type" + fi + + # open SMAPI in terminal + if $COMMAND x-terminal-emulator 2>/dev/null; then + x-terminal-emulator -e "$LAUNCHER" + elif $COMMAND gnome-terminal 2>/dev/null; then + gnome-terminal -e "$LAUNCHER" + elif $COMMAND xterm 2>/dev/null; then + xterm -e "$LAUNCHER" + elif $COMMAND konsole 2>/dev/null; then + konsole -e "$LAUNCHER" + elif $COMMAND terminal 2>/dev/null; then + terminal -e "$LAUNCHER" + else + $LAUNCHER fi fi diff --git a/src/TrainerMod/ItemData/ISearchItem.cs b/src/TrainerMod/ItemData/ISearchItem.cs new file mode 100644 index 00000000..b2f7c2b8 --- /dev/null +++ b/src/TrainerMod/ItemData/ISearchItem.cs @@ -0,0 +1,21 @@ +namespace TrainerMod.ItemData +{ + /// <summary>An item that can be searched and added to the player's inventory through the console.</summary> + internal interface ISearchItem + { + /********* + ** Accessors + *********/ + /// <summary>Whether the item is valid.</summary> + bool IsValid { get; } + + /// <summary>The item ID.</summary> + int ID { get; } + + /// <summary>The item name.</summary> + string Name { get; } + + /// <summary>The item type.</summary> + ItemType Type { get; } + } +}
\ No newline at end of file diff --git a/src/TrainerMod/ItemData/ItemType.cs b/src/TrainerMod/ItemData/ItemType.cs new file mode 100644 index 00000000..2e049aa1 --- /dev/null +++ b/src/TrainerMod/ItemData/ItemType.cs @@ -0,0 +1,15 @@ +namespace TrainerMod.ItemData +{ + /// <summary>An item type that can be searched and added to the player through the console.</summary> + internal enum ItemType + { + /// <summary>Any object in <see cref="StardewValley.Game1.objectInformation"/> (except rings).</summary> + Object, + + /// <summary>A ring in <see cref="StardewValley.Game1.objectInformation"/>.</summary> + Ring, + + /// <summary>A weapon from <c>Data\weapons</c>.</summary> + Weapon + } +} diff --git a/src/TrainerMod/ItemData/SearchableObject.cs b/src/TrainerMod/ItemData/SearchableObject.cs new file mode 100644 index 00000000..30362f54 --- /dev/null +++ b/src/TrainerMod/ItemData/SearchableObject.cs @@ -0,0 +1,48 @@ +using StardewValley; + +namespace TrainerMod.ItemData +{ + /// <summary>An object that can be searched and added to the player's inventory through the console.</summary> + internal class SearchableObject : ISearchItem + { + /********* + ** Properties + *********/ + /// <summary>The underlying item.</summary> + private readonly Item Item; + + + /********* + ** Accessors + *********/ + /// <summary>Whether the item is valid.</summary> + public bool IsValid => this.Item != null && this.Item.Name != "Broken Item"; + + /// <summary>The item ID.</summary> + public int ID => this.Item.parentSheetIndex; + + /// <summary>The item name.</summary> + public string Name => this.Item.Name; + + /// <summary>The item type.</summary> + public ItemType Type => ItemType.Object; + + + /********* + ** Accessors + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="id">The item ID.</param> + public SearchableObject(int id) + { + try + { + this.Item = new Object(id, 1); + } + catch + { + // invalid + } + } + } +}
\ No newline at end of file diff --git a/src/TrainerMod/ItemData/SearchableRing.cs b/src/TrainerMod/ItemData/SearchableRing.cs new file mode 100644 index 00000000..7751e6aa --- /dev/null +++ b/src/TrainerMod/ItemData/SearchableRing.cs @@ -0,0 +1,48 @@ +using StardewValley.Objects; + +namespace TrainerMod.ItemData +{ + /// <summary>A ring that can be searched and added to the player's inventory through the console.</summary> + internal class SearchableRing : ISearchItem + { + /********* + ** Properties + *********/ + /// <summary>The underlying item.</summary> + private readonly Ring Ring; + + + /********* + ** Accessors + *********/ + /// <summary>Whether the item is valid.</summary> + public bool IsValid => this.Ring != null; + + /// <summary>The item ID.</summary> + public int ID => this.Ring.parentSheetIndex; + + /// <summary>The item name.</summary> + public string Name => this.Ring.Name; + + /// <summary>The item type.</summary> + public ItemType Type => ItemType.Ring; + + + /********* + ** Accessors + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="id">The ring ID.</param> + public SearchableRing(int id) + { + try + { + this.Ring = new Ring(id); + } + catch + { + // invalid + } + } + } +}
\ No newline at end of file diff --git a/src/TrainerMod/ItemData/SearchableWeapon.cs b/src/TrainerMod/ItemData/SearchableWeapon.cs new file mode 100644 index 00000000..cc9ef459 --- /dev/null +++ b/src/TrainerMod/ItemData/SearchableWeapon.cs @@ -0,0 +1,48 @@ +using StardewValley.Tools; + +namespace TrainerMod.ItemData +{ + /// <summary>A weapon that can be searched and added to the player's inventory through the console.</summary> + internal class SearchableWeapon : ISearchItem + { + /********* + ** Properties + *********/ + /// <summary>The underlying item.</summary> + private readonly MeleeWeapon Weapon; + + + /********* + ** Accessors + *********/ + /// <summary>Whether the item is valid.</summary> + public bool IsValid => this.Weapon != null; + + /// <summary>The item ID.</summary> + public int ID => this.Weapon.initialParentTileIndex; + + /// <summary>The item name.</summary> + public string Name => this.Weapon.Name; + + /// <summary>The item type.</summary> + public ItemType Type => ItemType.Weapon; + + + /********* + ** Accessors + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="id">The weapon ID.</param> + public SearchableWeapon(int id) + { + try + { + this.Weapon = new MeleeWeapon(id); + } + catch + { + // invalid + } + } + } +}
\ No newline at end of file diff --git a/src/TrainerMod/TrainerMod.cs b/src/TrainerMod/TrainerMod.cs index dda72564..f0c7549f 100644 --- a/src/TrainerMod/TrainerMod.cs +++ b/src/TrainerMod/TrainerMod.cs @@ -9,6 +9,7 @@ using StardewValley.Menus; using StardewValley.Objects; using StardewValley.Tools; using TrainerMod.Framework; +using TrainerMod.ItemData; using Object = StardewValley.Object; namespace TrainerMod @@ -39,7 +40,7 @@ namespace TrainerMod ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> - /// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param> + /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { this.RegisterCommands(); @@ -99,9 +100,7 @@ namespace TrainerMod Command.RegisterCommand("player_addmelee", "Gives the player a melee item | player_addmelee <item>", new[] { "?<item>" }).CommandFired += this.HandlePlayerAddMelee; Command.RegisterCommand("player_addring", "Gives the player a ring | player_addring <item>", new[] { "?<item>" }).CommandFired += this.HandlePlayerAddRing; - Command.RegisterCommand("out_items", "Outputs a list of items | out_items", new[] { "" }).CommandFired += this.HandleOutItems; - Command.RegisterCommand("out_melee", "Outputs a list of melee weapons | out_melee", new[] { "" }).CommandFired += this.HandleOutMelee; - Command.RegisterCommand("out_rings", "Outputs a list of rings | out_rings", new[] { "" }).CommandFired += this.HandleOutRings; + Command.RegisterCommand("list_items", "Lists items in the game data | list_items [search]", new[] { "(String)<search>" }).CommandFired += this.HandleListItems; Command.RegisterCommand("world_settime", "Sets the time to the specified value | world_settime <value>", new[] { "(Int32)<value> The target time [06:00 AM is 600]" }).CommandFired += this.HandleWorldSetTime; Command.RegisterCommand("world_freezetime", "Freezes or thaws time | world_freezetime <value>", new[] { "(0 - 1)<value> Whether or not to freeze time. 0 is thawed, 1 is frozen" }).CommandFired += this.HandleWorldFreezeTime; @@ -657,49 +656,19 @@ namespace TrainerMod this.LogObjectValueNotSpecified(); } - /// <summary>The event raised when the 'out_items' command is triggered.</summary> + /// <summary>The event raised when the 'list_items' command is triggered.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> - private void HandleOutItems(object sender, EventArgsCommand e) + private void HandleListItems(object sender, EventArgsCommand e) { - for (var itemID = 0; itemID < 1000; itemID++) - { - try - { - Item itemName = new Object(itemID, 1); - if (itemName.Name != "Error Item") - this.Monitor.Log($"{itemID} | {itemName.Name}", LogLevel.Info); - } - catch { } - } - } - - /// <summary>The event raised when the 'out_melee' command is triggered.</summary> - /// <param name="sender">The event sender.</param> - /// <param name="e">The event arguments.</param> - private void HandleOutMelee(object sender, EventArgsCommand e) - { - var data = Game1.content.Load<Dictionary<int, string>>("Data\\weapons"); - this.Monitor.Log("DATA\\WEAPONS: ", LogLevel.Info); - foreach (var pair in data) - this.Monitor.Log($"{pair.Key} | {pair.Value}", LogLevel.Info); - } + var matches = this.GetItems(e.Command.CalledArgs).ToArray(); - /// <summary>The event raised when the 'out_rings' command is triggered.</summary> - /// <param name="sender">The event sender.</param> - /// <param name="e">The event arguments.</param> - private void HandleOutRings(object sender, EventArgsCommand e) - { - for (var ringID = 0; ringID < 100; ringID++) - { - try - { - Item item = new Ring(ringID); - if (item.Name != "Error Item") - this.Monitor.Log($"{ringID} | {item.Name}", LogLevel.Info); - } - catch { } - } + // show matches + string summary = "Searching...\n"; + if (matches.Any()) + this.Monitor.Log(summary + this.GetTableString(matches, new[] { "type", "id", "name" }, val => new[] { val.Type.ToString(), val.ID.ToString(), val.Name }), LogLevel.Info); + else + this.Monitor.Log(summary + "No items found", LogLevel.Info); } /// <summary>The event raised when the 'world_downMineLevel' command is triggered.</summary> @@ -727,6 +696,88 @@ namespace TrainerMod } /**** + ** Helpers + ****/ + /// <summary>Get all items which can be searched and added to the player's inventory through the console.</summary> + /// <param name="searchWords">The search string to find.</param> + private IEnumerable<ISearchItem> GetItems(string[] searchWords) + { + // normalise search term + searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray(); + if (searchWords?.Any() == false) + searchWords = null; + + // find matches + return ( + from item in this.GetItems() + let term = $"{item.ID}|{item.Type}|{item.Name}" + where searchWords == null || searchWords.All(word => term.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) != -1) + select item + ); + } + + /// <summary>Get all items which can be searched and added to the player's inventory through the console.</summary> + private IEnumerable<ISearchItem> GetItems() + { + // objects + foreach (int id in Game1.objectInformation.Keys) + { + ISearchItem obj = id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange + ? new SearchableRing(id) + : (ISearchItem)new SearchableObject(id); + if (obj.IsValid) + yield return obj; + } + + // weapons + foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\weapons").Keys) + { + ISearchItem weapon = new SearchableWeapon(id); + if (weapon.IsValid) + yield return weapon; + } + } + + /// <summary>Get an ASCII table for a set of tabular data.</summary> + /// <typeparam name="T">The data type.</typeparam> + /// <param name="data">The data to display.</param> + /// <param name="header">The table header.</param> + /// <param name="getRow">Returns a set of fields for a data value.</param> + private string GetTableString<T>(IEnumerable<T> data, string[] header, Func<T, string[]> getRow) + { + // get table data + int[] widths = header.Select(p => p.Length).ToArray(); + string[][] rows = data + .Select(item => + { + string[] fields = getRow(item); + if (fields.Length != widths.Length) + throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}"); + + for (int i = 0; i < fields.Length; i++) + widths[i] = Math.Max(widths[i], fields[i].Length); + + return fields; + }) + .ToArray(); + + // render fields + List<string[]> lines = new List<string[]>(rows.Length + 2) + { + header, + header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray() + }; + lines.AddRange(rows); + + return string.Join( + Environment.NewLine, + lines.Select(line => string.Join(" | ", + line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray()) + ) + ); + } + + /**** ** Logging ****/ /// <summary>Log an error indicating a value must be specified.</summary> diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 229e6b4d..e262e135 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -102,6 +102,11 @@ <Link>Properties\GlobalAssemblyInfo.cs</Link> </Compile> <Compile Include="Framework\Extensions.cs" /> + <Compile Include="ItemData\ISearchItem.cs" /> + <Compile Include="ItemData\ItemType.cs" /> + <Compile Include="ItemData\SearchableObject.cs" /> + <Compile Include="ItemData\SearchableRing.cs" /> + <Compile Include="ItemData\SearchableWeapon.cs" /> <Compile Include="TrainerMod.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> @@ -127,4 +132,10 @@ <!-- if game path is invalid, show one user-friendly error instead of a slew of reference errors --> <Error Condition="!Exists('$(GamePath)')" Text="Failed to find the game install path automatically; edit the *.csproj file and manually add a <GamePath> setting with the full directory path containing the Stardew Valley executable." /> </Target> + <Target Name="AfterBuild" Condition="$(Configuration) == 'Debug'"> + <Copy SourceFiles="$(TargetDir)\$(TargetName).dll" DestinationFolder="$(GamePath)\Mods\TrainerMod" /> + <Copy SourceFiles="$(TargetDir)\$(TargetName).dll.mdb" DestinationFolder="$(GamePath)\Mods\TrainerMod" Condition="$(OS) != 'Windows_NT'" /> + <Copy SourceFiles="$(TargetDir)\$(TargetName).pdb" DestinationFolder="$(GamePath)\Mods\TrainerMod" Condition="$(OS) == 'Windows_NT'" /> + <Copy SourceFiles="$(TargetDir)\manifest.json" DestinationFolder="$(GamePath)\Mods\TrainerMod" /> + </Target> </Project>
\ No newline at end of file diff --git a/src/dependencies.targets b/src/crossplatform.targets index d5428967..0eb1c776 100644 --- a/src/dependencies.targets +++ b/src/crossplatform.targets @@ -8,6 +8,8 @@ <!-- Windows paths --> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley</GamePath> + <GamePath Condition="!Exists('$(GamePath)') AND $(OS) == 'Windows_NT'">$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 413150@InstallLocation)</GamePath> + <GamePath Condition="!Exists('$(GamePath)') AND $(OS) == 'Windows_NT'">$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GOG.com\Games\1453375253@PATH)</GamePath> </PropertyGroup> <Choose> <When Condition="$(OS) == 'Windows_NT'"> |